@azure/event-hubs 5.13.0-alpha.20240813.2 → 5.13.0-alpha.20240829.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 (285) hide show
  1. package/README.md +1 -1
  2. package/dist/browser/batchingPartitionChannel.js +1 -1
  3. package/dist/browser/batchingPartitionChannel.js.map +1 -1
  4. package/dist/browser/connectionContext.js +1 -1
  5. package/dist/browser/connectionContext.js.map +1 -1
  6. package/dist/browser/dataTransformer.js +1 -1
  7. package/dist/browser/dataTransformer.js.map +1 -1
  8. package/dist/browser/diagnostics/instrumentEventData.js +1 -1
  9. package/dist/browser/diagnostics/instrumentEventData.js.map +1 -1
  10. package/dist/browser/diagnostics/tracing.js +1 -1
  11. package/dist/browser/diagnostics/tracing.js.map +1 -1
  12. package/dist/browser/eventData.js +1 -1
  13. package/dist/browser/eventData.js.map +1 -1
  14. package/dist/browser/eventDataAdapter.js +1 -1
  15. package/dist/browser/eventDataAdapter.js.map +1 -1
  16. package/dist/browser/eventDataBatch.js +1 -1
  17. package/dist/browser/eventDataBatch.js.map +1 -1
  18. package/dist/browser/eventHubBufferedProducerClient.js +1 -1
  19. package/dist/browser/eventHubBufferedProducerClient.js.map +1 -1
  20. package/dist/browser/eventHubConsumerClient.js +1 -1
  21. package/dist/browser/eventHubConsumerClient.js.map +1 -1
  22. package/dist/browser/eventHubConsumerClientModels.js +1 -1
  23. package/dist/browser/eventHubConsumerClientModels.js.map +1 -1
  24. package/dist/browser/eventHubProducerClient.js +1 -1
  25. package/dist/browser/eventHubProducerClient.js.map +1 -1
  26. package/dist/browser/eventHubSender.js +1 -1
  27. package/dist/browser/eventHubSender.js.map +1 -1
  28. package/dist/browser/eventPosition.js +1 -1
  29. package/dist/browser/eventPosition.js.map +1 -1
  30. package/dist/browser/eventProcessor.js +1 -1
  31. package/dist/browser/eventProcessor.js.map +1 -1
  32. package/dist/browser/eventhubConnectionConfig.js +1 -1
  33. package/dist/browser/eventhubConnectionConfig.js.map +1 -1
  34. package/dist/browser/impl/awaitableQueue.js +1 -1
  35. package/dist/browser/impl/awaitableQueue.js.map +1 -1
  36. package/dist/browser/impl/partitionAssigner.js +1 -1
  37. package/dist/browser/impl/partitionAssigner.js.map +1 -1
  38. package/dist/browser/impl/partitionGate.js +1 -1
  39. package/dist/browser/impl/partitionGate.js.map +1 -1
  40. package/dist/browser/impl/partitionKeyToIdMapper.js +1 -1
  41. package/dist/browser/impl/partitionKeyToIdMapper.js.map +1 -1
  42. package/dist/browser/inMemoryCheckpointStore.js +1 -1
  43. package/dist/browser/inMemoryCheckpointStore.js.map +1 -1
  44. package/dist/browser/index.js +1 -1
  45. package/dist/browser/index.js.map +1 -1
  46. package/dist/browser/loadBalancerStrategies/balancedStrategy.js +1 -1
  47. package/dist/browser/loadBalancerStrategies/balancedStrategy.js.map +1 -1
  48. package/dist/browser/loadBalancerStrategies/greedyStrategy.js +1 -1
  49. package/dist/browser/loadBalancerStrategies/greedyStrategy.js.map +1 -1
  50. package/dist/browser/loadBalancerStrategies/loadBalancingStrategy.js +1 -1
  51. package/dist/browser/loadBalancerStrategies/loadBalancingStrategy.js.map +1 -1
  52. package/dist/browser/loadBalancerStrategies/unbalancedStrategy.js +1 -1
  53. package/dist/browser/loadBalancerStrategies/unbalancedStrategy.js.map +1 -1
  54. package/dist/browser/logger.js +1 -1
  55. package/dist/browser/logger.js.map +1 -1
  56. package/dist/browser/managementClient.js +1 -1
  57. package/dist/browser/managementClient.js.map +1 -1
  58. package/dist/browser/models/private.js +1 -1
  59. package/dist/browser/models/private.js.map +1 -1
  60. package/dist/browser/models/public.js +1 -1
  61. package/dist/browser/models/public.js.map +1 -1
  62. package/dist/browser/partitionProcessor.js +1 -1
  63. package/dist/browser/partitionProcessor.js.map +1 -1
  64. package/dist/browser/partitionPump.js +1 -1
  65. package/dist/browser/partitionPump.js.map +1 -1
  66. package/dist/browser/partitionReceiver.js +1 -1
  67. package/dist/browser/partitionReceiver.js.map +1 -1
  68. package/dist/browser/pumpManager.js +1 -1
  69. package/dist/browser/pumpManager.js.map +1 -1
  70. package/dist/browser/util/connectionStringUtils.js +1 -1
  71. package/dist/browser/util/connectionStringUtils.js.map +1 -1
  72. package/dist/browser/util/constants.js +1 -1
  73. package/dist/browser/util/constants.js.map +1 -1
  74. package/dist/browser/util/delayWithoutThrow.js +1 -1
  75. package/dist/browser/util/delayWithoutThrow.js.map +1 -1
  76. package/dist/browser/util/error.js +1 -1
  77. package/dist/browser/util/error.js.map +1 -1
  78. package/dist/browser/util/getPromiseParts.js +1 -1
  79. package/dist/browser/util/getPromiseParts.js.map +1 -1
  80. package/dist/browser/util/operationOptions.js +1 -1
  81. package/dist/browser/util/operationOptions.js.map +1 -1
  82. package/dist/browser/util/parseEndpoint.js +1 -1
  83. package/dist/browser/util/parseEndpoint.js.map +1 -1
  84. package/dist/browser/util/retries.js +1 -1
  85. package/dist/browser/util/retries.js.map +1 -1
  86. package/dist/browser/util/runtimeInfo-browser.mjs.map +1 -1
  87. package/dist/browser/util/runtimeInfo.js +1 -1
  88. package/dist/browser/util/timerLoop.js +1 -1
  89. package/dist/browser/util/timerLoop.js.map +1 -1
  90. package/dist/browser/util/typeGuards.js +1 -1
  91. package/dist/browser/util/typeGuards.js.map +1 -1
  92. package/dist/browser/util/utils.js +1 -1
  93. package/dist/browser/util/utils.js.map +1 -1
  94. package/dist/browser/withAuth.js +1 -1
  95. package/dist/browser/withAuth.js.map +1 -1
  96. package/dist/commonjs/batchingPartitionChannel.js +1 -1
  97. package/dist/commonjs/batchingPartitionChannel.js.map +1 -1
  98. package/dist/commonjs/connectionContext.js +1 -1
  99. package/dist/commonjs/connectionContext.js.map +1 -1
  100. package/dist/commonjs/dataTransformer.js +1 -1
  101. package/dist/commonjs/dataTransformer.js.map +1 -1
  102. package/dist/commonjs/diagnostics/instrumentEventData.js +1 -1
  103. package/dist/commonjs/diagnostics/instrumentEventData.js.map +1 -1
  104. package/dist/commonjs/diagnostics/tracing.js +1 -1
  105. package/dist/commonjs/diagnostics/tracing.js.map +1 -1
  106. package/dist/commonjs/eventData.js +1 -1
  107. package/dist/commonjs/eventData.js.map +1 -1
  108. package/dist/commonjs/eventDataAdapter.js +1 -1
  109. package/dist/commonjs/eventDataAdapter.js.map +1 -1
  110. package/dist/commonjs/eventDataBatch.js +1 -1
  111. package/dist/commonjs/eventDataBatch.js.map +1 -1
  112. package/dist/commonjs/eventHubBufferedProducerClient.js +1 -1
  113. package/dist/commonjs/eventHubBufferedProducerClient.js.map +1 -1
  114. package/dist/commonjs/eventHubConsumerClient.js +1 -1
  115. package/dist/commonjs/eventHubConsumerClient.js.map +1 -1
  116. package/dist/commonjs/eventHubConsumerClientModels.js +1 -1
  117. package/dist/commonjs/eventHubConsumerClientModels.js.map +1 -1
  118. package/dist/commonjs/eventHubProducerClient.js +1 -1
  119. package/dist/commonjs/eventHubProducerClient.js.map +1 -1
  120. package/dist/commonjs/eventHubSender.js +1 -1
  121. package/dist/commonjs/eventHubSender.js.map +1 -1
  122. package/dist/commonjs/eventPosition.js +1 -1
  123. package/dist/commonjs/eventPosition.js.map +1 -1
  124. package/dist/commonjs/eventProcessor.js +1 -1
  125. package/dist/commonjs/eventProcessor.js.map +1 -1
  126. package/dist/commonjs/eventhubConnectionConfig.js +1 -1
  127. package/dist/commonjs/eventhubConnectionConfig.js.map +1 -1
  128. package/dist/commonjs/impl/awaitableQueue.js +1 -1
  129. package/dist/commonjs/impl/awaitableQueue.js.map +1 -1
  130. package/dist/commonjs/impl/partitionAssigner.js +1 -1
  131. package/dist/commonjs/impl/partitionAssigner.js.map +1 -1
  132. package/dist/commonjs/impl/partitionGate.js +1 -1
  133. package/dist/commonjs/impl/partitionGate.js.map +1 -1
  134. package/dist/commonjs/impl/partitionKeyToIdMapper.js +1 -1
  135. package/dist/commonjs/impl/partitionKeyToIdMapper.js.map +1 -1
  136. package/dist/commonjs/inMemoryCheckpointStore.js +1 -1
  137. package/dist/commonjs/inMemoryCheckpointStore.js.map +1 -1
  138. package/dist/commonjs/index.js +1 -1
  139. package/dist/commonjs/index.js.map +1 -1
  140. package/dist/commonjs/loadBalancerStrategies/balancedStrategy.js +1 -1
  141. package/dist/commonjs/loadBalancerStrategies/balancedStrategy.js.map +1 -1
  142. package/dist/commonjs/loadBalancerStrategies/greedyStrategy.js +1 -1
  143. package/dist/commonjs/loadBalancerStrategies/greedyStrategy.js.map +1 -1
  144. package/dist/commonjs/loadBalancerStrategies/loadBalancingStrategy.js +1 -1
  145. package/dist/commonjs/loadBalancerStrategies/loadBalancingStrategy.js.map +1 -1
  146. package/dist/commonjs/loadBalancerStrategies/unbalancedStrategy.js +1 -1
  147. package/dist/commonjs/loadBalancerStrategies/unbalancedStrategy.js.map +1 -1
  148. package/dist/commonjs/logger.js +1 -1
  149. package/dist/commonjs/logger.js.map +1 -1
  150. package/dist/commonjs/managementClient.js +1 -1
  151. package/dist/commonjs/managementClient.js.map +1 -1
  152. package/dist/commonjs/models/private.js +1 -1
  153. package/dist/commonjs/models/private.js.map +1 -1
  154. package/dist/commonjs/models/public.js +1 -1
  155. package/dist/commonjs/models/public.js.map +1 -1
  156. package/dist/commonjs/partitionProcessor.js +1 -1
  157. package/dist/commonjs/partitionProcessor.js.map +1 -1
  158. package/dist/commonjs/partitionPump.js +1 -1
  159. package/dist/commonjs/partitionPump.js.map +1 -1
  160. package/dist/commonjs/partitionReceiver.js +1 -1
  161. package/dist/commonjs/partitionReceiver.js.map +1 -1
  162. package/dist/commonjs/pumpManager.js +1 -1
  163. package/dist/commonjs/pumpManager.js.map +1 -1
  164. package/dist/commonjs/tsdoc-metadata.json +1 -1
  165. package/dist/commonjs/util/connectionStringUtils.js +1 -1
  166. package/dist/commonjs/util/connectionStringUtils.js.map +1 -1
  167. package/dist/commonjs/util/constants.js +1 -1
  168. package/dist/commonjs/util/constants.js.map +1 -1
  169. package/dist/commonjs/util/delayWithoutThrow.js +1 -1
  170. package/dist/commonjs/util/delayWithoutThrow.js.map +1 -1
  171. package/dist/commonjs/util/error.js +1 -1
  172. package/dist/commonjs/util/error.js.map +1 -1
  173. package/dist/commonjs/util/getPromiseParts.js +1 -1
  174. package/dist/commonjs/util/getPromiseParts.js.map +1 -1
  175. package/dist/commonjs/util/operationOptions.js +1 -1
  176. package/dist/commonjs/util/operationOptions.js.map +1 -1
  177. package/dist/commonjs/util/parseEndpoint.js +1 -1
  178. package/dist/commonjs/util/parseEndpoint.js.map +1 -1
  179. package/dist/commonjs/util/retries.js +1 -1
  180. package/dist/commonjs/util/retries.js.map +1 -1
  181. package/dist/commonjs/util/runtimeInfo.js +1 -1
  182. package/dist/commonjs/util/runtimeInfo.js.map +1 -1
  183. package/dist/commonjs/util/timerLoop.js +1 -1
  184. package/dist/commonjs/util/timerLoop.js.map +1 -1
  185. package/dist/commonjs/util/typeGuards.js +1 -1
  186. package/dist/commonjs/util/typeGuards.js.map +1 -1
  187. package/dist/commonjs/util/utils.js +1 -1
  188. package/dist/commonjs/util/utils.js.map +1 -1
  189. package/dist/commonjs/withAuth.js +1 -1
  190. package/dist/commonjs/withAuth.js.map +1 -1
  191. package/dist/esm/batchingPartitionChannel.js +1 -1
  192. package/dist/esm/batchingPartitionChannel.js.map +1 -1
  193. package/dist/esm/connectionContext.js +1 -1
  194. package/dist/esm/connectionContext.js.map +1 -1
  195. package/dist/esm/dataTransformer.js +1 -1
  196. package/dist/esm/dataTransformer.js.map +1 -1
  197. package/dist/esm/diagnostics/instrumentEventData.js +1 -1
  198. package/dist/esm/diagnostics/instrumentEventData.js.map +1 -1
  199. package/dist/esm/diagnostics/tracing.js +1 -1
  200. package/dist/esm/diagnostics/tracing.js.map +1 -1
  201. package/dist/esm/eventData.js +1 -1
  202. package/dist/esm/eventData.js.map +1 -1
  203. package/dist/esm/eventDataAdapter.js +1 -1
  204. package/dist/esm/eventDataAdapter.js.map +1 -1
  205. package/dist/esm/eventDataBatch.js +1 -1
  206. package/dist/esm/eventDataBatch.js.map +1 -1
  207. package/dist/esm/eventHubBufferedProducerClient.js +1 -1
  208. package/dist/esm/eventHubBufferedProducerClient.js.map +1 -1
  209. package/dist/esm/eventHubConsumerClient.js +1 -1
  210. package/dist/esm/eventHubConsumerClient.js.map +1 -1
  211. package/dist/esm/eventHubConsumerClientModels.js +1 -1
  212. package/dist/esm/eventHubConsumerClientModels.js.map +1 -1
  213. package/dist/esm/eventHubProducerClient.js +1 -1
  214. package/dist/esm/eventHubProducerClient.js.map +1 -1
  215. package/dist/esm/eventHubSender.js +1 -1
  216. package/dist/esm/eventHubSender.js.map +1 -1
  217. package/dist/esm/eventPosition.js +1 -1
  218. package/dist/esm/eventPosition.js.map +1 -1
  219. package/dist/esm/eventProcessor.js +1 -1
  220. package/dist/esm/eventProcessor.js.map +1 -1
  221. package/dist/esm/eventhubConnectionConfig.js +1 -1
  222. package/dist/esm/eventhubConnectionConfig.js.map +1 -1
  223. package/dist/esm/impl/awaitableQueue.js +1 -1
  224. package/dist/esm/impl/awaitableQueue.js.map +1 -1
  225. package/dist/esm/impl/partitionAssigner.js +1 -1
  226. package/dist/esm/impl/partitionAssigner.js.map +1 -1
  227. package/dist/esm/impl/partitionGate.js +1 -1
  228. package/dist/esm/impl/partitionGate.js.map +1 -1
  229. package/dist/esm/impl/partitionKeyToIdMapper.js +1 -1
  230. package/dist/esm/impl/partitionKeyToIdMapper.js.map +1 -1
  231. package/dist/esm/inMemoryCheckpointStore.js +1 -1
  232. package/dist/esm/inMemoryCheckpointStore.js.map +1 -1
  233. package/dist/esm/index.js +1 -1
  234. package/dist/esm/index.js.map +1 -1
  235. package/dist/esm/loadBalancerStrategies/balancedStrategy.js +1 -1
  236. package/dist/esm/loadBalancerStrategies/balancedStrategy.js.map +1 -1
  237. package/dist/esm/loadBalancerStrategies/greedyStrategy.js +1 -1
  238. package/dist/esm/loadBalancerStrategies/greedyStrategy.js.map +1 -1
  239. package/dist/esm/loadBalancerStrategies/loadBalancingStrategy.js +1 -1
  240. package/dist/esm/loadBalancerStrategies/loadBalancingStrategy.js.map +1 -1
  241. package/dist/esm/loadBalancerStrategies/unbalancedStrategy.js +1 -1
  242. package/dist/esm/loadBalancerStrategies/unbalancedStrategy.js.map +1 -1
  243. package/dist/esm/logger.js +1 -1
  244. package/dist/esm/logger.js.map +1 -1
  245. package/dist/esm/managementClient.js +1 -1
  246. package/dist/esm/managementClient.js.map +1 -1
  247. package/dist/esm/models/private.js +1 -1
  248. package/dist/esm/models/private.js.map +1 -1
  249. package/dist/esm/models/public.js +1 -1
  250. package/dist/esm/models/public.js.map +1 -1
  251. package/dist/esm/partitionProcessor.js +1 -1
  252. package/dist/esm/partitionProcessor.js.map +1 -1
  253. package/dist/esm/partitionPump.js +1 -1
  254. package/dist/esm/partitionPump.js.map +1 -1
  255. package/dist/esm/partitionReceiver.js +1 -1
  256. package/dist/esm/partitionReceiver.js.map +1 -1
  257. package/dist/esm/pumpManager.js +1 -1
  258. package/dist/esm/pumpManager.js.map +1 -1
  259. package/dist/esm/util/connectionStringUtils.js +1 -1
  260. package/dist/esm/util/connectionStringUtils.js.map +1 -1
  261. package/dist/esm/util/constants.js +1 -1
  262. package/dist/esm/util/constants.js.map +1 -1
  263. package/dist/esm/util/delayWithoutThrow.js +1 -1
  264. package/dist/esm/util/delayWithoutThrow.js.map +1 -1
  265. package/dist/esm/util/error.js +1 -1
  266. package/dist/esm/util/error.js.map +1 -1
  267. package/dist/esm/util/getPromiseParts.js +1 -1
  268. package/dist/esm/util/getPromiseParts.js.map +1 -1
  269. package/dist/esm/util/operationOptions.js +1 -1
  270. package/dist/esm/util/operationOptions.js.map +1 -1
  271. package/dist/esm/util/parseEndpoint.js +1 -1
  272. package/dist/esm/util/parseEndpoint.js.map +1 -1
  273. package/dist/esm/util/retries.js +1 -1
  274. package/dist/esm/util/retries.js.map +1 -1
  275. package/dist/esm/util/runtimeInfo.js +1 -1
  276. package/dist/esm/util/runtimeInfo.js.map +1 -1
  277. package/dist/esm/util/timerLoop.js +1 -1
  278. package/dist/esm/util/timerLoop.js.map +1 -1
  279. package/dist/esm/util/typeGuards.js +1 -1
  280. package/dist/esm/util/typeGuards.js.map +1 -1
  281. package/dist/esm/util/utils.js +1 -1
  282. package/dist/esm/util/utils.js.map +1 -1
  283. package/dist/esm/withAuth.js +1 -1
  284. package/dist/esm/withAuth.js.map +1 -1
  285. package/package.json +8 -10
@@ -1 +1 @@
1
- {"version":3,"file":"loadBalancingStrategy.js","sourceRoot":"","sources":["../../../src/loadBalancerStrategies/loadBalancingStrategy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AA+CtC;;;;;;;;;GASG;AACH,SAAS,4BAA4B,CACnC,qBAAsD,EACtD,sBAA8B;IAE9B,MAAM,2BAA2B,GAAoC,IAAI,GAAG,EAAE,CAAC;IAC/E,qBAAqB,CAAC,OAAO,CAAC,CAAC,kBAAsC,EAAE,WAAmB,EAAE,EAAE;QAC5F,6DAA6D;QAC7D,IACE,OAAO,kBAAkB,CAAC,oBAAoB,KAAK,WAAW;YAC9D,kBAAkB,CAAC,oBAAoB,KAAK,IAAI,EAChD,CAAC;YACD,OAAO;QACT,CAAC;QAED,MAAM,yBAAyB,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,kBAAkB,CAAC,oBAAoB,CAAC;QACvF,IAAI,yBAAyB,GAAG,sBAAsB,IAAI,kBAAkB,CAAC,OAAO,EAAE,CAAC;YACrF,2BAA2B,CAAC,GAAG,CAAC,WAAW,EAAE,kBAAkB,CAAC,CAAC;QACnE,CAAC;IACH,CAAC,CAAC,CAAC;IAEH,OAAO,2BAA2B,CAAC;AACrC,CAAC;AAED;;;;;;GAMG;AACH,SAAS,2BAA2B,CAClC,mBAAsD,EACtD,YAAsB;IAEtB,2FAA2F;IAC3F,yBAAyB;IACzB,MAAM,qBAAqB,GAAG,IAAI,CAAC,KAAK,CAAC,YAAY,CAAC,MAAM,GAAG,mBAAmB,CAAC,IAAI,CAAC,CAAC;IAEzF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B,wCAAwC,EACxC,mBAAmB,CAAC,GAAG,CAAC,OAAO,CAAE,CAAC,MAAM,EACxC,oBAAoB,CACrB,CAAC;IAEF,IAAI,yBAAyB,IAAI,CAAC,EAAE,CAAC;QACnC,OAAO,EAAE,CAAC;IACZ,CAAC;IAED,MAAM,iBAAiB,GAAa,EAAE,CAAC;IACvC,MAAM,qBAAqB,GAAG,YAAY,CAAC,MAAM,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC,2BAA2B,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC;IAEhG,iDAAiD;IACjD,OAAO,IAAI,CAAC,GAAG,CAAC,yBAAyB,EAAE,qBAAqB,CAAC,MAAM,CAAC,EAAE,CAAC;QACzE,MAAM,YAAY,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,qBAAqB,CAAC,MAAM,CAAC,CAAC;QAC9E,iBAAiB,CAAC,IAAI,CAAC,qBAAqB,CAAC,MAAM,CAAC,YAAY,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;QACzE,yBAAyB,EAAE,CAAC;IAC9B,CAAC;IAED,IAAI,yBAAyB,KAAK,CAAC,EAAE,CAAC;QACpC,OAAO,iBAAiB,CAAC;IAC3B,CAAC;IAED,iEAAiE;IACjE,MAAM,iBAAiB,GAAG,qBAAqB,CAC7C,yBAAyB,EACzB,qBAAqB,EACrB,wCAAwC,EACxC,OAAO,EACP,mBAAmB,CACpB,CAAC;IAEF,OAAO,iBAAiB,CAAC,MAAM,CAAC,iBAAiB,CAAC,CAAC;AACrD,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { PartitionOwnership } from \"../eventProcessor.js\";\nimport { logger } from \"../logger.js\";\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"]}
1
+ {"version":3,"file":"loadBalancingStrategy.js","sourceRoot":"","sources":["../../../src/loadBalancerStrategies/loadBalancingStrategy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AA+CtC;;;;;;;;;GASG;AACH,SAAS,4BAA4B,CACnC,qBAAsD,EACtD,sBAA8B;IAE9B,MAAM,2BAA2B,GAAoC,IAAI,GAAG,EAAE,CAAC;IAC/E,qBAAqB,CAAC,OAAO,CAAC,CAAC,kBAAsC,EAAE,WAAmB,EAAE,EAAE;QAC5F,6DAA6D;QAC7D,IACE,OAAO,kBAAkB,CAAC,oBAAoB,KAAK,WAAW;YAC9D,kBAAkB,CAAC,oBAAoB,KAAK,IAAI,EAChD,CAAC;YACD,OAAO;QACT,CAAC;QAED,MAAM,yBAAyB,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,kBAAkB,CAAC,oBAAoB,CAAC;QACvF,IAAI,yBAAyB,GAAG,sBAAsB,IAAI,kBAAkB,CAAC,OAAO,EAAE,CAAC;YACrF,2BAA2B,CAAC,GAAG,CAAC,WAAW,EAAE,kBAAkB,CAAC,CAAC;QACnE,CAAC;IACH,CAAC,CAAC,CAAC;IAEH,OAAO,2BAA2B,CAAC;AACrC,CAAC;AAED;;;;;;GAMG;AACH,SAAS,2BAA2B,CAClC,mBAAsD,EACtD,YAAsB;IAEtB,2FAA2F;IAC3F,yBAAyB;IACzB,MAAM,qBAAqB,GAAG,IAAI,CAAC,KAAK,CAAC,YAAY,CAAC,MAAM,GAAG,mBAAmB,CAAC,IAAI,CAAC,CAAC;IAEzF,+FAA+F;IAC/F,iGAAiG;IACjG,oBAAoB;IACp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OAAO,CAAE,CAAC,MAAM,EACxC,oBAAoB,CACrB,CAAC;IAEF,IAAI,yBAAyB,IAAI,CAAC,EAAE,CAAC;QACnC,OAAO,EAAE,CAAC;IACZ,CAAC;IAED,MAAM,iBAAiB,GAAa,EAAE,CAAC;IACvC,MAAM,qBAAqB,GAAG,YAAY,CAAC,MAAM,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC,2BAA2B,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC;IAEhG,iDAAiD;IACjD,OAAO,IAAI,CAAC,GAAG,CAAC,yBAAyB,EAAE,qBAAqB,CAAC,MAAM,CAAC,EAAE,CAAC;QACzE,MAAM,YAAY,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,qBAAqB,CAAC,MAAM,CAAC,CAAC;QAC9E,iBAAiB,CAAC,IAAI,CAAC,qBAAqB,CAAC,MAAM,CAAC,YAAY,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;QACzE,yBAAyB,EAAE,CAAC;IAC9B,CAAC;IAED,IAAI,yBAAyB,KAAK,CAAC,EAAE,CAAC;QACpC,OAAO,iBAAiB,CAAC;IAC3B,CAAC;IAED,iEAAiE;IACjE,MAAM,iBAAiB,GAAG,qBAAqB,CAC7C,yBAAyB,EACzB,qBAAqB,EACrB,wCAAwC,EACxC,OAAO,EACP,mBAAmB,CACpB,CAAC;IAEF,OAAO,iBAAiB,CAAC,MAAM,CAAC,iBAAiB,CAAC,CAAC;AACrD,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { PartitionOwnership } from \"../eventProcessor.js\";\nimport { logger } from \"../logger.js\";\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"]}
@@ -1,5 +1,5 @@
1
1
  // Copyright (c) Microsoft Corporation.
2
- // Licensed under the MIT license.
2
+ // Licensed under the MIT License.
3
3
  /**
4
4
  * The UnbalancedLoadBalancingStrategy does no actual load balancing.
5
5
  * It is intended to be used when you want to avoid load balancing
@@ -1 +1 @@
1
- {"version":3,"file":"unbalancedStrategy.js","sourceRoot":"","sources":["../../../src/loadBalancerStrategies/unbalancedStrategy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAKlC;;;;;GAKG;AACH,MAAM,OAAO,+BAA+B;IAC1C;;;;;;;OAOG;IACI,oBAAoB,CACzB,WAAmB,EACnB,6BAA8D,EAC9D,YAAsB;QAEtB,OAAO,YAAY,CAAC;IACtB,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { LoadBalancingStrategy } from \"./loadBalancingStrategy.js\";\nimport { PartitionOwnership } from \"../eventProcessor.js\";\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"]}
1
+ {"version":3,"file":"unbalancedStrategy.js","sourceRoot":"","sources":["../../../src/loadBalancerStrategies/unbalancedStrategy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAKlC;;;;;GAKG;AACH,MAAM,OAAO,+BAA+B;IAC1C;;;;;;;OAOG;IACI,oBAAoB,CACzB,WAAmB,EACnB,6BAA8D,EAC9D,YAAsB;QAEtB,OAAO,YAAY,CAAC;IACtB,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { LoadBalancingStrategy } from \"./loadBalancingStrategy.js\";\nimport { PartitionOwnership } from \"../eventProcessor.js\";\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"]}
@@ -1,5 +1,5 @@
1
1
  // Copyright (c) Microsoft Corporation.
2
- // Licensed under the MIT license.
2
+ // Licensed under the MIT License.
3
3
  import { createClientLogger } from "@azure/logger";
4
4
  import { isObjectWithProperties } from "@azure/core-util";
5
5
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"logger.js","sourceRoot":"","sources":["../../src/logger.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAA8B,kBAAkB,EAAY,MAAM,eAAe,CAAC;AACzF,OAAO,EAAE,sBAAsB,EAAE,MAAM,kBAAkB,CAAC;AAE1D;;;GAGG;AACH,MAAM,CAAC,MAAM,MAAM,GAAG,kBAAkB,CAAC,YAAY,CAAC,CAAC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iBAAiB,CAAC,WAAW,EAAE,MAAM,EAAE,SAAS,CAAC;KAC3D,CAAC;AACJ,CAAC;AAED,gBAAgB;AAChB,MAAM,UAAU,MAAM,CAAC,GAAY;IACjC,IAAI,CAAC,SAAS,CAAC,GAAG,EAAE,SAAS,EAAE,CAAC,CAAC,CAAC;AACpC,CAAC","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"]}
1
+ {"version":3,"file":"logger.js","sourceRoot":"","sources":["../../src/logger.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAA8B,kBAAkB,EAAY,MAAM,eAAe,CAAC;AACzF,OAAO,EAAE,sBAAsB,EAAE,MAAM,kBAAkB,CAAC;AAE1D;;;GAGG;AACH,MAAM,CAAC,MAAM,MAAM,GAAG,kBAAkB,CAAC,YAAY,CAAC,CAAC;AAEvD;;;;GAIG;AACH,MAAM,UAAU,kBAAkB,CAAC,KAAc;IAC/C,IAAI,sBAAsB,CAAC,KAAK,EAAE,CAAC,OAAO,CAAC,CAAC,EAAE,CAAC;QAC7C,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;IAC9B,CAAC;AACH,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,uBAAuB,CACrC,UAAkB,EAClB,YAAoB,EACpB,WAAmB;IAEnB,OAAO,IAAI,YAAY,eAAe,WAAW,IAAI,UAAU,EAAE,CAAC;AACpE,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,qBAAqB,CAAC,QAAgB,EAAE,YAAoB;IAC1E,OAAO,IAAI,YAAY,YAAY,QAAQ,EAAE,CAAC;AAChD,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,yBAAyB,CAAC,YAAoB;IAC5D,OAAO,IAAI,YAAY,cAAc,CAAC;AACxC,CAAC;AASD,SAAS,iBAAiB,CACxB,WAAwB,EACxB,MAAc,EACd,KAAoB;IAEpB,OAAO,CAAC,GAAQ,EAAE,GAAG,IAAW,EAAE,EAAE,CAClC,WAAW,CAAC,KAAK,CAAC,CAChB,GAAG,CAAC,OAAO,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAC,CAAC,GAAG,MAAM,KAAK,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,EACpE,GAAG,IAAI,CACR,CAAC;AACN,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,kBAAkB,CAAC,WAAwB,EAAE,MAAc;IACzE,OAAO;QACL,IAAI,EAAE,iBAAiB,CAAC,WAAW,EAAE,MAAM,EAAE,MAAM,CAAC;QACpD,KAAK,EAAE,iBAAiB,CAAC,WAAW,EAAE,MAAM,EAAE,OAAO,CAAC;QACtD,OAAO,EAAE,iBAAiB,CAAC,WAAW,EAAE,MAAM,EAAE,SAAS,CAAC;QAC1D,OAAO,EAAE,iBAAiB,CAAC,WAAW,EAAE,MAAM,EAAE,SAAS,CAAC;KAC3D,CAAC;AACJ,CAAC;AAED,gBAAgB;AAChB,MAAM,UAAU,MAAM,CAAC,GAAY;IACjC,IAAI,CAAC,SAAS,CAAC,GAAG,EAAE,SAAS,EAAE,CAAC,CAAC,CAAC;AACpC,CAAC","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"]}
@@ -1,5 +1,5 @@
1
1
  // Copyright (c) Microsoft Corporation.
2
- // Licensed under the MIT license.
2
+ // Licensed under the MIT License.
3
3
  import { Constants, RequestResponseLink, RetryOperationType, defaultCancellableLock, isSasTokenProvider, retry, translate, } from "@azure/core-amqp";
4
4
  import { ReceiverEvents, SenderEvents, } from "rhea-promise";
5
5
  import { logErrorStackTrace, createSimpleLogger, logger, createManagementLogPrefix, } from "./logger.js";
@@ -1 +1 @@
1
- {"version":3,"file":"managementClient.js","sourceRoot":"","sources":["../../src/managementClient.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EACL,SAAS,EACT,mBAAmB,EAEnB,kBAAkB,EAGlB,sBAAsB,EACtB,kBAAkB,EAClB,KAAK,EACL,SAAS,GACV,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAGL,cAAc,EAEd,YAAY,GAEb,MAAM,cAAc,CAAC;AACtB,O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,UAAU,GAAG,aAAa,EAAE,CAAC;gBACvC,CAAC;gBAED,OAAO,IAAI,CAAC,eAAgB,CAAC,WAAW,CAAC,OAAO,EAAE,kBAAkB,CAAC,CAAC;YACxE,CAAC,CAAC;YAEF,MAAM,MAAM,GAAyB,MAAM,CAAC,gBAAgB,CAC1D;gBACE,SAAS,EAAE,oBAAoB;gBAC/B,aAAa,EAAE,kBAAkB,CAAC,UAAU;gBAC5C,WAAW,EAAE,WAAW;gBACxB,YAAY,EAAE,YAAY;aAC3B,EACD;gBACE,YAAY,EAAE;oBACZ,UAAU,EAAE,IAAI;oBAChB,GAAG,EAAE,GAAG,EAAE;wBACR,OAAO,IAAI,CAAC,QAAQ,CAAC,YAAY,CAAC;oBACpC,CAAC;iBACF;aACF,CACsB,CAAC;YAC1B,OAAO,CAAC,MAAM,KAAK,CAAU,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC;QAC7C,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,MAAM,eAAe,GAAG,SAAS,CAAC,GAAG,CAAC,CAAC;YACvC,MAAM,CAAC,OAAO,CACZ,oFAAoF,EACpF,GAAG,eAAe,aAAf,eAAe,uBAAf,eAAe,CAAE,IAAI,KAAK,eAAe,aAAf,eAAe,uBAAf,eAAe,CAAE,OAAO,EAAE,CACxD,CAAC;YACF,kBAAkB,CAAC,eAAe,CAAC,CAAC;YACpC,MAAM,eAAe,CAAC;QACxB,CAAC;IACH,CAAC;IAEO,8BAA8B;QACpC,OAAO,IAAI,CAAC,eAAgB,IAAI,IAAI,CAAC,eAAgB,CAAC,MAAM,EAAE,CAAC;IACjE,CAAC;CACF","sourcesContent":["// 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.js\";\nimport { throwErrorIfConnectionClosed, throwTypeErrorIfParameterMissing } from \"./util/error.js\";\nimport { AbortSignalLike } from \"@azure/abort-controller\";\nimport { AccessToken } from \"@azure/core-auth\";\nimport { ConnectionContext } from \"./connectionContext.js\";\nimport { OperationOptions } from \"./util/operationOptions.js\";\nimport { toSpanOptions, tracingClient } from \"./diagnostics/tracing.js\";\nimport { getRetryAttemptTimeoutInMs } from \"./util/retries.js\";\nimport { TimerLoop } from \"./util/timerLoop.js\";\nimport { withAuth } from \"./withAuth.js\";\nimport { getRandomName } from \"./util/utils.js\";\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"]}
1
+ {"version":3,"file":"managementClient.js","sourceRoot":"","sources":["../../src/managementClient.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EACL,SAAS,EACT,mBAAmB,EAEnB,kBAAkB,EAGlB,sBAAsB,EACtB,kBAAkB,EAClB,KAAK,EACL,SAAS,GACV,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAGL,cAAc,EAEd,YAAY,GAEb,MAAM,cAAc,CAAC;AACtB,OAAO,EACL,kBAAkB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a,EAAE,CAAC;gBACvC,CAAC;gBAED,OAAO,IAAI,CAAC,eAAgB,CAAC,WAAW,CAAC,OAAO,EAAE,kBAAkB,CAAC,CAAC;YACxE,CAAC,CAAC;YAEF,MAAM,MAAM,GAAyB,MAAM,CAAC,gBAAgB,CAC1D;gBACE,SAAS,EAAE,oBAAoB;gBAC/B,aAAa,EAAE,kBAAkB,CAAC,UAAU;gBAC5C,WAAW,EAAE,WAAW;gBACxB,YAAY,EAAE,YAAY;aAC3B,EACD;gBACE,YAAY,EAAE;oBACZ,UAAU,EAAE,IAAI;oBAChB,GAAG,EAAE,GAAG,EAAE;wBACR,OAAO,IAAI,CAAC,QAAQ,CAAC,YAAY,CAAC;oBACpC,CAAC;iBACF;aACF,CACsB,CAAC;YAC1B,OAAO,CAAC,MAAM,KAAK,CAAU,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC;QAC7C,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,MAAM,eAAe,GAAG,SAAS,CAAC,GAAG,CAAC,CAAC;YACvC,MAAM,CAAC,OAAO,CACZ,oFAAoF,EACpF,GAAG,eAAe,aAAf,eAAe,uBAAf,eAAe,CAAE,IAAI,KAAK,eAAe,aAAf,eAAe,uBAAf,eAAe,CAAE,OAAO,EAAE,CACxD,CAAC;YACF,kBAAkB,CAAC,eAAe,CAAC,CAAC;YACpC,MAAM,eAAe,CAAC;QACxB,CAAC;IACH,CAAC;IAEO,8BAA8B;QACpC,OAAO,IAAI,CAAC,eAAgB,IAAI,IAAI,CAAC,eAAgB,CAAC,MAAM,EAAE,CAAC;IACjE,CAAC;CACF","sourcesContent":["// 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.js\";\nimport { throwErrorIfConnectionClosed, throwTypeErrorIfParameterMissing } from \"./util/error.js\";\nimport { AbortSignalLike } from \"@azure/abort-controller\";\nimport { AccessToken } from \"@azure/core-auth\";\nimport { ConnectionContext } from \"./connectionContext.js\";\nimport { OperationOptions } from \"./util/operationOptions.js\";\nimport { toSpanOptions, tracingClient } from \"./diagnostics/tracing.js\";\nimport { getRetryAttemptTimeoutInMs } from \"./util/retries.js\";\nimport { TimerLoop } from \"./util/timerLoop.js\";\nimport { withAuth } from \"./withAuth.js\";\nimport { getRandomName } from \"./util/utils.js\";\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"]}
@@ -1,4 +1,4 @@
1
1
  // Copyright (c) Microsoft Corporation.
2
- // Licensed under the MIT license.
2
+ // Licensed under the MIT License.
3
3
  import { idempotentProducerAmqpPropertyNames } from "../util/constants.js";
4
4
  //# sourceMappingURL=private.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"private.js","sourceRoot":"","sources":["../../../src/models/private.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAMlC,OAAO,EAAE,mCAAmC,EAAE,MAAM,sBAAsB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { LoadBalancingStrategy } from \"../loadBalancerStrategies/loadBalancingStrategy.js\";\nimport { RetryOptions } from \"@azure/core-amqp\";\nimport { Typed } from \"rhea-promise\";\nimport { SubscribeOptions } from \"../eventHubConsumerClientModels.js\";\nimport { idempotentProducerAmqpPropertyNames } from \"../util/constants.js\";\n\n/**\n * The set of options to configure the behavior of an `EventHubProducer`.\n * These can be specified when creating the producer via the `createProducer` method.\n * - `partitionId` : The string identifier of the partition that the producer can be bound to.\n * - `retryOptions` : The retry options used to govern retry attempts when an issue is encountered while sending events.\n * A simple usage can be `{ \"maxRetries\": 4 }`.\n * @internal\n */\nexport interface EventHubProducerOptions {\n /**\n * The identifier of the partition that the producer will be bound to.\n * If a value is provided, all events sent using the producer will reach the same partition.\n * If no value is provided, the service will determine the partition to which the event will be sent.\n */\n partitionId?: string;\n /**\n * The retry options used to govern retry attempts when an issue is encountered while sending events.\n * If no value is provided here, the retry options set when creating the `EventHubClient` is used.\n */\n retryOptions?: RetryOptions;\n}\n\n/**\n * @internal\n */\nexport type OperationNames = \"getEventHubProperties\" | \"getPartitionIds\" | \"getPartitionProperties\";\n\n/**\n * @internal\n */\nexport interface CommonEventProcessorOptions\n extends Required<Pick<SubscribeOptions, \"maxBatchSize\" | \"maxWaitTimeInSeconds\">>,\n Pick<\n SubscribeOptions,\n Exclude<\n keyof SubscribeOptions,\n // (made required above)\n \"maxBatchSize\" | \"maxWaitTimeInSeconds\"\n >\n > {\n /**\n * A load balancing strategy that determines how to claim partitions.\n */\n loadBalancingStrategy: LoadBalancingStrategy;\n\n /**\n * An optional ownerId to use rather than using an internally generated ID\n * This allows you to logically group a series of processors together (for instance\n * like we do with EventHubConsumerClient)\n */\n ownerId?: string;\n\n /**\n * The maximum amount of time since a PartitionOwnership was updated\n * to use to determine if a partition is no longer claimed.\n * Setting this value to 0 will cause the default value to be used.\n */\n inactiveTimeLimitInMs?: number;\n /**\n * Retry Options to be used when receiving events\n */\n retryOptions?: RetryOptions;\n}\n\n/**\n * The set of options to configure the behavior of an `EventHubConsumer`.\n * These can be specified when creating the consumer using the `createConsumer` method.\n * - `ownerLevel` : A number indicating that the consumer intends to be an exclusive consumer of events resulting in other\n * consumers to fail if their `ownerLevel` is lower or doesn't exist.\n * - `retryOptions`: The retry options used to govern retry attempts when an issue is encountered while receiving events.\n * A simple usage can be `{ \"maxRetries\": 4 }`.\n * - `skipParsingBodyAsJson` : Option to disable the client from running JSON.parse() on the message body when receiving the message.\n * Not applicable if the message was sent with AMQP body type value or sequence. Use this option when you prefer to work directly with\n * the bytes present in the message body than have the client attempt to parse it.\n *\n * Example usage:\n * ```js\n * {\n * retryOptions: {\n * maxRetries: 4\n * },\n * trackLastEnqueuedEventProperties: false,\n * skipParsingBodyAsJson: true\n * }\n * ```\n * @internal\n */\nexport interface PartitionReceiverOptions {\n /**\n * The owner level associated with an exclusive consumer.\n *\n * When provided, the owner level indicates that a consumer is intended to be the exclusive receiver of events for the\n * requested partition and the associated consumer group.\n * When multiple consumers exist for the same partition/consumer group pair, then the ones with lower or no\n * `ownerLevel` will get a `ReceiverDisconnectedError` during the next attempted receive operation.\n */\n ownerLevel?: number;\n /**\n * The retry options used to govern retry attempts when an issue is encountered while receiving events.\n * If no value is provided here, the retry options set when creating the `EventHubClient` is used.\n */\n retryOptions?: RetryOptions;\n /**\n * Indicates whether or not the consumer should request information on the last enqueued event on its\n * associated partition, and track that information as events are received.\n\n * When information about the partition's last enqueued event is being tracked, each event received\n * from the Event Hubs service will carry metadata about the partition that it otherwise would not. This results in a small amount of\n * additional network bandwidth consumption that is generally a favorable trade-off when considered\n * against periodically making requests for partition properties using the Event Hub client.\n */\n trackLastEnqueuedEventProperties?: boolean;\n /**\n * Option to disable the client from running JSON.parse() on the message body when receiving the message.\n * Not applicable if the message was sent with AMQP body type value or sequence. Use this option when you\n * prefer to work directly with the bytes present in the message body than have the client attempt to parse it.\n */\n skipParsingBodyAsJson?: boolean;\n /**\n * The count of events requested eagerly and queued without regard to whether a read was requested.\n */\n prefetchCount?: number;\n}\n\n/**\n * @internal\n */\nexport interface IdempotentLinkProperties {\n [idempotentProducerAmqpPropertyNames.epoch]: Typed | null;\n [idempotentProducerAmqpPropertyNames.producerId]: Typed | null;\n [idempotentProducerAmqpPropertyNames.producerSequenceNumber]: Typed | null;\n}\n\n/**\n * The set of options that can be specified for an `EventHubProducerClient`\n * to influence its behavior when publishing directly to an Event Hub partition.\n *\n * These options are ignored when publishing to the Event Hubs gateway for automatic\n * routing or when using a partition key.\n */\nexport interface PartitionPublishingOptions {\n /**\n * The owner level indicates that a publishing is intended to be performed exclusively for events in the\n * requested partition in the context of the associated producer group.\n *\n * To do so, publishing will attempt to assert ownership over the partition;\n * in the case where more than one publisher in the producer group attempts to assert ownership for the same partition,\n * the one having a larger `ownerLevel` value will \"win\".\n */\n ownerLevel?: number;\n /**\n * The identifier of the producer group that this producer is associated with when publishing to the associated partition.\n * Events will be published in the context of this group.\n *\n * If `undefined`, the Event Hubs service will control the value.\n *\n * The producer group is only recognized and relevant when certain features of the producer are enabled.\n * For example, it is used by idempotent publishing.\n */\n producerGroupId?: number;\n /**\n * The starting number that should be used for the automatic sequencing of events for the associated partition, when published by this producer.\n *\n * If `undefined`, the Event Hubs service will control the value.\n *\n * The producer group is only recognized and relevant when certain features of the producer are enabled.\n * For example, it is used by idempotent publishing.\n */\n startingSequenceNumber?: number;\n}\n\n/**\n * Describes the information about the state of publishing for a partition.\n */\nexport interface PartitionPublishingProperties {\n /**\n * Indicates whether or not idempotent publishing is enabled for the producer and, by extension, the associated partition.\n */\n isIdempotentPublishingEnabled: boolean;\n /**\n * The owner level of the producer publishing to the associated partition.\n */\n ownerLevel?: number;\n /**\n * The partition id the properties are associated with.\n */\n partitionId: string;\n /**\n * The identifier of the producer group for which this producer is publishing to the associated partition.\n */\n producerGroupId?: number;\n /**\n * The sequence number assigned to the event that was most recently published to the associated partition successfully.\n */\n lastPublishedSequenceNumber?: number;\n}\n"]}
1
+ {"version":3,"file":"private.js","sourceRoot":"","sources":["../../../src/models/private.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAMlC,OAAO,EAAE,mCAAmC,EAAE,MAAM,sBAAsB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { LoadBalancingStrategy } from \"../loadBalancerStrategies/loadBalancingStrategy.js\";\nimport { RetryOptions } from \"@azure/core-amqp\";\nimport { Typed } from \"rhea-promise\";\nimport { SubscribeOptions } from \"../eventHubConsumerClientModels.js\";\nimport { idempotentProducerAmqpPropertyNames } from \"../util/constants.js\";\n\n/**\n * The set of options to configure the behavior of an `EventHubProducer`.\n * These can be specified when creating the producer via the `createProducer` method.\n * - `partitionId` : The string identifier of the partition that the producer can be bound to.\n * - `retryOptions` : The retry options used to govern retry attempts when an issue is encountered while sending events.\n * A simple usage can be `{ \"maxRetries\": 4 }`.\n * @internal\n */\nexport interface EventHubProducerOptions {\n /**\n * The identifier of the partition that the producer will be bound to.\n * If a value is provided, all events sent using the producer will reach the same partition.\n * If no value is provided, the service will determine the partition to which the event will be sent.\n */\n partitionId?: string;\n /**\n * The retry options used to govern retry attempts when an issue is encountered while sending events.\n * If no value is provided here, the retry options set when creating the `EventHubClient` is used.\n */\n retryOptions?: RetryOptions;\n}\n\n/**\n * @internal\n */\nexport type OperationNames = \"getEventHubProperties\" | \"getPartitionIds\" | \"getPartitionProperties\";\n\n/**\n * @internal\n */\nexport interface CommonEventProcessorOptions\n extends Required<Pick<SubscribeOptions, \"maxBatchSize\" | \"maxWaitTimeInSeconds\">>,\n Pick<\n SubscribeOptions,\n Exclude<\n keyof SubscribeOptions,\n // (made required above)\n \"maxBatchSize\" | \"maxWaitTimeInSeconds\"\n >\n > {\n /**\n * A load balancing strategy that determines how to claim partitions.\n */\n loadBalancingStrategy: LoadBalancingStrategy;\n\n /**\n * An optional ownerId to use rather than using an internally generated ID\n * This allows you to logically group a series of processors together (for instance\n * like we do with EventHubConsumerClient)\n */\n ownerId?: string;\n\n /**\n * The maximum amount of time since a PartitionOwnership was updated\n * to use to determine if a partition is no longer claimed.\n * Setting this value to 0 will cause the default value to be used.\n */\n inactiveTimeLimitInMs?: number;\n /**\n * Retry Options to be used when receiving events\n */\n retryOptions?: RetryOptions;\n}\n\n/**\n * The set of options to configure the behavior of an `EventHubConsumer`.\n * These can be specified when creating the consumer using the `createConsumer` method.\n * - `ownerLevel` : A number indicating that the consumer intends to be an exclusive consumer of events resulting in other\n * consumers to fail if their `ownerLevel` is lower or doesn't exist.\n * - `retryOptions`: The retry options used to govern retry attempts when an issue is encountered while receiving events.\n * A simple usage can be `{ \"maxRetries\": 4 }`.\n * - `skipParsingBodyAsJson` : Option to disable the client from running JSON.parse() on the message body when receiving the message.\n * Not applicable if the message was sent with AMQP body type value or sequence. Use this option when you prefer to work directly with\n * the bytes present in the message body than have the client attempt to parse it.\n *\n * Example usage:\n * ```js\n * {\n * retryOptions: {\n * maxRetries: 4\n * },\n * trackLastEnqueuedEventProperties: false,\n * skipParsingBodyAsJson: true\n * }\n * ```\n * @internal\n */\nexport interface PartitionReceiverOptions {\n /**\n * The owner level associated with an exclusive consumer.\n *\n * When provided, the owner level indicates that a consumer is intended to be the exclusive receiver of events for the\n * requested partition and the associated consumer group.\n * When multiple consumers exist for the same partition/consumer group pair, then the ones with lower or no\n * `ownerLevel` will get a `ReceiverDisconnectedError` during the next attempted receive operation.\n */\n ownerLevel?: number;\n /**\n * The retry options used to govern retry attempts when an issue is encountered while receiving events.\n * If no value is provided here, the retry options set when creating the `EventHubClient` is used.\n */\n retryOptions?: RetryOptions;\n /**\n * Indicates whether or not the consumer should request information on the last enqueued event on its\n * associated partition, and track that information as events are received.\n\n * When information about the partition's last enqueued event is being tracked, each event received\n * from the Event Hubs service will carry metadata about the partition that it otherwise would not. This results in a small amount of\n * additional network bandwidth consumption that is generally a favorable trade-off when considered\n * against periodically making requests for partition properties using the Event Hub client.\n */\n trackLastEnqueuedEventProperties?: boolean;\n /**\n * Option to disable the client from running JSON.parse() on the message body when receiving the message.\n * Not applicable if the message was sent with AMQP body type value or sequence. Use this option when you\n * prefer to work directly with the bytes present in the message body than have the client attempt to parse it.\n */\n skipParsingBodyAsJson?: boolean;\n /**\n * The count of events requested eagerly and queued without regard to whether a read was requested.\n */\n prefetchCount?: number;\n}\n\n/**\n * @internal\n */\nexport interface IdempotentLinkProperties {\n [idempotentProducerAmqpPropertyNames.epoch]: Typed | null;\n [idempotentProducerAmqpPropertyNames.producerId]: Typed | null;\n [idempotentProducerAmqpPropertyNames.producerSequenceNumber]: Typed | null;\n}\n\n/**\n * The set of options that can be specified for an `EventHubProducerClient`\n * to influence its behavior when publishing directly to an Event Hub partition.\n *\n * These options are ignored when publishing to the Event Hubs gateway for automatic\n * routing or when using a partition key.\n */\nexport interface PartitionPublishingOptions {\n /**\n * The owner level indicates that a publishing is intended to be performed exclusively for events in the\n * requested partition in the context of the associated producer group.\n *\n * To do so, publishing will attempt to assert ownership over the partition;\n * in the case where more than one publisher in the producer group attempts to assert ownership for the same partition,\n * the one having a larger `ownerLevel` value will \"win\".\n */\n ownerLevel?: number;\n /**\n * The identifier of the producer group that this producer is associated with when publishing to the associated partition.\n * Events will be published in the context of this group.\n *\n * If `undefined`, the Event Hubs service will control the value.\n *\n * The producer group is only recognized and relevant when certain features of the producer are enabled.\n * For example, it is used by idempotent publishing.\n */\n producerGroupId?: number;\n /**\n * The starting number that should be used for the automatic sequencing of events for the associated partition, when published by this producer.\n *\n * If `undefined`, the Event Hubs service will control the value.\n *\n * The producer group is only recognized and relevant when certain features of the producer are enabled.\n * For example, it is used by idempotent publishing.\n */\n startingSequenceNumber?: number;\n}\n\n/**\n * Describes the information about the state of publishing for a partition.\n */\nexport interface PartitionPublishingProperties {\n /**\n * Indicates whether or not idempotent publishing is enabled for the producer and, by extension, the associated partition.\n */\n isIdempotentPublishingEnabled: boolean;\n /**\n * The owner level of the producer publishing to the associated partition.\n */\n ownerLevel?: number;\n /**\n * The partition id the properties are associated with.\n */\n partitionId: string;\n /**\n * The identifier of the producer group for which this producer is publishing to the associated partition.\n */\n producerGroupId?: number;\n /**\n * The sequence number assigned to the event that was most recently published to the associated partition successfully.\n */\n lastPublishedSequenceNumber?: number;\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  // Copyright (c) Microsoft Corporation.
2
- // Licensed under the MIT license.
2
+ // Licensed under the MIT License.
3
3
  /**
4
4
  * An enum representing the different reasons for an `EventHubConsumerClient` to stop processing
5
5
  * events from a partition in a consumer group of an Event Hub.
@@ -1 +1 @@
1
- {"version":3,"file":"public.js","sourceRoot":"","sources":["../../../src/models/public.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAwElC;;;GAGG;AACH,MAAM,CAAN,IAAY,WASX;AATD,WAAY,WAAW;IACrB;;OAEG;IACH,8CAA+B,CAAA;IAC/B;;OAEG;IACH,oCAAqB,CAAA;AACvB,CAAC,EATW,WAAW,KAAX,WAAW,QAStB","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { RetryOptions, WebSocketOptions } from \"@azure/core-amqp\";\nimport { OperationOptions } from \"../util/operationOptions.js\";\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"]}
1
+ {"version":3,"file":"public.js","sourceRoot":"","sources":["../../../src/models/public.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAwElC;;;GAGG;AACH,MAAM,CAAN,IAAY,WASX;AATD,WAAY,WAAW;IACrB;;OAEG;IACH,8CAA+B,CAAA;IAC/B;;OAEG;IACH,oCAAqB,CAAA;AACvB,CAAC,EATW,WAAW,KAAX,WAAW,QAStB","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { RetryOptions, WebSocketOptions } from \"@azure/core-amqp\";\nimport { OperationOptions } from \"../util/operationOptions.js\";\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"]}
@@ -1,5 +1,5 @@
1
1
  // Copyright (c) Microsoft Corporation.
2
- // Licensed under the MIT license.
2
+ // Licensed under the MIT License.
3
3
  import { logger } from "./logger.js";
4
4
  /**
5
5
  * The `PartitionProcessor` is responsible for processing events received from Event Hubs when using `EventProcessor`
@@ -1 +1 @@
1
- {"version":3,"file":"partitionProcessor.js","sourceRoot":"","sources":["../../src/partitionProcessor.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAWlC,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAyCrC;;;;;;;;;GASG;AACH,MAAM,OAAO,kBAAkB;IAG7B,YACU,cAAyC,EACzC,gBAAiC,EACjC,QAEP;QAJO,mBAAc,GAAd,cAAc,CAA2B;QACzC,qBAAgB,GAAhB,gBAAgB,CAAiB;QACjC,aAAQ,GAAR,QAAQ,CAEf;IACA,CAAC;IAEJ;;;;;OAKG;IACH,IAAW,2BAA2B;QACpC,OAAO,IAAI,CAAC,4BAA6B,CAAC;IAC5C,CAAC;IAED;;;;OA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AAC,CAAC;YACtD,CAAC;YAAC,OAAO,GAAQ,EAAE,CAAC;gBAClB,MAAM,CAAC,OAAO,CAAC,mDAAmD,GAAG,EAAE,CAAC,CAAC;YAC3E,CAAC;QACH,CAAC;IACH,CAAC;IAED;;;;;;;OAOG;IACI,KAAK,CAAC,gBAAgB,CAAC,SAA4B;QACxD,MAAM,UAAU,GAAe;YAC7B,uBAAuB,EAAE,IAAI,CAAC,QAAQ,CAAC,uBAAuB;YAC9D,YAAY,EAAE,IAAI,CAAC,QAAQ,CAAC,YAAY;YACxC,aAAa,EAAE,IAAI,CAAC,QAAQ,CAAC,aAAa;YAC1C,WAAW,EAAE,IAAI,CAAC,QAAQ,CAAC,WAAW;YACtC,cAAc,EAAE,SAAS,CAAC,cAAc;YACxC,MAAM,EAAE,SAAS,CAAC,MAAM;SACzB,CAAC;QAEF,MAAM,IAAI,CAAC,gBAAiB,CAAC,gBAAgB,CAAC,UAAU,CAAC,CAAC;IAC5D,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n BasicPartitionProperties,\n PartitionContext,\n SubscriptionEventHandlers,\n} from \"./eventHubConsumerClientModels.js\";\nimport { CheckpointStore } from \"./eventProcessor.js\";\nimport { CloseReason } from \"./models/public.js\";\nimport { LastEnqueuedEventProperties } from \"./partitionReceiver.js\";\nimport { ReceivedEventData } from \"./eventData.js\";\nimport { logger } from \"./logger.js\";\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"]}
1
+ {"version":3,"file":"partitionProcessor.js","sourceRoot":"","sources":["../../src/partitionProcessor.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAWlC,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAyCrC;;;;;;;;;GASG;AACH,MAAM,OAAO,kBAAkB;IAG7B,YACU,cAAyC,EACzC,gBAAiC,EACjC,QAEP;QAJO,mBAAc,GAAd,cAAc,CAA2B;QACzC,qBAAgB,GAAhB,gBAAgB,CAAiB;QACjC,aAAQ,GAAR,QAAQ,CAEf;IACA,CAAC;IAEJ;;;;;OAKG;IACH,IAAW,2BAA2B;QACpC,OAAO,IAAI,CAAC,4BAA6B,CAAC;IAC5C,CAAC;IAED;;;;OAIG;IACH,IAAW,2BAA2B,CAAC,UAAuC;QAC5E,IAAI,CAAC,4BAA4B,GAAG,UAAU,CAAC;IACjD,CAAC;IAED;;;OAGG;IACH,IAAW,uBAAuB;QAChC,OAAO,IAAI,CAAC,QAAQ,CAAC,uBAAuB,CAAC;IAC/C,CAAC;IAED;;;OAGG;IACH,IAAW,aAAa;QACtB,OAAO,IAAI,CAAC,QAAQ,CAAC,aAAc,CAAC;IACtC,CAAC;IAED;;;OAGG;IACH,IAAW,YAAY;QACrB,OAAO,IAAI,CAAC,QAAQ,CAAC,YAAY,CAAC;IACpC,CAAC;IAED;;;OAGG;IACH,IAAW,WAAW;QACpB,OAAO,IAAI,CAAC,QAAQ,CAAC,WAAW,CAAC;IACnC,CAAC;IAED;;OAEG;IACH,IAAW,gBAAgB;QACzB,OAAO,IAAI,CAAC,QAAQ,CAAC,gBAAgB,CAAC;IACxC,CAAC;IAED;;;OAGG;IACH,KAAK,CAAC,UAAU;;QACd,OAAO,MAAA,MAAA,IAAI,CAAC,cAAc,EAAC,iBAA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ensed under the MIT License.\n\nimport {\n BasicPartitionProperties,\n PartitionContext,\n SubscriptionEventHandlers,\n} from \"./eventHubConsumerClientModels.js\";\nimport { CheckpointStore } from \"./eventProcessor.js\";\nimport { CloseReason } from \"./models/public.js\";\nimport { LastEnqueuedEventProperties } from \"./partitionReceiver.js\";\nimport { ReceivedEventData } from \"./eventData.js\";\nimport { logger } from \"./logger.js\";\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"]}
@@ -1,5 +1,5 @@
1
1
  // Copyright (c) Microsoft Corporation.
2
- // Licensed under the MIT license.
2
+ // Licensed under the MIT License.
3
3
  import { logErrorStackTrace, logger } from "./logger.js";
4
4
  import { CloseReason } from "./models/public.js";
5
5
  import { createReceiver } from "./partitionReceiver.js";
@@ -1 +1 @@
1
- {"version":3,"file":"partitionPump.js","sourceRoot":"","sources":["../../src/partitionPump.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,kBAAkB,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACzD,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAIjD,OAAO,EAAE,cAAc,EAAqB,MAAM,wBAAwB,CAAC;AAK3E,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;A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CACrC,cAAmC,EACnC,kBAAyE;IAEzE,MAAM,SAAS,GAAsB,EAAE,CAAC;IACxC,KAAK,MAAM,aAAa,IAAI,cAAc,EAAE,CAAC;QAC3C,MAAM,cAAc,GAAG,+BAA+B,CAAC,aAAa,CAAC,CAAC;QACtE,IAAI,cAAc,EAAE,CAAC;YACnB,SAAS,CAAC,IAAI,CAAC;gBACb,cAAc;gBACd,UAAU,EAAE;oBACV,YAAY,EAAE,aAAa,CAAC,eAAe,CAAC,OAAO,EAAE;iBACtD;aACF,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IACD,uBACE,SAAS,EACT,QAAQ,EAAE,UAAU,IACjB,aAAa,CAAC,kBAAkB,EAAE,SAAS,CAAC,EAC/C;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { TracingSpanOptions, TracingSpanLink } from \"@azure/core-tracing\";\nimport { logErrorStackTrace, logger } from \"./logger.js\";\nimport { CloseReason } from \"./models/public.js\";\nimport { CommonEventProcessorOptions } from \"./models/private.js\";\nimport { ConnectionContext } from \"./connectionContext.js\";\nimport { EventHubConnectionConfig } from \"./eventhubConnectionConfig.js\";\nimport { createReceiver, PartitionReceiver } from \"./partitionReceiver.js\";\nimport { EventPosition } from \"./eventPosition.js\";\nimport { MessagingError } from \"@azure/core-amqp\";\nimport { PartitionProcessor } from \"./partitionProcessor.js\";\nimport { ReceivedEventData } from \"./eventData.js\";\nimport { toSpanOptions, tracingClient } from \"./diagnostics/tracing.js\";\nimport { extractSpanContextFromEventData } from \"./diagnostics/instrumentEventData.js\";\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"]}
1
+ {"version":3,"file":"partitionPump.js","sourceRoot":"","sources":["../../src/partitionPump.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,kBAAkB,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACzD,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAIjD,OAAO,EAAE,cAAc,EAAqB,MAAM,wBAAwB,CAAC;AAK3E,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AACxE,OAAO,EAAE,+BAA+B,EAAE,MAAM,sCAAsC,CAAC;AAEvF;;GAEG;AACH,MAAM,OAAO,aAAa;IAOxB,YACU,QAA2B,EACnC,kBAAsC,EACrB,cAA6B,EAC9C,OAAoC;QAH5B,aAA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AAC,CAAC;QACtE,IAAI,cAAc,EAAE,CAAC;YACnB,SAAS,CAAC,IAAI,CAAC;gBACb,cAAc;gBACd,UAAU,EAAE;oBACV,YAAY,EAAE,aAAa,CAAC,eAAe,CAAC,OAAO,EAAE;iBACtD;aACF,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IACD,uBACE,SAAS,EACT,QAAQ,EAAE,UAAU,IACjB,aAAa,CAAC,kBAAkB,EAAE,SAAS,CAAC,EAC/C;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { TracingSpanOptions, TracingSpanLink } from \"@azure/core-tracing\";\nimport { logErrorStackTrace, logger } from \"./logger.js\";\nimport { CloseReason } from \"./models/public.js\";\nimport { CommonEventProcessorOptions } from \"./models/private.js\";\nimport { ConnectionContext } from \"./connectionContext.js\";\nimport { EventHubConnectionConfig } from \"./eventhubConnectionConfig.js\";\nimport { createReceiver, PartitionReceiver } from \"./partitionReceiver.js\";\nimport { EventPosition } from \"./eventPosition.js\";\nimport { MessagingError } from \"@azure/core-amqp\";\nimport { PartitionProcessor } from \"./partitionProcessor.js\";\nimport { ReceivedEventData } from \"./eventData.js\";\nimport { toSpanOptions, tracingClient } from \"./diagnostics/tracing.js\";\nimport { extractSpanContextFromEventData } from \"./diagnostics/instrumentEventData.js\";\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"]}
@@ -1,5 +1,5 @@
1
1
  // Copyright (c) Microsoft Corporation.
2
- // Licensed under the MIT license.
2
+ // Licensed under the MIT License.
3
3
  import { AbortError } from "@azure/abort-controller";
4
4
  import { Constants, RetryOperationType, StandardAbortMessage, retry, translate, } from "@azure/core-amqp";
5
5
  import { types, } from "rhea-promise";