@azure/monitor-opentelemetry-exporter 1.0.0-beta.27 → 1.0.0-beta.29

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 (370) hide show
  1. package/README.md +59 -53
  2. package/dist/commonjs/Declarations/Constants.d.ts +131 -0
  3. package/dist/commonjs/Declarations/Constants.d.ts.map +1 -0
  4. package/dist/commonjs/Declarations/Constants.js +147 -0
  5. package/dist/commonjs/Declarations/Constants.js.map +1 -0
  6. package/dist/commonjs/Declarations/Contracts/Constants.d.ts +14 -0
  7. package/dist/commonjs/Declarations/Contracts/Constants.d.ts.map +1 -0
  8. package/dist/commonjs/Declarations/Contracts/Constants.js +5 -0
  9. package/dist/commonjs/Declarations/Contracts/Constants.js.map +1 -0
  10. package/dist/commonjs/Declarations/Contracts/index.d.ts +2 -0
  11. package/dist/commonjs/Declarations/Contracts/index.d.ts.map +1 -0
  12. package/dist/commonjs/Declarations/Contracts/index.js +7 -0
  13. package/dist/commonjs/Declarations/Contracts/index.js.map +1 -0
  14. package/dist/commonjs/config.d.ts +30 -0
  15. package/dist/commonjs/config.d.ts.map +1 -0
  16. package/dist/commonjs/config.js +3 -0
  17. package/dist/commonjs/config.js.map +1 -0
  18. package/dist/commonjs/export/base.d.ts +36 -0
  19. package/dist/commonjs/export/base.d.ts.map +1 -0
  20. package/dist/commonjs/export/base.js +59 -0
  21. package/dist/commonjs/export/base.js.map +1 -0
  22. package/dist/commonjs/export/log.d.ts +30 -0
  23. package/dist/commonjs/export/log.d.ts.map +1 -0
  24. package/dist/commonjs/export/log.js +68 -0
  25. package/dist/commonjs/export/log.js.map +1 -0
  26. package/dist/commonjs/export/metric.d.ts +39 -0
  27. package/dist/commonjs/export/metric.d.ts.map +1 -0
  28. package/dist/commonjs/export/metric.js +79 -0
  29. package/dist/commonjs/export/metric.js.map +1 -0
  30. package/dist/commonjs/export/statsbeat/longIntervalStatsbeatMetrics.d.ts +39 -0
  31. package/dist/commonjs/export/statsbeat/longIntervalStatsbeatMetrics.d.ts.map +1 -0
  32. package/dist/commonjs/export/statsbeat/longIntervalStatsbeatMetrics.js +127 -0
  33. package/dist/commonjs/export/statsbeat/longIntervalStatsbeatMetrics.js.map +1 -0
  34. package/dist/commonjs/export/statsbeat/networkStatsbeatMetrics.d.ts +51 -0
  35. package/dist/commonjs/export/statsbeat/networkStatsbeatMetrics.d.ts.map +1 -0
  36. package/dist/commonjs/export/statsbeat/networkStatsbeatMetrics.js +289 -0
  37. package/dist/commonjs/export/statsbeat/networkStatsbeatMetrics.js.map +1 -0
  38. package/dist/commonjs/export/statsbeat/statsbeatExporter.d.ts +32 -0
  39. package/dist/commonjs/export/statsbeat/statsbeatExporter.d.ts.map +1 -0
  40. package/dist/commonjs/export/statsbeat/statsbeatExporter.js +62 -0
  41. package/dist/commonjs/export/statsbeat/statsbeatExporter.js.map +1 -0
  42. package/dist/commonjs/export/statsbeat/statsbeatMetrics.d.ts +11 -0
  43. package/dist/commonjs/export/statsbeat/statsbeatMetrics.d.ts.map +1 -0
  44. package/dist/commonjs/export/statsbeat/statsbeatMetrics.js +106 -0
  45. package/dist/commonjs/export/statsbeat/statsbeatMetrics.js.map +1 -0
  46. package/dist/commonjs/export/statsbeat/types.d.ts +102 -0
  47. package/dist/commonjs/export/statsbeat/types.d.ts.map +1 -0
  48. package/dist/commonjs/export/statsbeat/types.js +89 -0
  49. package/dist/commonjs/export/statsbeat/types.js.map +1 -0
  50. package/dist/commonjs/export/trace.d.ts +31 -0
  51. package/dist/commonjs/export/trace.d.ts.map +1 -0
  52. package/dist/commonjs/export/trace.js +76 -0
  53. package/dist/commonjs/export/trace.js.map +1 -0
  54. package/dist/commonjs/generated/applicationInsightsClient.d.ts +17 -0
  55. package/dist/commonjs/generated/applicationInsightsClient.d.ts.map +1 -0
  56. package/dist/commonjs/generated/applicationInsightsClient.js +89 -0
  57. package/dist/commonjs/generated/applicationInsightsClient.js.map +1 -0
  58. package/dist/commonjs/generated/index.d.ts +3 -0
  59. package/dist/commonjs/generated/index.d.ts.map +1 -0
  60. package/dist/commonjs/generated/index.js +15 -0
  61. package/dist/commonjs/generated/index.js.map +1 -0
  62. package/dist/commonjs/generated/models/index.d.ts +429 -0
  63. package/dist/commonjs/generated/models/index.d.ts.map +1 -0
  64. package/dist/commonjs/generated/models/index.js +93 -0
  65. package/dist/commonjs/generated/models/index.js.map +1 -0
  66. package/dist/commonjs/generated/models/mappers.d.ts +19 -0
  67. package/dist/commonjs/generated/models/mappers.d.ts.map +1 -0
  68. package/dist/commonjs/generated/models/mappers.js +848 -0
  69. package/dist/commonjs/generated/models/mappers.js.map +1 -0
  70. package/dist/commonjs/generated/models/parameters.d.ts +6 -0
  71. package/dist/commonjs/generated/models/parameters.d.ts.map +1 -0
  72. package/dist/commonjs/generated/models/parameters.js +60 -0
  73. package/dist/commonjs/generated/models/parameters.js.map +1 -0
  74. package/dist/commonjs/index.d.ts +10 -0
  75. package/dist/commonjs/index.d.ts.map +1 -0
  76. package/dist/commonjs/index.js +20 -0
  77. package/dist/commonjs/index.js.map +1 -0
  78. package/dist/commonjs/package.json +3 -0
  79. package/dist/commonjs/platform/index.d.ts +2 -0
  80. package/dist/commonjs/platform/index.d.ts.map +1 -0
  81. package/dist/commonjs/platform/index.js +10 -0
  82. package/dist/commonjs/platform/index.js.map +1 -0
  83. package/dist/commonjs/platform/nodejs/baseSender.d.ts +49 -0
  84. package/dist/commonjs/platform/nodejs/baseSender.d.ts.map +1 -0
  85. package/dist/commonjs/platform/nodejs/baseSender.js +239 -0
  86. package/dist/commonjs/platform/nodejs/baseSender.js.map +1 -0
  87. package/dist/commonjs/platform/nodejs/constants.d.ts +10 -0
  88. package/dist/commonjs/platform/nodejs/constants.d.ts.map +1 -0
  89. package/dist/commonjs/platform/nodejs/constants.js +15 -0
  90. package/dist/commonjs/platform/nodejs/constants.js.map +1 -0
  91. package/dist/commonjs/platform/nodejs/context/context.d.ts +20 -0
  92. package/dist/commonjs/platform/nodejs/context/context.d.ts.map +1 -0
  93. package/dist/commonjs/platform/nodejs/context/context.js +54 -0
  94. package/dist/commonjs/platform/nodejs/context/context.js.map +1 -0
  95. package/dist/commonjs/platform/nodejs/context/index.d.ts +2 -0
  96. package/dist/commonjs/platform/nodejs/context/index.d.ts.map +1 -0
  97. package/dist/commonjs/platform/nodejs/context/index.js +7 -0
  98. package/dist/commonjs/platform/nodejs/context/index.js.map +1 -0
  99. package/dist/commonjs/platform/nodejs/httpSender.d.ts +32 -0
  100. package/dist/commonjs/platform/nodejs/httpSender.d.ts.map +1 -0
  101. package/dist/commonjs/platform/nodejs/httpSender.js +70 -0
  102. package/dist/commonjs/platform/nodejs/httpSender.js.map +1 -0
  103. package/dist/commonjs/platform/nodejs/index.d.ts +8 -0
  104. package/dist/commonjs/platform/nodejs/index.d.ts.map +1 -0
  105. package/dist/commonjs/platform/nodejs/index.js +13 -0
  106. package/dist/commonjs/platform/nodejs/index.js.map +1 -0
  107. package/dist/commonjs/platform/nodejs/persist/fileAccessControl.d.ts +18 -0
  108. package/dist/commonjs/platform/nodejs/persist/fileAccessControl.d.ts.map +1 -0
  109. package/dist/commonjs/platform/nodejs/persist/fileAccessControl.js +177 -0
  110. package/dist/commonjs/platform/nodejs/persist/fileAccessControl.js.map +1 -0
  111. package/dist/commonjs/platform/nodejs/persist/fileSystemHelpers.d.ts +11 -0
  112. package/dist/commonjs/platform/nodejs/persist/fileSystemHelpers.d.ts.map +1 -0
  113. package/dist/commonjs/platform/nodejs/persist/fileSystemHelpers.js +60 -0
  114. package/dist/commonjs/platform/nodejs/persist/fileSystemHelpers.js.map +1 -0
  115. package/dist/commonjs/platform/nodejs/persist/fileSystemPersist.d.ts +29 -0
  116. package/dist/commonjs/platform/nodejs/persist/fileSystemPersist.d.ts.map +1 -0
  117. package/dist/commonjs/platform/nodejs/persist/fileSystemPersist.js +184 -0
  118. package/dist/commonjs/platform/nodejs/persist/fileSystemPersist.js.map +1 -0
  119. package/dist/commonjs/platform/nodejs/persist/index.d.ts +2 -0
  120. package/dist/commonjs/platform/nodejs/persist/index.d.ts.map +1 -0
  121. package/dist/commonjs/platform/nodejs/persist/index.js +7 -0
  122. package/dist/commonjs/platform/nodejs/persist/index.js.map +1 -0
  123. package/dist/commonjs/sampling.d.ts +38 -0
  124. package/dist/commonjs/sampling.d.ts.map +1 -0
  125. package/dist/commonjs/sampling.js +92 -0
  126. package/dist/commonjs/sampling.js.map +1 -0
  127. package/dist/commonjs/tsdoc-metadata.json +11 -0
  128. package/dist/commonjs/types.d.ts +96 -0
  129. package/dist/commonjs/types.d.ts.map +1 -0
  130. package/dist/commonjs/types.js +93 -0
  131. package/dist/commonjs/types.js.map +1 -0
  132. package/dist/commonjs/utils/breezeUtils.d.ts +25 -0
  133. package/dist/commonjs/utils/breezeUtils.d.ts.map +1 -0
  134. package/dist/commonjs/utils/breezeUtils.js +39 -0
  135. package/dist/commonjs/utils/breezeUtils.js.map +1 -0
  136. package/dist/commonjs/utils/common.d.ts +14 -0
  137. package/dist/commonjs/utils/common.d.ts.map +1 -0
  138. package/dist/commonjs/utils/common.js +251 -0
  139. package/dist/commonjs/utils/common.js.map +1 -0
  140. package/dist/commonjs/utils/connectionStringParser.d.ts +13 -0
  141. package/dist/commonjs/utils/connectionStringParser.d.ts.map +1 -0
  142. package/dist/commonjs/utils/connectionStringParser.js +83 -0
  143. package/dist/commonjs/utils/connectionStringParser.js.map +1 -0
  144. package/dist/commonjs/utils/constants/applicationinsights.d.ts +42 -0
  145. package/dist/commonjs/utils/constants/applicationinsights.d.ts.map +1 -0
  146. package/dist/commonjs/utils/constants/applicationinsights.js +48 -0
  147. package/dist/commonjs/utils/constants/applicationinsights.js.map +1 -0
  148. package/dist/commonjs/utils/constants/span/azAttributes.d.ts +16 -0
  149. package/dist/commonjs/utils/constants/span/azAttributes.d.ts.map +1 -0
  150. package/dist/commonjs/utils/constants/span/azAttributes.js +21 -0
  151. package/dist/commonjs/utils/constants/span/azAttributes.js.map +1 -0
  152. package/dist/commonjs/utils/eventhub.d.ts +10 -0
  153. package/dist/commonjs/utils/eventhub.d.ts.map +1 -0
  154. package/dist/commonjs/utils/eventhub.js +57 -0
  155. package/dist/commonjs/utils/eventhub.js.map +1 -0
  156. package/dist/commonjs/utils/logUtils.d.ts +8 -0
  157. package/dist/commonjs/utils/logUtils.d.ts.map +1 -0
  158. package/dist/commonjs/utils/logUtils.js +218 -0
  159. package/dist/commonjs/utils/logUtils.js.map +1 -0
  160. package/dist/commonjs/utils/metricUtils.d.ts +13 -0
  161. package/dist/commonjs/utils/metricUtils.d.ts.map +1 -0
  162. package/dist/commonjs/utils/metricUtils.js +132 -0
  163. package/dist/commonjs/utils/metricUtils.js.map +1 -0
  164. package/dist/commonjs/utils/spanUtils.d.ts +27 -0
  165. package/dist/commonjs/utils/spanUtils.d.ts.map +1 -0
  166. package/dist/commonjs/utils/spanUtils.js +516 -0
  167. package/dist/commonjs/utils/spanUtils.js.map +1 -0
  168. package/dist/esm/Declarations/Constants.d.ts +131 -0
  169. package/dist/esm/Declarations/Constants.d.ts.map +1 -0
  170. package/{dist-esm/src → dist/esm}/Declarations/Constants.js +33 -0
  171. package/dist/esm/Declarations/Constants.js.map +1 -0
  172. package/dist/esm/Declarations/Contracts/Constants.d.ts +14 -0
  173. package/dist/esm/Declarations/Contracts/Constants.d.ts.map +1 -0
  174. package/dist/esm/Declarations/Contracts/index.d.ts +2 -0
  175. package/dist/esm/Declarations/Contracts/index.d.ts.map +1 -0
  176. package/{dist-esm/src/platform/nodejs/context → dist/esm/Declarations/Contracts}/index.js +1 -1
  177. package/dist/esm/Declarations/Contracts/index.js.map +1 -0
  178. package/dist/esm/config.d.ts +30 -0
  179. package/dist/esm/config.d.ts.map +1 -0
  180. package/dist/esm/config.js.map +1 -0
  181. package/dist/esm/export/base.d.ts +36 -0
  182. package/dist/esm/export/base.d.ts.map +1 -0
  183. package/{dist-esm/src → dist/esm}/export/base.js +2 -2
  184. package/dist/esm/export/base.js.map +1 -0
  185. package/dist/esm/export/log.d.ts +30 -0
  186. package/dist/esm/export/log.d.ts.map +1 -0
  187. package/{dist-esm/src → dist/esm}/export/log.js +3 -4
  188. package/dist/esm/export/log.js.map +1 -0
  189. package/dist/esm/export/metric.d.ts +39 -0
  190. package/dist/esm/export/metric.d.ts.map +1 -0
  191. package/{dist-esm/src → dist/esm}/export/metric.js +4 -5
  192. package/dist/esm/export/metric.js.map +1 -0
  193. package/dist/esm/export/statsbeat/longIntervalStatsbeatMetrics.d.ts +39 -0
  194. package/dist/esm/export/statsbeat/longIntervalStatsbeatMetrics.d.ts.map +1 -0
  195. package/{dist-esm/src → dist/esm}/export/statsbeat/longIntervalStatsbeatMetrics.js +18 -15
  196. package/dist/esm/export/statsbeat/longIntervalStatsbeatMetrics.js.map +1 -0
  197. package/dist/esm/export/statsbeat/networkStatsbeatMetrics.d.ts +51 -0
  198. package/dist/esm/export/statsbeat/networkStatsbeatMetrics.d.ts.map +1 -0
  199. package/{dist-esm/src → dist/esm}/export/statsbeat/networkStatsbeatMetrics.js +11 -10
  200. package/dist/esm/export/statsbeat/networkStatsbeatMetrics.js.map +1 -0
  201. package/dist/esm/export/statsbeat/statsbeatExporter.d.ts +32 -0
  202. package/dist/esm/export/statsbeat/statsbeatExporter.d.ts.map +1 -0
  203. package/{dist-esm/src → dist/esm}/export/statsbeat/statsbeatExporter.js +3 -4
  204. package/dist/esm/export/statsbeat/statsbeatExporter.js.map +1 -0
  205. package/dist/esm/export/statsbeat/statsbeatMetrics.d.ts +11 -0
  206. package/dist/esm/export/statsbeat/statsbeatMetrics.d.ts.map +1 -0
  207. package/{dist-esm/src → dist/esm}/export/statsbeat/statsbeatMetrics.js +3 -4
  208. package/dist/esm/export/statsbeat/statsbeatMetrics.js.map +1 -0
  209. package/dist/esm/export/statsbeat/types.d.ts +102 -0
  210. package/dist/esm/export/statsbeat/types.d.ts.map +1 -0
  211. package/{dist-esm/src → dist/esm}/export/statsbeat/types.js +6 -0
  212. package/dist/esm/export/statsbeat/types.js.map +1 -0
  213. package/dist/esm/export/trace.d.ts +31 -0
  214. package/dist/esm/export/trace.d.ts.map +1 -0
  215. package/{dist-esm/src → dist/esm}/export/trace.js +4 -5
  216. package/dist/esm/export/trace.js.map +1 -0
  217. package/dist/esm/generated/applicationInsightsClient.d.ts +17 -0
  218. package/dist/esm/generated/applicationInsightsClient.d.ts.map +1 -0
  219. package/{dist-esm/src → dist/esm}/generated/applicationInsightsClient.js +3 -3
  220. package/dist/esm/generated/applicationInsightsClient.js.map +1 -0
  221. package/dist/esm/generated/index.d.ts +3 -0
  222. package/dist/esm/generated/index.d.ts.map +1 -0
  223. package/{dist-esm/src → dist/esm}/generated/index.js +2 -2
  224. package/dist/esm/generated/index.js.map +1 -0
  225. package/dist/esm/generated/models/index.d.ts +429 -0
  226. package/dist/esm/generated/models/index.d.ts.map +1 -0
  227. package/dist/esm/generated/models/mappers.d.ts +19 -0
  228. package/dist/esm/generated/models/mappers.d.ts.map +1 -0
  229. package/dist/esm/generated/models/parameters.d.ts +6 -0
  230. package/dist/esm/generated/models/parameters.d.ts.map +1 -0
  231. package/dist/esm/index.d.ts +10 -0
  232. package/dist/esm/index.d.ts.map +1 -0
  233. package/dist/esm/index.js +10 -0
  234. package/dist/esm/index.js.map +1 -0
  235. package/dist/esm/package.json +3 -0
  236. package/dist/esm/platform/index.d.ts +2 -0
  237. package/dist/esm/platform/index.d.ts.map +1 -0
  238. package/{dist-esm/src → dist/esm}/platform/index.js +1 -1
  239. package/dist/esm/platform/index.js.map +1 -0
  240. package/dist/esm/platform/nodejs/baseSender.d.ts +49 -0
  241. package/dist/esm/platform/nodejs/baseSender.d.ts.map +1 -0
  242. package/{dist-esm/src → dist/esm}/platform/nodejs/baseSender.js +10 -8
  243. package/dist/esm/platform/nodejs/baseSender.js.map +1 -0
  244. package/dist/esm/platform/nodejs/constants.d.ts +10 -0
  245. package/dist/esm/platform/nodejs/constants.d.ts.map +1 -0
  246. package/dist/esm/platform/nodejs/context/context.d.ts +20 -0
  247. package/dist/esm/platform/nodejs/context/context.d.ts.map +1 -0
  248. package/{dist-esm/src → dist/esm}/platform/nodejs/context/context.js +5 -5
  249. package/dist/esm/platform/nodejs/context/context.js.map +1 -0
  250. package/dist/esm/platform/nodejs/context/index.d.ts +2 -0
  251. package/dist/esm/platform/nodejs/context/index.d.ts.map +1 -0
  252. package/{dist-esm/src/Declarations/Contracts → dist/esm/platform/nodejs/context}/index.js +1 -1
  253. package/{dist-esm/src → dist/esm}/platform/nodejs/context/index.js.map +1 -1
  254. package/dist/esm/platform/nodejs/httpSender.d.ts +32 -0
  255. package/dist/esm/platform/nodejs/httpSender.d.ts.map +1 -0
  256. package/{dist-esm/src → dist/esm}/platform/nodejs/httpSender.js +3 -4
  257. package/dist/esm/platform/nodejs/httpSender.js.map +1 -0
  258. package/dist/esm/platform/nodejs/index.d.ts +8 -0
  259. package/dist/esm/platform/nodejs/index.d.ts.map +1 -0
  260. package/dist/esm/platform/nodejs/index.js +10 -0
  261. package/dist/esm/platform/nodejs/index.js.map +1 -0
  262. package/dist/esm/platform/nodejs/persist/fileAccessControl.d.ts +18 -0
  263. package/dist/esm/platform/nodejs/persist/fileAccessControl.d.ts.map +1 -0
  264. package/{dist-esm/src → dist/esm}/platform/nodejs/persist/fileAccessControl.js +14 -13
  265. package/dist/esm/platform/nodejs/persist/fileAccessControl.js.map +1 -0
  266. package/dist/esm/platform/nodejs/persist/fileSystemHelpers.d.ts +11 -0
  267. package/dist/esm/platform/nodejs/persist/fileSystemHelpers.d.ts.map +1 -0
  268. package/{dist-esm/src → dist/esm}/platform/nodejs/persist/fileSystemHelpers.js +6 -11
  269. package/dist/esm/platform/nodejs/persist/fileSystemHelpers.js.map +1 -0
  270. package/dist/esm/platform/nodejs/persist/fileSystemPersist.d.ts +29 -0
  271. package/dist/esm/platform/nodejs/persist/fileSystemPersist.d.ts.map +1 -0
  272. package/{dist-esm/src → dist/esm}/platform/nodejs/persist/fileSystemPersist.js +19 -26
  273. package/dist/esm/platform/nodejs/persist/fileSystemPersist.js.map +1 -0
  274. package/dist/esm/platform/nodejs/persist/index.d.ts +2 -0
  275. package/dist/esm/platform/nodejs/persist/index.d.ts.map +1 -0
  276. package/{dist-esm/src → dist/esm}/platform/nodejs/persist/index.js +1 -1
  277. package/{dist-esm/src → dist/esm}/platform/nodejs/persist/index.js.map +1 -1
  278. package/dist/esm/sampling.d.ts +38 -0
  279. package/dist/esm/sampling.d.ts.map +1 -0
  280. package/{dist-esm/src → dist/esm}/sampling.js +1 -1
  281. package/dist/esm/sampling.js.map +1 -0
  282. package/dist/esm/types.d.ts +96 -0
  283. package/dist/esm/types.d.ts.map +1 -0
  284. package/dist/esm/types.js +90 -0
  285. package/dist/esm/types.js.map +1 -0
  286. package/dist/esm/utils/breezeUtils.d.ts +25 -0
  287. package/dist/esm/utils/breezeUtils.d.ts.map +1 -0
  288. package/dist/esm/utils/common.d.ts +14 -0
  289. package/dist/esm/utils/common.d.ts.map +1 -0
  290. package/{dist-esm/src → dist/esm}/utils/common.js +22 -20
  291. package/dist/esm/utils/common.js.map +1 -0
  292. package/dist/esm/utils/connectionStringParser.d.ts +13 -0
  293. package/dist/esm/utils/connectionStringParser.d.ts.map +1 -0
  294. package/{dist-esm/src → dist/esm}/utils/connectionStringParser.js +1 -1
  295. package/dist/esm/utils/connectionStringParser.js.map +1 -0
  296. package/dist/esm/utils/constants/applicationinsights.d.ts +42 -0
  297. package/dist/esm/utils/constants/applicationinsights.d.ts.map +1 -0
  298. package/{dist-esm/src → dist/esm}/utils/constants/applicationinsights.js +2 -1
  299. package/dist/esm/utils/constants/applicationinsights.js.map +1 -0
  300. package/dist/esm/utils/constants/span/azAttributes.d.ts +16 -0
  301. package/dist/esm/utils/constants/span/azAttributes.d.ts.map +1 -0
  302. package/dist/esm/utils/eventhub.d.ts +10 -0
  303. package/dist/esm/utils/eventhub.d.ts.map +1 -0
  304. package/{dist-esm/src → dist/esm}/utils/eventhub.js +2 -2
  305. package/dist/esm/utils/eventhub.js.map +1 -0
  306. package/dist/esm/utils/logUtils.d.ts +8 -0
  307. package/dist/esm/utils/logUtils.d.ts.map +1 -0
  308. package/{dist-esm/src → dist/esm}/utils/logUtils.js +55 -39
  309. package/dist/esm/utils/logUtils.js.map +1 -0
  310. package/dist/esm/utils/metricUtils.d.ts +13 -0
  311. package/dist/esm/utils/metricUtils.d.ts.map +1 -0
  312. package/{dist-esm/src → dist/esm}/utils/metricUtils.js +41 -3
  313. package/dist/esm/utils/metricUtils.js.map +1 -0
  314. package/dist/esm/utils/spanUtils.d.ts +27 -0
  315. package/dist/esm/utils/spanUtils.d.ts.map +1 -0
  316. package/{dist-esm/src → dist/esm}/utils/spanUtils.js +151 -100
  317. package/dist/esm/utils/spanUtils.js.map +1 -0
  318. package/package.json +63 -43
  319. package/dist/index.js +0 -4134
  320. package/dist-esm/src/Declarations/Constants.js.map +0 -1
  321. package/dist-esm/src/Declarations/Contracts/index.js.map +0 -1
  322. package/dist-esm/src/config.js.map +0 -1
  323. package/dist-esm/src/export/base.js.map +0 -1
  324. package/dist-esm/src/export/log.js.map +0 -1
  325. package/dist-esm/src/export/metric.js.map +0 -1
  326. package/dist-esm/src/export/statsbeat/longIntervalStatsbeatMetrics.js.map +0 -1
  327. package/dist-esm/src/export/statsbeat/networkStatsbeatMetrics.js.map +0 -1
  328. package/dist-esm/src/export/statsbeat/statsbeatExporter.js.map +0 -1
  329. package/dist-esm/src/export/statsbeat/statsbeatMetrics.js.map +0 -1
  330. package/dist-esm/src/export/statsbeat/types.js.map +0 -1
  331. package/dist-esm/src/export/trace.js.map +0 -1
  332. package/dist-esm/src/generated/applicationInsightsClient.js.map +0 -1
  333. package/dist-esm/src/generated/index.js.map +0 -1
  334. package/dist-esm/src/index.js +0 -9
  335. package/dist-esm/src/index.js.map +0 -1
  336. package/dist-esm/src/platform/index.js.map +0 -1
  337. package/dist-esm/src/platform/nodejs/baseSender.js.map +0 -1
  338. package/dist-esm/src/platform/nodejs/context/context.js.map +0 -1
  339. package/dist-esm/src/platform/nodejs/httpSender.js.map +0 -1
  340. package/dist-esm/src/platform/nodejs/index.js +0 -10
  341. package/dist-esm/src/platform/nodejs/index.js.map +0 -1
  342. package/dist-esm/src/platform/nodejs/persist/fileAccessControl.js.map +0 -1
  343. package/dist-esm/src/platform/nodejs/persist/fileSystemHelpers.js.map +0 -1
  344. package/dist-esm/src/platform/nodejs/persist/fileSystemPersist.js.map +0 -1
  345. package/dist-esm/src/sampling.js.map +0 -1
  346. package/dist-esm/src/types.js +0 -40
  347. package/dist-esm/src/types.js.map +0 -1
  348. package/dist-esm/src/utils/common.js.map +0 -1
  349. package/dist-esm/src/utils/connectionStringParser.js.map +0 -1
  350. package/dist-esm/src/utils/constants/applicationinsights.js.map +0 -1
  351. package/dist-esm/src/utils/eventhub.js.map +0 -1
  352. package/dist-esm/src/utils/logUtils.js.map +0 -1
  353. package/dist-esm/src/utils/metricUtils.js.map +0 -1
  354. package/dist-esm/src/utils/spanUtils.js.map +0 -1
  355. package/types/monitor-opentelemetry-exporter.d.ts +0 -222
  356. /package/{dist-esm/src → dist/esm}/Declarations/Contracts/Constants.js +0 -0
  357. /package/{dist-esm/src → dist/esm}/Declarations/Contracts/Constants.js.map +0 -0
  358. /package/{dist-esm/src → dist/esm}/config.js +0 -0
  359. /package/{dist-esm/src → dist/esm}/generated/models/index.js +0 -0
  360. /package/{dist-esm/src → dist/esm}/generated/models/index.js.map +0 -0
  361. /package/{dist-esm/src → dist/esm}/generated/models/mappers.js +0 -0
  362. /package/{dist-esm/src → dist/esm}/generated/models/mappers.js.map +0 -0
  363. /package/{dist-esm/src → dist/esm}/generated/models/parameters.js +0 -0
  364. /package/{dist-esm/src → dist/esm}/generated/models/parameters.js.map +0 -0
  365. /package/{dist-esm/src → dist/esm}/platform/nodejs/constants.js +0 -0
  366. /package/{dist-esm/src → dist/esm}/platform/nodejs/constants.js.map +0 -0
  367. /package/{dist-esm/src → dist/esm}/utils/breezeUtils.js +0 -0
  368. /package/{dist-esm/src → dist/esm}/utils/breezeUtils.js.map +0 -0
  369. /package/{dist-esm/src → dist/esm}/utils/constants/span/azAttributes.js +0 -0
  370. /package/{dist-esm/src → dist/esm}/utils/constants/span/azAttributes.js.map +0 -0
package/dist/index.js DELETED
@@ -1,4134 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- var sdkTraceBase = require('@opentelemetry/sdk-trace-base');
6
- var api = require('@opentelemetry/api');
7
- var core = require('@opentelemetry/core');
8
- var semanticConventions = require('@opentelemetry/semantic-conventions');
9
- var os$1 = require('os');
10
- var url = require('url');
11
- var coreRestPipeline = require('@azure/core-rest-pipeline');
12
- var sdkMetrics = require('@opentelemetry/sdk-metrics');
13
- var fs = require('fs');
14
- var path = require('path');
15
- var child_process = require('child_process');
16
- var util = require('util');
17
- var coreClient = require('@azure/core-client');
18
-
19
- function _interopNamespaceDefault(e) {
20
- var n = Object.create(null);
21
- if (e) {
22
- Object.keys(e).forEach(function (k) {
23
- if (k !== 'default') {
24
- var d = Object.getOwnPropertyDescriptor(e, k);
25
- Object.defineProperty(n, k, d.get ? d : {
26
- enumerable: true,
27
- get: function () { return e[k]; }
28
- });
29
- }
30
- });
31
- }
32
- n.default = e;
33
- return Object.freeze(n);
34
- }
35
-
36
- var os__namespace = /*#__PURE__*/_interopNamespaceDefault(os$1);
37
- var fs__namespace = /*#__PURE__*/_interopNamespaceDefault(fs);
38
- var path__namespace = /*#__PURE__*/_interopNamespaceDefault(path);
39
- var child_process__namespace = /*#__PURE__*/_interopNamespaceDefault(child_process);
40
- var coreClient__namespace = /*#__PURE__*/_interopNamespaceDefault(coreClient);
41
-
42
- // Copyright (c) Microsoft Corporation.
43
- // Licensed under the MIT License.
44
- /**
45
- * AI MS Links.
46
- * @internal
47
- */
48
- const MS_LINKS = "_MS.links";
49
- /**
50
- * AI enqueued time attribute.
51
- * @internal
52
- */
53
- const ENQUEUED_TIME = "enqueuedTime";
54
- /**
55
- * AI time since enqueued attribute.
56
- * @internal
57
- */
58
- const TIME_SINCE_ENQUEUED = "timeSinceEnqueued";
59
- /**
60
- * AzureMonitorTraceExporter version.
61
- * @internal
62
- */
63
- const packageVersion = "1.0.0-beta.27";
64
- var DependencyTypes;
65
- (function (DependencyTypes) {
66
- DependencyTypes["InProc"] = "InProc";
67
- DependencyTypes["QueueMessage"] = "Queue Message";
68
- DependencyTypes["Sql"] = "SQL";
69
- DependencyTypes["Http"] = "Http";
70
- DependencyTypes["Grpc"] = "GRPC";
71
- DependencyTypes["Wcf"] = "WCF Service";
72
- })(DependencyTypes || (DependencyTypes = {}));
73
- const AzureMonitorSampleRate = "microsoft.sample_rate";
74
- const ApplicationInsightsBaseType = "_MS.baseType";
75
- const ApplicationInsightsMessageName = "Microsoft.ApplicationInsights.Message";
76
- const ApplicationInsightsExceptionName = "Microsoft.ApplicationInsights.Exception";
77
- const ApplicationInsightsPageViewName = "Microsoft.ApplicationInsights.PageView";
78
- const ApplicationInsightsAvailabilityName = "Microsoft.ApplicationInsights.Availability";
79
- const ApplicationInsightsEventName = "Microsoft.ApplicationInsights.Event";
80
- const ApplicationInsightsMessageBaseType = "MessageData";
81
- const ApplicationInsightsExceptionBaseType = "ExceptionData";
82
- const ApplicationInsightsPageViewBaseType = "PageViewData";
83
- const ApplicationInsightsAvailabilityBaseType = "AvailabilityData";
84
- const ApplicationInsightsEventBaseType = "EventData";
85
-
86
- /**
87
- * ApplicationInsightsSampler is responsible for the following:
88
- * Implements same trace id hashing algorithm so that traces are sampled the same across multiple nodes
89
- * Adds item count to span attribute if span is sampled (needed for ingestion service)
90
- * @param samplingRatio - 0 to 1 value.
91
- */
92
- class ApplicationInsightsSampler {
93
- /**
94
- * Initializes a new instance of the ApplicationInsightsSampler class.
95
- * @param samplingRatio - Value in the range [0,1], 1 meaning all data will sampled and 0 all Tracing data will be sampled out.
96
- */
97
- constructor(samplingRatio = 1) {
98
- this.samplingRatio = samplingRatio;
99
- if (this.samplingRatio > 1 || this.samplingRatio < 0 || !Number.isFinite(this.samplingRatio)) {
100
- throw new Error("Wrong sampling rate, data will not be sampled out");
101
- }
102
- this._sampleRate = Math.round(this.samplingRatio * 100);
103
- }
104
- /**
105
- * Checks whether span needs to be created and tracked.
106
- *
107
- * @param context - Parent Context which may contain a span.
108
- * @param traceId - traceif of the span to be created. It can be different from the
109
- * traceId in the {@link SpanContext}. Typically in situations when the
110
- * span to be created starts a new trace.
111
- * @param spanName - Name of the span to be created.
112
- * @param spanKind - Kind of the span to be created.
113
- * @param attributes - Initial set of SpanAttributes for the Span being constructed.
114
- * @param links - Collection of links that will be associated with the Span to
115
- * be created. Typically useful for batch operations.
116
- * @returns a {@link SamplingResult}.
117
- */
118
- shouldSample(
119
- // @ts-expect-error unused argument
120
- context, traceId,
121
- // @ts-expect-error unused argument
122
- spanName,
123
- // @ts-expect-error unused argument
124
- spanKind, attributes,
125
- // @ts-expect-error unused argument
126
- links) {
127
- let isSampledIn = false;
128
- if (this._sampleRate === 100) {
129
- isSampledIn = true;
130
- }
131
- else if (this._sampleRate === 0) {
132
- isSampledIn = false;
133
- }
134
- else {
135
- isSampledIn = this._getSamplingHashCode(traceId) < this._sampleRate;
136
- }
137
- // Add sample rate as span attribute
138
- attributes = attributes || {};
139
- // Only send the sample rate if it's not 100
140
- if (this._sampleRate !== 100) {
141
- attributes[AzureMonitorSampleRate] = this._sampleRate;
142
- }
143
- return isSampledIn
144
- ? { decision: sdkTraceBase.SamplingDecision.RECORD_AND_SAMPLED, attributes: attributes }
145
- : { decision: sdkTraceBase.SamplingDecision.NOT_RECORD, attributes: attributes };
146
- }
147
- /**
148
- * Return Sampler description
149
- */
150
- toString() {
151
- return `ApplicationInsightsSampler{${this.samplingRatio}}`;
152
- }
153
- _getSamplingHashCode(input) {
154
- const csharpMin = -2147483648;
155
- const csharpMax = 2147483647;
156
- let hash = 5381;
157
- if (!input) {
158
- return 0;
159
- }
160
- while (input.length < 8) {
161
- input = input + input;
162
- }
163
- for (let i = 0; i < input.length; i++) {
164
- // JS doesn't respond to integer overflow by wrapping around. Simulate it with bitwise operators ( | 0)
165
- hash = ((((hash << 5) + hash) | 0) + input.charCodeAt(i)) | 0;
166
- }
167
- hash = hash <= csharpMin ? csharpMax : Math.abs(hash);
168
- return (hash / csharpMax) * 100;
169
- }
170
- }
171
-
172
- // Copyright (c) Microsoft Corporation.
173
- // Licensed under the MIT License.
174
- /**
175
- * Azure service API version.
176
- */
177
- exports.ServiceApiVersion = void 0;
178
- (function (ServiceApiVersion) {
179
- /**
180
- * V2 Version
181
- */
182
- ServiceApiVersion["V2"] = "2020-09-15_Preview";
183
- })(exports.ServiceApiVersion || (exports.ServiceApiVersion = {}));
184
- /**
185
- * Default Breeze endpoint.
186
- * @internal
187
- */
188
- const DEFAULT_BREEZE_ENDPOINT = "https://dc.services.visualstudio.com";
189
- /**
190
- * Default Breeze API version.
191
- * @internal
192
- */
193
- exports.ServiceApiVersion.V2;
194
- /**
195
- * Default Live Metrics endpoint.
196
- * @internal
197
- */
198
- const DEFAULT_LIVEMETRICS_ENDPOINT = "https://rt.services.visualstudio.com";
199
- /**
200
- * Connection string environment variable name.
201
- * @internal
202
- */
203
- const ENV_CONNECTION_STRING = "APPLICATIONINSIGHTS_CONNECTION_STRING";
204
- /**
205
- * Disable Statsbeat environment variable name.
206
- * @internal
207
- */
208
- const ENV_DISABLE_STATSBEAT = "APPLICATIONINSIGHTS_STATSBEAT_DISABLED";
209
- /**
210
- * Legacy disable Statsbeat environment variable name.
211
- * @internal
212
- */
213
- const LEGACY_ENV_DISABLE_STATSBEAT = "APPLICATION_INSIGHTS_NO_STATSBEAT";
214
- /**
215
- * QuickPulse metric counter names.
216
- * @internal
217
- */
218
- var QuickPulseCounter;
219
- (function (QuickPulseCounter) {
220
- // Memory
221
- QuickPulseCounter["COMMITTED_BYTES"] = "\\Memory\\Committed Bytes";
222
- // CPU
223
- QuickPulseCounter["PROCESSOR_TIME"] = "\\Processor(_Total)\\% Processor Time";
224
- // Request
225
- QuickPulseCounter["REQUEST_RATE"] = "\\ApplicationInsights\\Requests/Sec";
226
- QuickPulseCounter["REQUEST_FAILURE_RATE"] = "\\ApplicationInsights\\Requests Failed/Sec";
227
- QuickPulseCounter["REQUEST_DURATION"] = "\\ApplicationInsights\\Request Duration";
228
- // Dependency
229
- QuickPulseCounter["DEPENDENCY_RATE"] = "\\ApplicationInsights\\Dependency Calls/Sec";
230
- QuickPulseCounter["DEPENDENCY_FAILURE_RATE"] = "\\ApplicationInsights\\Dependency Calls Failed/Sec";
231
- QuickPulseCounter["DEPENDENCY_DURATION"] = "\\ApplicationInsights\\Dependency Call Duration";
232
- // Exception
233
- QuickPulseCounter["EXCEPTION_RATE"] = "\\ApplicationInsights\\Exceptions/Sec";
234
- })(QuickPulseCounter || (QuickPulseCounter = {}));
235
- /**
236
- * Performance metric counter names.
237
- * @internal
238
- */
239
- var PerformanceCounter;
240
- (function (PerformanceCounter) {
241
- // Memory
242
- PerformanceCounter["PRIVATE_BYTES"] = "\\Process(??APP_WIN32_PROC??)\\Private Bytes";
243
- PerformanceCounter["AVAILABLE_BYTES"] = "\\Memory\\Available Bytes";
244
- // CPU
245
- PerformanceCounter["PROCESSOR_TIME"] = "\\Processor(_Total)\\% Processor Time";
246
- PerformanceCounter["PROCESS_TIME"] = "\\Process(??APP_WIN32_PROC??)\\% Processor Time";
247
- // Requests
248
- PerformanceCounter["REQUEST_RATE"] = "\\ASP.NET Applications(??APP_W3SVC_PROC??)\\Requests/Sec";
249
- PerformanceCounter["REQUEST_DURATION"] = "\\ASP.NET Applications(??APP_W3SVC_PROC??)\\Request Execution Time";
250
- })(PerformanceCounter || (PerformanceCounter = {}));
251
- /**
252
- * Map a PerformanceCounter/QuickPulseCounter to a QuickPulseCounter. If no mapping exists, mapping is *undefined*
253
- * @internal
254
- */
255
- ({
256
- [PerformanceCounter.PROCESSOR_TIME]: QuickPulseCounter.PROCESSOR_TIME,
257
- [PerformanceCounter.REQUEST_RATE]: QuickPulseCounter.REQUEST_RATE,
258
- [PerformanceCounter.REQUEST_DURATION]: QuickPulseCounter.REQUEST_DURATION,
259
- // Remap quick pulse only counters
260
- [QuickPulseCounter.COMMITTED_BYTES]: QuickPulseCounter.COMMITTED_BYTES,
261
- [QuickPulseCounter.REQUEST_FAILURE_RATE]: QuickPulseCounter.REQUEST_FAILURE_RATE,
262
- [QuickPulseCounter.DEPENDENCY_RATE]: QuickPulseCounter.DEPENDENCY_RATE,
263
- [QuickPulseCounter.DEPENDENCY_FAILURE_RATE]: QuickPulseCounter.DEPENDENCY_FAILURE_RATE,
264
- [QuickPulseCounter.DEPENDENCY_DURATION]: QuickPulseCounter.DEPENDENCY_DURATION,
265
- [QuickPulseCounter.EXCEPTION_RATE]: QuickPulseCounter.EXCEPTION_RATE,
266
- });
267
-
268
- // Copyright (c) Microsoft Corporation.
269
- // Licensed under the MIT License.
270
- /**
271
- * ConnectionString parser.
272
- * @internal
273
- */
274
- class ConnectionStringParser {
275
- static parse(connectionString) {
276
- if (!connectionString) {
277
- return {};
278
- }
279
- const kvPairs = connectionString.split(ConnectionStringParser.FIELDS_SEPARATOR);
280
- let isValid = true;
281
- const result = kvPairs.reduce((fields, kv) => {
282
- const kvParts = kv.split(ConnectionStringParser.FIELD_KEY_VALUE_SEPARATOR);
283
- if (kvParts.length === 2) {
284
- // only save fields with valid formats
285
- const key = kvParts[0].toLowerCase();
286
- const value = kvParts[1];
287
- return Object.assign(Object.assign({}, fields), { [key]: value });
288
- }
289
- api.diag.error(`Connection string key-value pair is invalid: ${kv}`, `Entire connection string will be discarded`, connectionString);
290
- isValid = false;
291
- return fields;
292
- }, {});
293
- if (isValid && Object.keys(result).length > 0) {
294
- // this is a valid connection string, so parse the results
295
- if (result.endpointsuffix) {
296
- // use endpoint suffix where overrides are not provided
297
- const locationPrefix = result.location ? `${result.location}.` : "";
298
- result.ingestionendpoint =
299
- result.ingestionendpoint || `https://${locationPrefix}dc.${result.endpointsuffix}`;
300
- result.liveendpoint =
301
- result.liveendpoint || `https://${locationPrefix}live.${result.endpointsuffix}`;
302
- }
303
- result.ingestionendpoint = result.ingestionendpoint
304
- ? ConnectionStringParser.sanitizeUrl(result.ingestionendpoint)
305
- : DEFAULT_BREEZE_ENDPOINT;
306
- result.liveendpoint = result.liveendpoint
307
- ? ConnectionStringParser.sanitizeUrl(result.liveendpoint)
308
- : DEFAULT_LIVEMETRICS_ENDPOINT;
309
- if (result.authorization && result.authorization.toLowerCase() !== "ikey") {
310
- api.diag.warn(`Connection String contains an unsupported 'Authorization' value: ${result.authorization}. Defaulting to 'Authorization=ikey'. Instrumentation Key ${result.instrumentationkey}`);
311
- }
312
- }
313
- else {
314
- api.diag.error("An invalid connection string was passed in. There may be telemetry loss", connectionString);
315
- }
316
- return result;
317
- }
318
- static sanitizeUrl(url) {
319
- let newUrl = url.trim();
320
- if (newUrl.indexOf("https://") < 0) {
321
- // Try to update http to https
322
- newUrl = newUrl.replace("http://", "https://");
323
- }
324
- // Remove final slash if present
325
- if (newUrl[newUrl.length - 1] === "/") {
326
- newUrl = newUrl.slice(0, -1);
327
- }
328
- return newUrl;
329
- }
330
- static validateInstrumentationKey(iKey) {
331
- if (iKey.startsWith("InstrumentationKey=")) {
332
- const startIndex = iKey.indexOf("InstrumentationKey=") + "InstrumentationKey=".length;
333
- const endIndex = iKey.indexOf(";", startIndex);
334
- iKey = iKey.substring(startIndex, endIndex);
335
- }
336
- const UUID_Regex = "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$";
337
- const regexp = new RegExp(UUID_Regex);
338
- return regexp.test(iKey);
339
- }
340
- }
341
- ConnectionStringParser.FIELDS_SEPARATOR = ";";
342
- ConnectionStringParser.FIELD_KEY_VALUE_SEPARATOR = "=";
343
-
344
- // Copyright (c) Microsoft Corporation.
345
- // Licensed under the MIT License.
346
- /**
347
- * Azure Monitor OpenTelemetry Trace Exporter.
348
- */
349
- class AzureMonitorBaseExporter {
350
- /**
351
- * Initializes a new instance of the AzureMonitorBaseExporter class.
352
- * @param AzureMonitorExporterOptions - Exporter configuration.
353
- */
354
- constructor(options = {}, isStatsbeatExporter) {
355
- var _a;
356
- /**
357
- * Instrumentation key to be used for exported envelopes
358
- */
359
- this.instrumentationKey = "";
360
- /**
361
- * Ingestion Endpoint URL
362
- */
363
- this.endpointUrl = "";
364
- /**
365
- *Flag to determine if exporter will generate Statsbeat data
366
- */
367
- this.trackStatsbeat = false;
368
- this.options = options;
369
- this.instrumentationKey = "";
370
- this.endpointUrl = DEFAULT_BREEZE_ENDPOINT;
371
- const connectionString = this.options.connectionString || process.env[ENV_CONNECTION_STRING];
372
- this.isStatsbeatExporter = isStatsbeatExporter ? isStatsbeatExporter : false;
373
- if (connectionString) {
374
- const parsedConnectionString = ConnectionStringParser.parse(connectionString);
375
- this.instrumentationKey =
376
- parsedConnectionString.instrumentationkey || this.instrumentationKey;
377
- this.endpointUrl = ((_a = parsedConnectionString.ingestionendpoint) === null || _a === void 0 ? void 0 : _a.trim()) || this.endpointUrl;
378
- this.aadAudience = parsedConnectionString.aadaudience;
379
- }
380
- // Instrumentation key is required
381
- if (!this.instrumentationKey) {
382
- const message = "No instrumentation key or connection string was provided to the Azure Monitor Exporter";
383
- api.diag.error(message);
384
- throw new Error(message);
385
- }
386
- if (!ConnectionStringParser.validateInstrumentationKey(this.instrumentationKey)) {
387
- const message = "Invalid instrumentation key was provided to the Azure Monitor Exporter";
388
- api.diag.error(message);
389
- throw new Error(message);
390
- }
391
- this.trackStatsbeat = !this.isStatsbeatExporter && !process.env[LEGACY_ENV_DISABLE_STATSBEAT];
392
- api.diag.debug("AzureMonitorExporter was successfully setup");
393
- }
394
- }
395
-
396
- // Copyright (c) Microsoft Corporation.
397
- // Licensed under the MIT License.
398
- class FileAccessControl {
399
- // Check if file access control could be enabled
400
- static checkFileProtection() {
401
- if (!FileAccessControl.OS_PROVIDES_FILE_PROTECTION &&
402
- !FileAccessControl.OS_FILE_PROTECTION_CHECKED) {
403
- FileAccessControl.OS_FILE_PROTECTION_CHECKED = true;
404
- // Node's chmod levels do not appropriately restrict file access on Windows
405
- // Use the built-in command line tool ICACLS on Windows to properly restrict
406
- // access to the temporary directory used for disk retry mode.
407
- if (FileAccessControl.USE_ICACLS) {
408
- // This should be async - but it's currently safer to have this synchronous
409
- // This guarantees we can immediately fail setDiskRetryMode if we need to
410
- try {
411
- FileAccessControl.OS_PROVIDES_FILE_PROTECTION = fs__namespace.existsSync(FileAccessControl.ICACLS_PATH);
412
- }
413
- catch (e) {
414
- // Ignore error
415
- }
416
- if (!FileAccessControl.OS_PROVIDES_FILE_PROTECTION) {
417
- api.diag.warn("Could not find ICACLS in expected location! This is necessary to use disk retry mode on Windows.");
418
- }
419
- }
420
- else {
421
- // chmod works everywhere else
422
- FileAccessControl.OS_PROVIDES_FILE_PROTECTION = true;
423
- }
424
- }
425
- }
426
- static async applyACLRules(directory) {
427
- if (FileAccessControl.USE_ICACLS) {
428
- if (FileAccessControl.ACLED_DIRECTORIES[directory] === undefined) {
429
- // Avoid multiple calls race condition by setting ACLED_DIRECTORIES to false for this directory immediately
430
- // If batches are being failed faster than the processes spawned below return, some data won't be stored to disk
431
- // This is better than the alternative of potentially infinitely spawned processes
432
- FileAccessControl.ACLED_DIRECTORIES[directory] = false;
433
- try {
434
- // Restrict this directory to only current user and administrator access
435
- const identity = await this._getACLIdentity();
436
- await this._runICACLS(this._getACLArguments(directory, identity));
437
- FileAccessControl.ACLED_DIRECTORIES[directory] = true;
438
- }
439
- catch (ex) {
440
- FileAccessControl.ACLED_DIRECTORIES[directory] = false; // false is used to cache failed (vs undefined which is "not yet tried")
441
- throw ex;
442
- }
443
- }
444
- else {
445
- if (!FileAccessControl.ACLED_DIRECTORIES[directory]) {
446
- throw new Error("Setting ACL restrictions did not succeed (cached result)");
447
- }
448
- }
449
- }
450
- }
451
- static applyACLRulesSync(directory) {
452
- if (FileAccessControl.USE_ICACLS) {
453
- // For performance, only run ACL rules if we haven't already during this session
454
- if (FileAccessControl.ACLED_DIRECTORIES[directory] === undefined) {
455
- this._runICACLSSync(this._getACLArguments(directory, this._getACLIdentitySync()));
456
- FileAccessControl.ACLED_DIRECTORIES[directory] = true; // If we get here, it succeeded. _runIACLSSync will throw on failures
457
- return;
458
- }
459
- else if (!FileAccessControl.ACLED_DIRECTORIES[directory]) {
460
- // falsy but not undefined
461
- throw new Error("Setting ACL restrictions did not succeed (cached result)");
462
- }
463
- }
464
- }
465
- static _runICACLS(args) {
466
- return new Promise((resolve, reject) => {
467
- const aclProc = child_process__namespace.spawn(FileAccessControl.ICACLS_PATH, args, {
468
- windowsHide: true,
469
- });
470
- aclProc.on("error", (e) => reject(e));
471
- aclProc.on("close", (code) => {
472
- if (code === 0) {
473
- resolve();
474
- }
475
- else {
476
- reject(new Error(`Setting ACL restrictions did not succeed (ICACLS returned code ${code})`));
477
- }
478
- });
479
- });
480
- }
481
- static _runICACLSSync(args) {
482
- // Some very old versions of Node (< 0.11) don't have this
483
- if (child_process__namespace.spawnSync) {
484
- const aclProc = child_process__namespace.spawnSync(FileAccessControl.ICACLS_PATH, args, {
485
- windowsHide: true,
486
- });
487
- if (aclProc.error) {
488
- throw aclProc.error;
489
- }
490
- else if (aclProc.status !== 0) {
491
- throw new Error(`Setting ACL restrictions did not succeed (ICACLS returned code ${aclProc.status})`);
492
- }
493
- }
494
- else {
495
- throw new Error("Could not synchronously call ICACLS under current version of Node.js");
496
- }
497
- }
498
- static _getACLIdentity() {
499
- return new Promise((resolve, reject) => {
500
- if (FileAccessControl.ACL_IDENTITY) {
501
- resolve(FileAccessControl.ACL_IDENTITY);
502
- }
503
- const psProc = child_process__namespace.spawn(FileAccessControl.POWERSHELL_PATH, ["-Command", "[System.Security.Principal.WindowsIdentity]::GetCurrent().Name"], {
504
- windowsHide: true,
505
- stdio: ["ignore", "pipe", "pipe"], // Needed to prevent hanging on Win 7
506
- });
507
- let data = "";
508
- psProc.stdout.on("data", (d) => (data += d));
509
- psProc.on("error", (e) => reject(e));
510
- psProc.on("close", (code) => {
511
- FileAccessControl.ACL_IDENTITY = data && data.trim();
512
- if (code === 0) {
513
- resolve(FileAccessControl.ACL_IDENTITY);
514
- }
515
- else {
516
- reject(new Error(`Getting ACL identity did not succeed (PS returned code ${code})`));
517
- }
518
- });
519
- });
520
- }
521
- static _getACLIdentitySync() {
522
- if (FileAccessControl.ACL_IDENTITY) {
523
- return FileAccessControl.ACL_IDENTITY;
524
- }
525
- // Some very old versions of Node (< 0.11) don't have this
526
- if (child_process__namespace.spawnSync) {
527
- const psProc = child_process__namespace.spawnSync(FileAccessControl.POWERSHELL_PATH, ["-Command", "[System.Security.Principal.WindowsIdentity]::GetCurrent().Name"], {
528
- windowsHide: true,
529
- stdio: ["ignore", "pipe", "pipe"], // Needed to prevent hanging on Win 7
530
- });
531
- if (psProc.error) {
532
- throw psProc.error;
533
- }
534
- else if (psProc.status !== 0) {
535
- throw new Error(`Getting ACL identity did not succeed (PS returned code ${psProc.status})`);
536
- }
537
- FileAccessControl.ACL_IDENTITY = psProc.stdout && psProc.stdout.toString().trim();
538
- return FileAccessControl.ACL_IDENTITY;
539
- }
540
- else {
541
- throw new Error("Could not synchronously get ACL identity under current version of Node.js");
542
- }
543
- }
544
- static _getACLArguments(directory, identity) {
545
- return [
546
- directory,
547
- "/grant",
548
- "*S-1-5-32-544:(OI)(CI)F", // Full permission for Administrators
549
- "/grant",
550
- `${identity}:(OI)(CI)F`, // Full permission for current user
551
- "/inheritance:r",
552
- ]; // Remove all inherited permissions
553
- }
554
- }
555
- FileAccessControl.ICACLS_PATH = `${process.env.systemdrive}/windows/system32/icacls.exe`;
556
- FileAccessControl.POWERSHELL_PATH = `${process.env.systemdrive}/windows/system32/windowspowershell/v1.0/powershell.exe`;
557
- FileAccessControl.ACLED_DIRECTORIES = {};
558
- FileAccessControl.ACL_IDENTITY = null;
559
- FileAccessControl.OS_FILE_PROTECTION_CHECKED = false;
560
- FileAccessControl.OS_PROVIDES_FILE_PROTECTION = false;
561
- FileAccessControl.USE_ICACLS = os__namespace.type() === "Windows_NT";
562
-
563
- // Copyright (c) Microsoft Corporation.
564
- // Licensed under the MIT License.
565
- const readdirAsync$1 = util.promisify(fs__namespace.readdir);
566
- const statAsync$1 = util.promisify(fs__namespace.stat);
567
- const lstatAsync = util.promisify(fs__namespace.lstat);
568
- const mkdirAsync = util.promisify(fs__namespace.mkdir);
569
- /**
570
- * Computes the size (in bytes) of all files in a directory at the root level. Asynchronously.
571
- * @internal
572
- */
573
- const getShallowDirectorySize = async (directory) => {
574
- let totalSize = 0;
575
- try {
576
- // Get the directory listing
577
- const files = await readdirAsync$1(directory);
578
- // Query all file sizes
579
- for (const file of files) {
580
- const fileStats = await statAsync$1(path__namespace.join(directory, file));
581
- if (fileStats.isFile()) {
582
- totalSize += fileStats.size;
583
- }
584
- }
585
- return totalSize;
586
- }
587
- catch (err) {
588
- api.diag.error(`Error getting directory size: ${err}`);
589
- return 0;
590
- }
591
- };
592
- /**
593
- * Validate directory exists.
594
- * @internal
595
- */
596
- const confirmDirExists = async (directory) => {
597
- try {
598
- const stats = await lstatAsync(directory);
599
- if (!stats.isDirectory()) {
600
- throw new Error("Path existed but was not a directory");
601
- }
602
- }
603
- catch (err) {
604
- if (err && err.code === "ENOENT") {
605
- try {
606
- const options = { recursive: true };
607
- await mkdirAsync(directory, options);
608
- }
609
- catch (mkdirErr) {
610
- if (mkdirErr && mkdirErr.code !== "EEXIST") {
611
- // Handle race condition by ignoring EEXIST
612
- throw mkdirErr;
613
- }
614
- }
615
- }
616
- }
617
- };
618
-
619
- // Copyright (c) Microsoft Corporation.
620
- // Licensed under the MIT License.
621
- const statAsync = util.promisify(fs__namespace.stat);
622
- const readdirAsync = util.promisify(fs__namespace.readdir);
623
- const readFileAsync = util.promisify(fs__namespace.readFile);
624
- const unlinkAsync = util.promisify(fs__namespace.unlink);
625
- const writeFileAsync = util.promisify(fs__namespace.writeFile);
626
- /**
627
- * File system persist class.
628
- * @internal
629
- */
630
- class FileSystemPersist {
631
- constructor(instrumentationKey, _options) {
632
- var _a, _b;
633
- this._options = _options;
634
- this.fileRetemptionPeriod = 2 * 24 * 60 * 60 * 1000; // 2 days
635
- this.cleanupTimeOut = 60 * 60 * 1000; // 1 hour
636
- this.maxBytesOnDisk = 50000000; // ~50MB
637
- this._tempDirectory = "";
638
- this._fileCleanupTimer = null;
639
- this._instrumentationKey = instrumentationKey;
640
- if ((_a = this._options) === null || _a === void 0 ? void 0 : _a.disableOfflineStorage) {
641
- this._enabled = false;
642
- return;
643
- }
644
- this._enabled = true;
645
- FileAccessControl.checkFileProtection();
646
- if (!FileAccessControl.OS_PROVIDES_FILE_PROTECTION) {
647
- this._enabled = false;
648
- api.diag.error("Sufficient file protection capabilities were not detected. Files will not be persisted");
649
- }
650
- if (!this._instrumentationKey) {
651
- this._enabled = false;
652
- api.diag.error(`No instrumentation key was provided to FileSystemPersister. Files will not be persisted`);
653
- }
654
- if (this._enabled) {
655
- this._tempDirectory = path__namespace.join(((_b = this._options) === null || _b === void 0 ? void 0 : _b.storageDirectory) || os__namespace.tmpdir(), "Microsoft", "AzureMonitor", FileSystemPersist.TEMPDIR_PREFIX + this._instrumentationKey);
656
- // Starts file cleanup task
657
- if (!this._fileCleanupTimer) {
658
- this._fileCleanupTimer = setTimeout(() => {
659
- this._fileCleanupTask();
660
- }, this.cleanupTimeOut);
661
- this._fileCleanupTimer.unref();
662
- }
663
- }
664
- }
665
- push(value) {
666
- var _a;
667
- if (this._enabled) {
668
- api.diag.debug("Pushing value to persistent storage", value.toString());
669
- return this._storeToDisk(JSON.stringify(value));
670
- }
671
- // Only return a false promise if the SDK isn't set to disable offline storage
672
- if (!((_a = this._options) === null || _a === void 0 ? void 0 : _a.disableOfflineStorage)) {
673
- return new Promise((resolve) => {
674
- resolve(false);
675
- });
676
- }
677
- return new Promise((resolve) => {
678
- resolve(true);
679
- });
680
- }
681
- async shift() {
682
- if (this._enabled) {
683
- api.diag.debug("Searching for filesystem persisted files");
684
- try {
685
- const buffer = await this._getFirstFileOnDisk();
686
- if (buffer) {
687
- return JSON.parse(buffer.toString("utf8"));
688
- }
689
- }
690
- catch (e) {
691
- api.diag.debug("Failed to read persisted file", e);
692
- }
693
- return null;
694
- }
695
- return new Promise((resolve) => {
696
- resolve(null);
697
- });
698
- }
699
- /**
700
- * Check for temp telemetry files
701
- * reads the first file if exist, deletes it and tries to send its load
702
- */
703
- async _getFirstFileOnDisk() {
704
- try {
705
- const stats = await statAsync(this._tempDirectory);
706
- if (stats.isDirectory()) {
707
- const origFiles = await readdirAsync(this._tempDirectory);
708
- const files = origFiles.filter((f) => path__namespace.basename(f).includes(FileSystemPersist.FILENAME_SUFFIX));
709
- if (files.length === 0) {
710
- return null;
711
- }
712
- else {
713
- const firstFile = files[0];
714
- const filePath = path__namespace.join(this._tempDirectory, firstFile);
715
- const payload = await readFileAsync(filePath);
716
- // delete the file first to prevent double sending
717
- await unlinkAsync(filePath);
718
- return payload;
719
- }
720
- }
721
- return null;
722
- }
723
- catch (e) {
724
- if (e.code === "ENOENT") {
725
- // File does not exist -- return null instead of throwing
726
- return null;
727
- }
728
- else {
729
- throw e;
730
- }
731
- }
732
- }
733
- async _storeToDisk(payload) {
734
- try {
735
- await confirmDirExists(this._tempDirectory);
736
- }
737
- catch (error) {
738
- api.diag.warn(`Error while checking/creating directory: `, error && error.message);
739
- return false;
740
- }
741
- try {
742
- const size = await getShallowDirectorySize(this._tempDirectory);
743
- if (size > this.maxBytesOnDisk) {
744
- api.diag.warn(`Not saving data due to max size limit being met. Directory size in bytes is: ${size}`);
745
- return false;
746
- }
747
- }
748
- catch (error) {
749
- api.diag.warn(`Error while checking size of persistence directory: `, error && error.message);
750
- return false;
751
- }
752
- const fileName = `${new Date().getTime()}${FileSystemPersist.FILENAME_SUFFIX}`;
753
- const fileFullPath = path__namespace.join(this._tempDirectory, fileName);
754
- // Mode 600 is w/r for creator and no read access for others
755
- api.diag.info(`saving data to disk at: ${fileFullPath}`);
756
- try {
757
- await writeFileAsync(fileFullPath, payload, { mode: 0o600 });
758
- }
759
- catch (writeError) {
760
- api.diag.warn(`Error writing file to persistent file storage`, writeError);
761
- return false;
762
- }
763
- return true;
764
- }
765
- async _fileCleanupTask() {
766
- try {
767
- const stats = await statAsync(this._tempDirectory);
768
- if (stats.isDirectory()) {
769
- const origFiles = await readdirAsync(this._tempDirectory);
770
- const files = origFiles.filter((f) => path__namespace.basename(f).includes(FileSystemPersist.FILENAME_SUFFIX));
771
- if (files.length === 0) {
772
- return false;
773
- }
774
- else {
775
- // eslint-disable-next-line @typescript-eslint/no-misused-promises
776
- files.forEach(async (file) => {
777
- // Check expiration
778
- const fileCreationDate = new Date(parseInt(file.split(FileSystemPersist.FILENAME_SUFFIX)[0]));
779
- const expired = new Date(+new Date() - this.fileRetemptionPeriod) > fileCreationDate;
780
- if (expired) {
781
- const filePath = path__namespace.join(this._tempDirectory, file);
782
- await unlinkAsync(filePath);
783
- }
784
- });
785
- return true;
786
- }
787
- }
788
- return false;
789
- }
790
- catch (error) {
791
- api.diag.info(`Failed cleanup of persistent file storage expired files`, error);
792
- return false;
793
- }
794
- }
795
- }
796
- FileSystemPersist.TEMPDIR_PREFIX = "ot-azure-exporter-";
797
- FileSystemPersist.FILENAME_SUFFIX = ".ai.json";
798
-
799
- /*
800
- * Copyright (c) Microsoft Corporation.
801
- * Licensed under the MIT License.
802
- *
803
- * Code generated by Microsoft (R) AutoRest Code Generator.
804
- * Changes may cause incorrect behavior and will be lost if the code is regenerated.
805
- */
806
- /** Known values of {@link DataPointType} that the service accepts. */
807
- var KnownDataPointType;
808
- (function (KnownDataPointType) {
809
- /** Measurement */
810
- KnownDataPointType["Measurement"] = "Measurement";
811
- /** Aggregation */
812
- KnownDataPointType["Aggregation"] = "Aggregation";
813
- })(KnownDataPointType || (KnownDataPointType = {}));
814
- /** Known values of {@link SeverityLevel} that the service accepts. */
815
- var KnownSeverityLevel;
816
- (function (KnownSeverityLevel) {
817
- /** Verbose */
818
- KnownSeverityLevel["Verbose"] = "Verbose";
819
- /** Information */
820
- KnownSeverityLevel["Information"] = "Information";
821
- /** Warning */
822
- KnownSeverityLevel["Warning"] = "Warning";
823
- /** Error */
824
- KnownSeverityLevel["Error"] = "Error";
825
- /** Critical */
826
- KnownSeverityLevel["Critical"] = "Critical";
827
- })(KnownSeverityLevel || (KnownSeverityLevel = {}));
828
- /** Known values of {@link ContextTagKeys} that the service accepts. */
829
- var KnownContextTagKeys;
830
- (function (KnownContextTagKeys) {
831
- /** AiApplicationVer */
832
- KnownContextTagKeys["AiApplicationVer"] = "ai.application.ver";
833
- /** AiDeviceId */
834
- KnownContextTagKeys["AiDeviceId"] = "ai.device.id";
835
- /** AiDeviceLocale */
836
- KnownContextTagKeys["AiDeviceLocale"] = "ai.device.locale";
837
- /** AiDeviceModel */
838
- KnownContextTagKeys["AiDeviceModel"] = "ai.device.model";
839
- /** AiDeviceOemName */
840
- KnownContextTagKeys["AiDeviceOemName"] = "ai.device.oemName";
841
- /** AiDeviceOsVersion */
842
- KnownContextTagKeys["AiDeviceOsVersion"] = "ai.device.osVersion";
843
- /** AiDeviceType */
844
- KnownContextTagKeys["AiDeviceType"] = "ai.device.type";
845
- /** AiLocationIp */
846
- KnownContextTagKeys["AiLocationIp"] = "ai.location.ip";
847
- /** AiLocationCountry */
848
- KnownContextTagKeys["AiLocationCountry"] = "ai.location.country";
849
- /** AiLocationProvince */
850
- KnownContextTagKeys["AiLocationProvince"] = "ai.location.province";
851
- /** AiLocationCity */
852
- KnownContextTagKeys["AiLocationCity"] = "ai.location.city";
853
- /** AiOperationId */
854
- KnownContextTagKeys["AiOperationId"] = "ai.operation.id";
855
- /** AiOperationName */
856
- KnownContextTagKeys["AiOperationName"] = "ai.operation.name";
857
- /** AiOperationParentId */
858
- KnownContextTagKeys["AiOperationParentId"] = "ai.operation.parentId";
859
- /** AiOperationSyntheticSource */
860
- KnownContextTagKeys["AiOperationSyntheticSource"] = "ai.operation.syntheticSource";
861
- /** AiOperationCorrelationVector */
862
- KnownContextTagKeys["AiOperationCorrelationVector"] = "ai.operation.correlationVector";
863
- /** AiSessionId */
864
- KnownContextTagKeys["AiSessionId"] = "ai.session.id";
865
- /** AiSessionIsFirst */
866
- KnownContextTagKeys["AiSessionIsFirst"] = "ai.session.isFirst";
867
- /** AiUserAccountId */
868
- KnownContextTagKeys["AiUserAccountId"] = "ai.user.accountId";
869
- /** AiUserId */
870
- KnownContextTagKeys["AiUserId"] = "ai.user.id";
871
- /** AiUserAuthUserId */
872
- KnownContextTagKeys["AiUserAuthUserId"] = "ai.user.authUserId";
873
- /** AiCloudRole */
874
- KnownContextTagKeys["AiCloudRole"] = "ai.cloud.role";
875
- /** AiCloudRoleVer */
876
- KnownContextTagKeys["AiCloudRoleVer"] = "ai.cloud.roleVer";
877
- /** AiCloudRoleInstance */
878
- KnownContextTagKeys["AiCloudRoleInstance"] = "ai.cloud.roleInstance";
879
- /** AiCloudLocation */
880
- KnownContextTagKeys["AiCloudLocation"] = "ai.cloud.location";
881
- /** AiInternalSdkVersion */
882
- KnownContextTagKeys["AiInternalSdkVersion"] = "ai.internal.sdkVersion";
883
- /** AiInternalAgentVersion */
884
- KnownContextTagKeys["AiInternalAgentVersion"] = "ai.internal.agentVersion";
885
- /** AiInternalNodeName */
886
- KnownContextTagKeys["AiInternalNodeName"] = "ai.internal.nodeName";
887
- })(KnownContextTagKeys || (KnownContextTagKeys = {}));
888
-
889
- /*
890
- * Copyright (c) Microsoft Corporation.
891
- * Licensed under the MIT License.
892
- *
893
- * Code generated by Microsoft (R) AutoRest Code Generator.
894
- * Changes may cause incorrect behavior and will be lost if the code is regenerated.
895
- */
896
- const contentType = {
897
- parameterPath: ["options", "contentType"],
898
- mapper: {
899
- defaultValue: "application/json",
900
- isConstant: true,
901
- serializedName: "Content-Type",
902
- type: {
903
- name: "String",
904
- },
905
- },
906
- };
907
- const body = {
908
- parameterPath: "body",
909
- mapper: {
910
- serializedName: "body",
911
- required: true,
912
- type: {
913
- name: "Sequence",
914
- element: {
915
- type: {
916
- name: "Composite",
917
- className: "TelemetryItem",
918
- },
919
- },
920
- },
921
- },
922
- };
923
- const accept = {
924
- parameterPath: "accept",
925
- mapper: {
926
- defaultValue: "application/json",
927
- isConstant: true,
928
- serializedName: "Accept",
929
- type: {
930
- name: "String",
931
- },
932
- },
933
- };
934
- const host = {
935
- parameterPath: "host",
936
- mapper: {
937
- serializedName: "Host",
938
- required: true,
939
- type: {
940
- name: "String",
941
- },
942
- },
943
- skipEncoding: true,
944
- };
945
-
946
- /*
947
- * Copyright (c) Microsoft Corporation.
948
- * Licensed under the MIT License.
949
- *
950
- * Code generated by Microsoft (R) AutoRest Code Generator.
951
- * Changes may cause incorrect behavior and will be lost if the code is regenerated.
952
- */
953
- const TelemetryItem = {
954
- type: {
955
- name: "Composite",
956
- className: "TelemetryItem",
957
- modelProperties: {
958
- version: {
959
- defaultValue: 1,
960
- serializedName: "ver",
961
- type: {
962
- name: "Number",
963
- },
964
- },
965
- name: {
966
- serializedName: "name",
967
- required: true,
968
- type: {
969
- name: "String",
970
- },
971
- },
972
- time: {
973
- serializedName: "time",
974
- required: true,
975
- type: {
976
- name: "DateTime",
977
- },
978
- },
979
- sampleRate: {
980
- defaultValue: 100,
981
- serializedName: "sampleRate",
982
- type: {
983
- name: "Number",
984
- },
985
- },
986
- sequence: {
987
- constraints: {
988
- MaxLength: 64,
989
- },
990
- serializedName: "seq",
991
- type: {
992
- name: "String",
993
- },
994
- },
995
- instrumentationKey: {
996
- serializedName: "iKey",
997
- type: {
998
- name: "String",
999
- },
1000
- },
1001
- tags: {
1002
- serializedName: "tags",
1003
- type: {
1004
- name: "Dictionary",
1005
- value: { type: { name: "String" } },
1006
- },
1007
- },
1008
- data: {
1009
- serializedName: "data",
1010
- type: {
1011
- name: "Composite",
1012
- className: "MonitorBase",
1013
- },
1014
- },
1015
- },
1016
- },
1017
- };
1018
- const MonitorBase = {
1019
- type: {
1020
- name: "Composite",
1021
- className: "MonitorBase",
1022
- modelProperties: {
1023
- baseType: {
1024
- serializedName: "baseType",
1025
- type: {
1026
- name: "String",
1027
- },
1028
- },
1029
- baseData: {
1030
- serializedName: "baseData",
1031
- type: {
1032
- name: "Composite",
1033
- className: "MonitorDomain",
1034
- },
1035
- },
1036
- },
1037
- },
1038
- };
1039
- const MonitorDomain = {
1040
- type: {
1041
- name: "Composite",
1042
- className: "MonitorDomain",
1043
- additionalProperties: { type: { name: "Object" } },
1044
- modelProperties: {
1045
- version: {
1046
- defaultValue: 2,
1047
- serializedName: "ver",
1048
- required: true,
1049
- type: {
1050
- name: "Number",
1051
- },
1052
- },
1053
- },
1054
- },
1055
- };
1056
- const TrackResponse = {
1057
- type: {
1058
- name: "Composite",
1059
- className: "TrackResponse",
1060
- modelProperties: {
1061
- itemsReceived: {
1062
- serializedName: "itemsReceived",
1063
- type: {
1064
- name: "Number",
1065
- },
1066
- },
1067
- itemsAccepted: {
1068
- serializedName: "itemsAccepted",
1069
- type: {
1070
- name: "Number",
1071
- },
1072
- },
1073
- errors: {
1074
- serializedName: "errors",
1075
- type: {
1076
- name: "Sequence",
1077
- element: {
1078
- type: {
1079
- name: "Composite",
1080
- className: "TelemetryErrorDetails",
1081
- },
1082
- },
1083
- },
1084
- },
1085
- },
1086
- },
1087
- };
1088
- const TelemetryErrorDetails = {
1089
- type: {
1090
- name: "Composite",
1091
- className: "TelemetryErrorDetails",
1092
- modelProperties: {
1093
- index: {
1094
- serializedName: "index",
1095
- type: {
1096
- name: "Number",
1097
- },
1098
- },
1099
- statusCode: {
1100
- serializedName: "statusCode",
1101
- type: {
1102
- name: "Number",
1103
- },
1104
- },
1105
- message: {
1106
- serializedName: "message",
1107
- type: {
1108
- name: "String",
1109
- },
1110
- },
1111
- },
1112
- },
1113
- };
1114
- const MetricDataPoint = {
1115
- type: {
1116
- name: "Composite",
1117
- className: "MetricDataPoint",
1118
- modelProperties: {
1119
- namespace: {
1120
- constraints: {
1121
- MaxLength: 256,
1122
- },
1123
- serializedName: "ns",
1124
- type: {
1125
- name: "String",
1126
- },
1127
- },
1128
- name: {
1129
- constraints: {
1130
- MaxLength: 1024,
1131
- },
1132
- serializedName: "name",
1133
- required: true,
1134
- type: {
1135
- name: "String",
1136
- },
1137
- },
1138
- dataPointType: {
1139
- serializedName: "kind",
1140
- type: {
1141
- name: "String",
1142
- },
1143
- },
1144
- value: {
1145
- serializedName: "value",
1146
- required: true,
1147
- type: {
1148
- name: "Number",
1149
- },
1150
- },
1151
- count: {
1152
- serializedName: "count",
1153
- nullable: true,
1154
- type: {
1155
- name: "Number",
1156
- },
1157
- },
1158
- min: {
1159
- serializedName: "min",
1160
- nullable: true,
1161
- type: {
1162
- name: "Number",
1163
- },
1164
- },
1165
- max: {
1166
- serializedName: "max",
1167
- nullable: true,
1168
- type: {
1169
- name: "Number",
1170
- },
1171
- },
1172
- stdDev: {
1173
- serializedName: "stdDev",
1174
- nullable: true,
1175
- type: {
1176
- name: "Number",
1177
- },
1178
- },
1179
- },
1180
- },
1181
- };
1182
- const TelemetryExceptionDetails = {
1183
- type: {
1184
- name: "Composite",
1185
- className: "TelemetryExceptionDetails",
1186
- modelProperties: {
1187
- id: {
1188
- serializedName: "id",
1189
- type: {
1190
- name: "Number",
1191
- },
1192
- },
1193
- outerId: {
1194
- serializedName: "outerId",
1195
- type: {
1196
- name: "Number",
1197
- },
1198
- },
1199
- typeName: {
1200
- constraints: {
1201
- MaxLength: 1024,
1202
- },
1203
- serializedName: "typeName",
1204
- type: {
1205
- name: "String",
1206
- },
1207
- },
1208
- message: {
1209
- constraints: {
1210
- MaxLength: 32768,
1211
- },
1212
- serializedName: "message",
1213
- required: true,
1214
- type: {
1215
- name: "String",
1216
- },
1217
- },
1218
- hasFullStack: {
1219
- defaultValue: true,
1220
- serializedName: "hasFullStack",
1221
- type: {
1222
- name: "Boolean",
1223
- },
1224
- },
1225
- stack: {
1226
- constraints: {
1227
- MaxLength: 32768,
1228
- },
1229
- serializedName: "stack",
1230
- type: {
1231
- name: "String",
1232
- },
1233
- },
1234
- parsedStack: {
1235
- serializedName: "parsedStack",
1236
- type: {
1237
- name: "Sequence",
1238
- element: {
1239
- type: {
1240
- name: "Composite",
1241
- className: "StackFrame",
1242
- },
1243
- },
1244
- },
1245
- },
1246
- },
1247
- },
1248
- };
1249
- const StackFrame = {
1250
- type: {
1251
- name: "Composite",
1252
- className: "StackFrame",
1253
- modelProperties: {
1254
- level: {
1255
- serializedName: "level",
1256
- required: true,
1257
- type: {
1258
- name: "Number",
1259
- },
1260
- },
1261
- method: {
1262
- constraints: {
1263
- MaxLength: 1024,
1264
- },
1265
- serializedName: "method",
1266
- required: true,
1267
- type: {
1268
- name: "String",
1269
- },
1270
- },
1271
- assembly: {
1272
- constraints: {
1273
- MaxLength: 1024,
1274
- },
1275
- serializedName: "assembly",
1276
- type: {
1277
- name: "String",
1278
- },
1279
- },
1280
- fileName: {
1281
- constraints: {
1282
- MaxLength: 1024,
1283
- },
1284
- serializedName: "fileName",
1285
- type: {
1286
- name: "String",
1287
- },
1288
- },
1289
- line: {
1290
- serializedName: "line",
1291
- type: {
1292
- name: "Number",
1293
- },
1294
- },
1295
- },
1296
- },
1297
- };
1298
- const AvailabilityData = {
1299
- type: {
1300
- name: "Composite",
1301
- className: "AvailabilityData",
1302
- additionalProperties: { type: { name: "Object" } },
1303
- modelProperties: Object.assign(Object.assign({}, MonitorDomain.type.modelProperties), { id: {
1304
- constraints: {
1305
- MaxLength: 512,
1306
- },
1307
- serializedName: "id",
1308
- required: true,
1309
- type: {
1310
- name: "String",
1311
- },
1312
- }, name: {
1313
- constraints: {
1314
- MaxLength: 1024,
1315
- },
1316
- serializedName: "name",
1317
- required: true,
1318
- type: {
1319
- name: "String",
1320
- },
1321
- }, duration: {
1322
- serializedName: "duration",
1323
- required: true,
1324
- type: {
1325
- name: "String",
1326
- },
1327
- }, success: {
1328
- serializedName: "success",
1329
- required: true,
1330
- type: {
1331
- name: "Boolean",
1332
- },
1333
- }, runLocation: {
1334
- constraints: {
1335
- MaxLength: 1024,
1336
- },
1337
- serializedName: "runLocation",
1338
- type: {
1339
- name: "String",
1340
- },
1341
- }, message: {
1342
- constraints: {
1343
- MaxLength: 8192,
1344
- },
1345
- serializedName: "message",
1346
- type: {
1347
- name: "String",
1348
- },
1349
- }, properties: {
1350
- serializedName: "properties",
1351
- type: {
1352
- name: "Dictionary",
1353
- value: { type: { name: "String" }, constraints: { MaxLength: 8192 } },
1354
- },
1355
- }, measurements: {
1356
- serializedName: "measurements",
1357
- type: {
1358
- name: "Dictionary",
1359
- value: { type: { name: "Number" } },
1360
- },
1361
- } }),
1362
- },
1363
- };
1364
- const TelemetryEventData = {
1365
- type: {
1366
- name: "Composite",
1367
- className: "TelemetryEventData",
1368
- additionalProperties: { type: { name: "Object" } },
1369
- modelProperties: Object.assign(Object.assign({}, MonitorDomain.type.modelProperties), { name: {
1370
- constraints: {
1371
- MaxLength: 512,
1372
- },
1373
- serializedName: "name",
1374
- required: true,
1375
- type: {
1376
- name: "String",
1377
- },
1378
- }, properties: {
1379
- serializedName: "properties",
1380
- type: {
1381
- name: "Dictionary",
1382
- value: { type: { name: "String" }, constraints: { MaxLength: 8192 } },
1383
- },
1384
- }, measurements: {
1385
- serializedName: "measurements",
1386
- type: {
1387
- name: "Dictionary",
1388
- value: { type: { name: "Number" } },
1389
- },
1390
- } }),
1391
- },
1392
- };
1393
- const TelemetryExceptionData = {
1394
- type: {
1395
- name: "Composite",
1396
- className: "TelemetryExceptionData",
1397
- additionalProperties: { type: { name: "Object" } },
1398
- modelProperties: Object.assign(Object.assign({}, MonitorDomain.type.modelProperties), { exceptions: {
1399
- serializedName: "exceptions",
1400
- required: true,
1401
- type: {
1402
- name: "Sequence",
1403
- element: {
1404
- type: {
1405
- name: "Composite",
1406
- className: "TelemetryExceptionDetails",
1407
- },
1408
- },
1409
- },
1410
- }, severityLevel: {
1411
- serializedName: "severityLevel",
1412
- nullable: true,
1413
- type: {
1414
- name: "String",
1415
- },
1416
- }, problemId: {
1417
- constraints: {
1418
- MaxLength: 1024,
1419
- },
1420
- serializedName: "problemId",
1421
- type: {
1422
- name: "String",
1423
- },
1424
- }, properties: {
1425
- serializedName: "properties",
1426
- type: {
1427
- name: "Dictionary",
1428
- value: { type: { name: "String" }, constraints: { MaxLength: 8192 } },
1429
- },
1430
- }, measurements: {
1431
- serializedName: "measurements",
1432
- type: {
1433
- name: "Dictionary",
1434
- value: { type: { name: "Number" } },
1435
- },
1436
- } }),
1437
- },
1438
- };
1439
- const MessageData = {
1440
- type: {
1441
- name: "Composite",
1442
- className: "MessageData",
1443
- additionalProperties: { type: { name: "Object" } },
1444
- modelProperties: Object.assign(Object.assign({}, MonitorDomain.type.modelProperties), { message: {
1445
- constraints: {
1446
- MaxLength: 32768,
1447
- },
1448
- serializedName: "message",
1449
- required: true,
1450
- type: {
1451
- name: "String",
1452
- },
1453
- }, severityLevel: {
1454
- serializedName: "severityLevel",
1455
- type: {
1456
- name: "String",
1457
- },
1458
- }, properties: {
1459
- serializedName: "properties",
1460
- type: {
1461
- name: "Dictionary",
1462
- value: { type: { name: "String" }, constraints: { MaxLength: 8192 } },
1463
- },
1464
- }, measurements: {
1465
- serializedName: "measurements",
1466
- type: {
1467
- name: "Dictionary",
1468
- value: { type: { name: "Number" } },
1469
- },
1470
- } }),
1471
- },
1472
- };
1473
- const MetricsData = {
1474
- type: {
1475
- name: "Composite",
1476
- className: "MetricsData",
1477
- additionalProperties: { type: { name: "Object" } },
1478
- modelProperties: Object.assign(Object.assign({}, MonitorDomain.type.modelProperties), { metrics: {
1479
- serializedName: "metrics",
1480
- required: true,
1481
- type: {
1482
- name: "Sequence",
1483
- element: {
1484
- type: {
1485
- name: "Composite",
1486
- className: "MetricDataPoint",
1487
- },
1488
- },
1489
- },
1490
- }, properties: {
1491
- serializedName: "properties",
1492
- type: {
1493
- name: "Dictionary",
1494
- value: { type: { name: "String" }, constraints: { MaxLength: 8192 } },
1495
- },
1496
- } }),
1497
- },
1498
- };
1499
- const PageViewData = {
1500
- type: {
1501
- name: "Composite",
1502
- className: "PageViewData",
1503
- additionalProperties: { type: { name: "Object" } },
1504
- modelProperties: Object.assign(Object.assign({}, MonitorDomain.type.modelProperties), { id: {
1505
- constraints: {
1506
- MaxLength: 512,
1507
- },
1508
- serializedName: "id",
1509
- required: true,
1510
- type: {
1511
- name: "String",
1512
- },
1513
- }, name: {
1514
- constraints: {
1515
- MaxLength: 1024,
1516
- },
1517
- serializedName: "name",
1518
- required: true,
1519
- type: {
1520
- name: "String",
1521
- },
1522
- }, url: {
1523
- constraints: {
1524
- MaxLength: 2048,
1525
- },
1526
- serializedName: "url",
1527
- type: {
1528
- name: "String",
1529
- },
1530
- }, duration: {
1531
- serializedName: "duration",
1532
- type: {
1533
- name: "String",
1534
- },
1535
- }, referredUri: {
1536
- constraints: {
1537
- MaxLength: 2048,
1538
- },
1539
- serializedName: "referredUri",
1540
- type: {
1541
- name: "String",
1542
- },
1543
- }, properties: {
1544
- serializedName: "properties",
1545
- type: {
1546
- name: "Dictionary",
1547
- value: { type: { name: "String" }, constraints: { MaxLength: 8192 } },
1548
- },
1549
- }, measurements: {
1550
- serializedName: "measurements",
1551
- type: {
1552
- name: "Dictionary",
1553
- value: { type: { name: "Number" } },
1554
- },
1555
- } }),
1556
- },
1557
- };
1558
- const PageViewPerfData = {
1559
- type: {
1560
- name: "Composite",
1561
- className: "PageViewPerfData",
1562
- additionalProperties: { type: { name: "Object" } },
1563
- modelProperties: Object.assign(Object.assign({}, MonitorDomain.type.modelProperties), { id: {
1564
- constraints: {
1565
- MaxLength: 512,
1566
- },
1567
- serializedName: "id",
1568
- required: true,
1569
- type: {
1570
- name: "String",
1571
- },
1572
- }, name: {
1573
- constraints: {
1574
- MaxLength: 1024,
1575
- },
1576
- serializedName: "name",
1577
- required: true,
1578
- type: {
1579
- name: "String",
1580
- },
1581
- }, url: {
1582
- constraints: {
1583
- MaxLength: 2048,
1584
- },
1585
- serializedName: "url",
1586
- type: {
1587
- name: "String",
1588
- },
1589
- }, duration: {
1590
- serializedName: "duration",
1591
- type: {
1592
- name: "String",
1593
- },
1594
- }, perfTotal: {
1595
- serializedName: "perfTotal",
1596
- type: {
1597
- name: "String",
1598
- },
1599
- }, networkConnect: {
1600
- serializedName: "networkConnect",
1601
- type: {
1602
- name: "String",
1603
- },
1604
- }, sentRequest: {
1605
- serializedName: "sentRequest",
1606
- type: {
1607
- name: "String",
1608
- },
1609
- }, receivedResponse: {
1610
- serializedName: "receivedResponse",
1611
- type: {
1612
- name: "String",
1613
- },
1614
- }, domProcessing: {
1615
- serializedName: "domProcessing",
1616
- type: {
1617
- name: "String",
1618
- },
1619
- }, properties: {
1620
- serializedName: "properties",
1621
- type: {
1622
- name: "Dictionary",
1623
- value: { type: { name: "String" }, constraints: { MaxLength: 8192 } },
1624
- },
1625
- }, measurements: {
1626
- serializedName: "measurements",
1627
- type: {
1628
- name: "Dictionary",
1629
- value: { type: { name: "Number" } },
1630
- },
1631
- } }),
1632
- },
1633
- };
1634
- const RemoteDependencyData = {
1635
- type: {
1636
- name: "Composite",
1637
- className: "RemoteDependencyData",
1638
- additionalProperties: { type: { name: "Object" } },
1639
- modelProperties: Object.assign(Object.assign({}, MonitorDomain.type.modelProperties), { id: {
1640
- constraints: {
1641
- MaxLength: 512,
1642
- },
1643
- serializedName: "id",
1644
- type: {
1645
- name: "String",
1646
- },
1647
- }, name: {
1648
- constraints: {
1649
- MaxLength: 1024,
1650
- },
1651
- serializedName: "name",
1652
- required: true,
1653
- type: {
1654
- name: "String",
1655
- },
1656
- }, resultCode: {
1657
- constraints: {
1658
- MaxLength: 1024,
1659
- },
1660
- serializedName: "resultCode",
1661
- type: {
1662
- name: "String",
1663
- },
1664
- }, data: {
1665
- constraints: {
1666
- MaxLength: 8192,
1667
- },
1668
- serializedName: "data",
1669
- type: {
1670
- name: "String",
1671
- },
1672
- }, type: {
1673
- constraints: {
1674
- MaxLength: 1024,
1675
- },
1676
- serializedName: "type",
1677
- type: {
1678
- name: "String",
1679
- },
1680
- }, target: {
1681
- constraints: {
1682
- MaxLength: 1024,
1683
- },
1684
- serializedName: "target",
1685
- type: {
1686
- name: "String",
1687
- },
1688
- }, duration: {
1689
- serializedName: "duration",
1690
- required: true,
1691
- type: {
1692
- name: "String",
1693
- },
1694
- }, success: {
1695
- defaultValue: true,
1696
- serializedName: "success",
1697
- type: {
1698
- name: "Boolean",
1699
- },
1700
- }, properties: {
1701
- serializedName: "properties",
1702
- type: {
1703
- name: "Dictionary",
1704
- value: { type: { name: "String" }, constraints: { MaxLength: 8192 } },
1705
- },
1706
- }, measurements: {
1707
- serializedName: "measurements",
1708
- type: {
1709
- name: "Dictionary",
1710
- value: { type: { name: "Number" } },
1711
- },
1712
- } }),
1713
- },
1714
- };
1715
- const RequestData = {
1716
- type: {
1717
- name: "Composite",
1718
- className: "RequestData",
1719
- additionalProperties: { type: { name: "Object" } },
1720
- modelProperties: Object.assign(Object.assign({}, MonitorDomain.type.modelProperties), { id: {
1721
- constraints: {
1722
- MaxLength: 512,
1723
- },
1724
- serializedName: "id",
1725
- required: true,
1726
- type: {
1727
- name: "String",
1728
- },
1729
- }, name: {
1730
- constraints: {
1731
- MaxLength: 1024,
1732
- },
1733
- serializedName: "name",
1734
- type: {
1735
- name: "String",
1736
- },
1737
- }, duration: {
1738
- serializedName: "duration",
1739
- required: true,
1740
- type: {
1741
- name: "String",
1742
- },
1743
- }, success: {
1744
- defaultValue: true,
1745
- serializedName: "success",
1746
- required: true,
1747
- type: {
1748
- name: "Boolean",
1749
- },
1750
- }, responseCode: {
1751
- constraints: {
1752
- MaxLength: 1024,
1753
- },
1754
- serializedName: "responseCode",
1755
- required: true,
1756
- type: {
1757
- name: "String",
1758
- },
1759
- }, source: {
1760
- constraints: {
1761
- MaxLength: 1024,
1762
- },
1763
- serializedName: "source",
1764
- type: {
1765
- name: "String",
1766
- },
1767
- }, url: {
1768
- constraints: {
1769
- MaxLength: 2048,
1770
- },
1771
- serializedName: "url",
1772
- type: {
1773
- name: "String",
1774
- },
1775
- }, properties: {
1776
- serializedName: "properties",
1777
- type: {
1778
- name: "Dictionary",
1779
- value: { type: { name: "String" }, constraints: { MaxLength: 8192 } },
1780
- },
1781
- }, measurements: {
1782
- serializedName: "measurements",
1783
- type: {
1784
- name: "Dictionary",
1785
- value: { type: { name: "Number" } },
1786
- },
1787
- } }),
1788
- },
1789
- };
1790
-
1791
- var Mappers = /*#__PURE__*/Object.freeze({
1792
- __proto__: null,
1793
- AvailabilityData: AvailabilityData,
1794
- MessageData: MessageData,
1795
- MetricDataPoint: MetricDataPoint,
1796
- MetricsData: MetricsData,
1797
- MonitorBase: MonitorBase,
1798
- MonitorDomain: MonitorDomain,
1799
- PageViewData: PageViewData,
1800
- PageViewPerfData: PageViewPerfData,
1801
- RemoteDependencyData: RemoteDependencyData,
1802
- RequestData: RequestData,
1803
- StackFrame: StackFrame,
1804
- TelemetryErrorDetails: TelemetryErrorDetails,
1805
- TelemetryEventData: TelemetryEventData,
1806
- TelemetryExceptionData: TelemetryExceptionData,
1807
- TelemetryExceptionDetails: TelemetryExceptionDetails,
1808
- TelemetryItem: TelemetryItem,
1809
- TrackResponse: TrackResponse
1810
- });
1811
-
1812
- /*
1813
- * Copyright (c) Microsoft Corporation.
1814
- * Licensed under the MIT License.
1815
- *
1816
- * Code generated by Microsoft (R) AutoRest Code Generator.
1817
- * Changes may cause incorrect behavior and will be lost if the code is regenerated.
1818
- */
1819
- class ApplicationInsightsClient extends coreClient__namespace.ServiceClient {
1820
- /**
1821
- * Initializes a new instance of the ApplicationInsightsClient class.
1822
- * @param options The parameter options
1823
- */
1824
- constructor(options) {
1825
- var _a, _b;
1826
- // Initializing default values for options
1827
- if (!options) {
1828
- options = {};
1829
- }
1830
- const defaults = {
1831
- requestContentType: "application/json; charset=utf-8",
1832
- };
1833
- const packageDetails = `azsdk-js-monitor-opentelemetry-exporter/1.0.0-beta.27`;
1834
- const userAgentPrefix = options.userAgentOptions && options.userAgentOptions.userAgentPrefix
1835
- ? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}`
1836
- : `${packageDetails}`;
1837
- const optionsWithDefaults = Object.assign(Object.assign(Object.assign({}, defaults), options), { userAgentOptions: {
1838
- userAgentPrefix,
1839
- }, endpoint: (_b = (_a = options.endpoint) !== null && _a !== void 0 ? _a : options.baseUri) !== null && _b !== void 0 ? _b : "{Host}/v2.1" });
1840
- super(optionsWithDefaults);
1841
- // Assigning values to Constant parameters
1842
- this.host = options.host || "https://dc.services.visualstudio.com";
1843
- }
1844
- /**
1845
- * This operation sends a sequence of telemetry events that will be monitored by Azure Monitor.
1846
- * @param body The list of telemetry events to track.
1847
- * @param options The options parameters.
1848
- */
1849
- track(body, options) {
1850
- return this.sendOperationRequest({ body, options }, trackOperationSpec);
1851
- }
1852
- }
1853
- // Operation Specifications
1854
- const serializer = coreClient__namespace.createSerializer(Mappers, /* isXml */ false);
1855
- const trackOperationSpec = {
1856
- path: "/track",
1857
- httpMethod: "POST",
1858
- responses: {
1859
- 200: {
1860
- bodyMapper: TrackResponse,
1861
- },
1862
- 206: {
1863
- bodyMapper: TrackResponse,
1864
- },
1865
- 400: {
1866
- bodyMapper: TrackResponse,
1867
- isError: true,
1868
- },
1869
- 402: {
1870
- bodyMapper: TrackResponse,
1871
- isError: true,
1872
- },
1873
- 429: {
1874
- bodyMapper: TrackResponse,
1875
- isError: true,
1876
- },
1877
- 500: {
1878
- bodyMapper: TrackResponse,
1879
- isError: true,
1880
- },
1881
- 503: {
1882
- bodyMapper: TrackResponse,
1883
- isError: true,
1884
- },
1885
- },
1886
- requestBody: body,
1887
- urlParameters: [host],
1888
- headerParameters: [contentType, accept],
1889
- mediaType: "json",
1890
- serializer,
1891
- };
1892
-
1893
- // Copyright (c) Microsoft Corporation.
1894
- // Licensed under the MIT License.
1895
- class NetworkStatsbeat {
1896
- constructor(endpoint, host) {
1897
- this.endpoint = endpoint;
1898
- this.host = host;
1899
- this.totalRequestCount = 0;
1900
- this.totalSuccesfulRequestCount = 0;
1901
- this.totalReadFailureCount = 0;
1902
- this.totalWriteFailureCount = 0;
1903
- this.totalFailedRequestCount = [];
1904
- this.retryCount = [];
1905
- this.exceptionCount = [];
1906
- this.throttleCount = [];
1907
- this.intervalRequestExecutionTime = 0;
1908
- this.lastIntervalRequestExecutionTime = 0;
1909
- this.lastTime = +new Date();
1910
- this.lastRequestCount = 0;
1911
- this.averageRequestExecutionTime = 0;
1912
- }
1913
- }
1914
- const STATSBEAT_LANGUAGE = "node";
1915
- const MAX_STATSBEAT_FAILURES = 3;
1916
- const StatsbeatResourceProvider = {
1917
- appsvc: "appsvc",
1918
- aks: "aks",
1919
- functions: "functions",
1920
- vm: "vm",
1921
- unknown: "unknown",
1922
- };
1923
- var StatsbeatCounter;
1924
- (function (StatsbeatCounter) {
1925
- StatsbeatCounter["SUCCESS_COUNT"] = "Request_Success_Count";
1926
- StatsbeatCounter["FAILURE_COUNT"] = "Request_Failure_Count";
1927
- StatsbeatCounter["RETRY_COUNT"] = "Retry_Count";
1928
- StatsbeatCounter["THROTTLE_COUNT"] = "Throttle_Count";
1929
- StatsbeatCounter["EXCEPTION_COUNT"] = "Exception_Count";
1930
- StatsbeatCounter["AVERAGE_DURATION"] = "Request_Duration";
1931
- StatsbeatCounter["READ_FAILURE_COUNT"] = "Read_Failure_Count";
1932
- StatsbeatCounter["WRITE_FAILURE_COUNT"] = "Write_Failure_Count";
1933
- StatsbeatCounter["ATTACH"] = "Attach";
1934
- StatsbeatCounter["FEATURE"] = "Feature";
1935
- })(StatsbeatCounter || (StatsbeatCounter = {}));
1936
- const AIMS_URI = "http://169.254.169.254/metadata/instance/compute";
1937
- const AIMS_API_VERSION = "api-version=2017-12-01";
1938
- const AIMS_FORMAT = "format=json";
1939
- const NON_EU_CONNECTION_STRING = "InstrumentationKey=c4a29126-a7cb-47e5-b348-11414998b11e;IngestionEndpoint=https://westus-0.in.applicationinsights.azure.com";
1940
- const EU_CONNECTION_STRING = "InstrumentationKey=7dc56bab-3c0c-4e9f-9ebb-d1acadee8d0f;IngestionEndpoint=https://westeurope-5.in.applicationinsights.azure.com";
1941
- const EU_ENDPOINTS = [
1942
- "westeurope",
1943
- "northeurope",
1944
- "francecentral",
1945
- "francesouth",
1946
- "germanywestcentral",
1947
- "norwayeast",
1948
- "norwaywest",
1949
- "swedencentral",
1950
- "switzerlandnorth",
1951
- "switzerlandwest",
1952
- "uksouth",
1953
- "ukwest",
1954
- ];
1955
- var StatsbeatFeatureType;
1956
- (function (StatsbeatFeatureType) {
1957
- StatsbeatFeatureType[StatsbeatFeatureType["FEATURE"] = 0] = "FEATURE";
1958
- StatsbeatFeatureType[StatsbeatFeatureType["INSTRUMENTATION"] = 1] = "INSTRUMENTATION";
1959
- })(StatsbeatFeatureType || (StatsbeatFeatureType = {}));
1960
- /**
1961
- * Status codes indicating that we should shutdown statsbeat
1962
- * @internal
1963
- */
1964
- function isStatsbeatShutdownStatus(statusCode) {
1965
- return (statusCode === 401 || // Unauthorized
1966
- statusCode === 403 || // Forbidden
1967
- statusCode === 503 // Server Unavailable
1968
- );
1969
- }
1970
-
1971
- // Copyright (c) Microsoft Corporation.
1972
- // Licensed under the MIT License.
1973
- // eslint-disable-next-line @typescript-eslint/no-require-imports
1974
- const os = require("os");
1975
- class StatsbeatMetrics {
1976
- constructor() {
1977
- this.resourceProvider = StatsbeatResourceProvider.unknown;
1978
- this.vmInfo = {};
1979
- this.os = os.type();
1980
- this.resourceIdentifier = "";
1981
- }
1982
- async getResourceProvider() {
1983
- // Check resource provider
1984
- this.resourceProvider = StatsbeatResourceProvider.unknown;
1985
- if (process.env.AKS_ARM_NAMESPACE_ID) {
1986
- // AKS
1987
- this.resourceProvider = StatsbeatResourceProvider.aks;
1988
- this.resourceIdentifier = process.env.AKS_ARM_NAMESPACE_ID;
1989
- }
1990
- else if (process.env.WEBSITE_SITE_NAME) {
1991
- // Web apps
1992
- this.resourceProvider = StatsbeatResourceProvider.appsvc;
1993
- this.resourceIdentifier = process.env.WEBSITE_SITE_NAME;
1994
- if (process.env.WEBSITE_HOME_STAMPNAME) {
1995
- this.resourceIdentifier += "/" + process.env.WEBSITE_HOME_STAMPNAME;
1996
- }
1997
- }
1998
- else if (process.env.FUNCTIONS_WORKER_RUNTIME) {
1999
- // Function apps
2000
- this.resourceProvider = StatsbeatResourceProvider.functions;
2001
- if (process.env.WEBSITE_HOSTNAME) {
2002
- this.resourceIdentifier = process.env.WEBSITE_HOSTNAME;
2003
- }
2004
- }
2005
- else if (await this.getAzureComputeMetadata()) {
2006
- this.resourceProvider = StatsbeatResourceProvider.vm;
2007
- this.resourceIdentifier = this.vmInfo.id + "/" + this.vmInfo.subscriptionId;
2008
- // Overrride OS as VM info have higher precedence
2009
- if (this.vmInfo.osType) {
2010
- this.os = this.vmInfo.osType;
2011
- }
2012
- }
2013
- else {
2014
- this.resourceProvider = StatsbeatResourceProvider.unknown;
2015
- }
2016
- }
2017
- async getAzureComputeMetadata() {
2018
- const httpClient = coreRestPipeline.createDefaultHttpClient();
2019
- const method = "GET";
2020
- const options = {
2021
- url: `${AIMS_URI}?${AIMS_API_VERSION}&${AIMS_FORMAT}`,
2022
- timeout: 5000, // 5 seconds
2023
- method: method,
2024
- allowInsecureConnection: true,
2025
- };
2026
- const request = coreRestPipeline.createPipelineRequest(options);
2027
- await httpClient
2028
- .sendRequest(request)
2029
- .then((res) => {
2030
- if (res.status === 200) {
2031
- // Success; VM
2032
- this.vmInfo.isVM = true;
2033
- let virtualMachineData = "";
2034
- res.on("data", (data) => {
2035
- virtualMachineData += data;
2036
- });
2037
- res.on("end", () => {
2038
- try {
2039
- const data = JSON.parse(virtualMachineData);
2040
- this.vmInfo.id = data["vmId"] || "";
2041
- this.vmInfo.subscriptionId = data["subscriptionId"] || "";
2042
- this.vmInfo.osType = data["osType"] || "";
2043
- }
2044
- catch (error) {
2045
- api.diag.debug("Failed to parse JSON: ", error);
2046
- }
2047
- });
2048
- return true;
2049
- }
2050
- else {
2051
- return false;
2052
- }
2053
- })
2054
- .catch(() => {
2055
- return false;
2056
- });
2057
- return false;
2058
- }
2059
- getConnectionString(endpointUrl) {
2060
- const currentEndpoint = endpointUrl;
2061
- for (let i = 0; i < EU_ENDPOINTS.length; i++) {
2062
- if (currentEndpoint.includes(EU_ENDPOINTS[i])) {
2063
- return EU_CONNECTION_STRING;
2064
- }
2065
- }
2066
- return NON_EU_CONNECTION_STRING;
2067
- }
2068
- }
2069
-
2070
- // Copyright (c) Microsoft Corporation.
2071
- // Licensed under the MIT License.
2072
- /**
2073
- * Performance Counter OpenTelemetry compliant names.
2074
- * @internal
2075
- */
2076
- var OTelPerformanceCounterNames;
2077
- (function (OTelPerformanceCounterNames) {
2078
- OTelPerformanceCounterNames["PRIVATE_BYTES"] = "Private_Bytes";
2079
- OTelPerformanceCounterNames["AVAILABLE_BYTES"] = "Available_Bytes";
2080
- OTelPerformanceCounterNames["PROCESSOR_TIME"] = "Processor_Time";
2081
- OTelPerformanceCounterNames["PROCESS_TIME"] = "Process_Time";
2082
- OTelPerformanceCounterNames["REQUEST_RATE"] = "Request_Rate";
2083
- OTelPerformanceCounterNames["REQUEST_DURATION"] = "Request_Execution_Time";
2084
- })(OTelPerformanceCounterNames || (OTelPerformanceCounterNames = {}));
2085
- /**
2086
- * Breeze Performance Counter names.
2087
- * @internal
2088
- */
2089
- var BreezePerformanceCounterNames;
2090
- (function (BreezePerformanceCounterNames) {
2091
- BreezePerformanceCounterNames["PRIVATE_BYTES"] = "\\Process(??APP_WIN32_PROC??)\\Private Bytes";
2092
- BreezePerformanceCounterNames["AVAILABLE_BYTES"] = "\\Memory\\Available Bytes";
2093
- BreezePerformanceCounterNames["PROCESSOR_TIME"] = "\\Processor(_Total)\\% Processor Time";
2094
- BreezePerformanceCounterNames["PROCESS_TIME"] = "\\Process(??APP_WIN32_PROC??)\\% Processor Time";
2095
- BreezePerformanceCounterNames["REQUEST_RATE"] = "\\ASP.NET Applications(??APP_W3SVC_PROC??)\\Requests/Sec";
2096
- BreezePerformanceCounterNames["REQUEST_DURATION"] = "\\ASP.NET Applications(??APP_W3SVC_PROC??)\\Request Execution Time";
2097
- })(BreezePerformanceCounterNames || (BreezePerformanceCounterNames = {}));
2098
- /**
2099
- * Property Max Lengths
2100
- * @internal
2101
- */
2102
- var MaxPropertyLengths;
2103
- (function (MaxPropertyLengths) {
2104
- MaxPropertyLengths[MaxPropertyLengths["NINE_BIT"] = 512] = "NINE_BIT";
2105
- MaxPropertyLengths[MaxPropertyLengths["TEN_BIT"] = 1024] = "TEN_BIT";
2106
- MaxPropertyLengths[MaxPropertyLengths["THIRTEEN_BIT"] = 8192] = "THIRTEEN_BIT";
2107
- MaxPropertyLengths[MaxPropertyLengths["FIFTEEN_BIT"] = 32768] = "FIFTEEN_BIT";
2108
- })(MaxPropertyLengths || (MaxPropertyLengths = {}));
2109
-
2110
- // Copyright (c) Microsoft Corporation.
2111
- // Licensed under the MIT License.
2112
- const breezePerformanceCountersMap = new Map([
2113
- [OTelPerformanceCounterNames.PRIVATE_BYTES, BreezePerformanceCounterNames.PRIVATE_BYTES],
2114
- [OTelPerformanceCounterNames.AVAILABLE_BYTES, BreezePerformanceCounterNames.AVAILABLE_BYTES],
2115
- [OTelPerformanceCounterNames.PROCESSOR_TIME, BreezePerformanceCounterNames.PROCESSOR_TIME],
2116
- [OTelPerformanceCounterNames.PROCESS_TIME, BreezePerformanceCounterNames.PROCESS_TIME],
2117
- [OTelPerformanceCounterNames.REQUEST_RATE, BreezePerformanceCounterNames.REQUEST_RATE],
2118
- [OTelPerformanceCounterNames.REQUEST_DURATION, BreezePerformanceCounterNames.REQUEST_DURATION],
2119
- ]);
2120
- function createPropertiesFromMetricAttributes(attributes) {
2121
- const properties = {};
2122
- if (attributes) {
2123
- for (const key of Object.keys(attributes)) {
2124
- properties[key] = attributes[key];
2125
- }
2126
- }
2127
- return properties;
2128
- }
2129
- /**
2130
- * Metric to Azure envelope parsing.
2131
- * @internal
2132
- */
2133
- function resourceMetricsToEnvelope(metrics, ikey, isStatsbeat) {
2134
- const envelopes = [];
2135
- const time = new Date();
2136
- const instrumentationKey = ikey;
2137
- const tags = createTagsFromResource(metrics.resource);
2138
- let envelopeName;
2139
- if (isStatsbeat) {
2140
- envelopeName = "Microsoft.ApplicationInsights.Statsbeat";
2141
- }
2142
- else {
2143
- envelopeName = "Microsoft.ApplicationInsights.Metric";
2144
- }
2145
- metrics.scopeMetrics.forEach((scopeMetric) => {
2146
- scopeMetric.metrics.forEach((metric) => {
2147
- metric.dataPoints.forEach((dataPoint) => {
2148
- const baseData = {
2149
- metrics: [],
2150
- version: 2,
2151
- properties: {},
2152
- };
2153
- baseData.properties = createPropertiesFromMetricAttributes(dataPoint.attributes);
2154
- let perfCounterName;
2155
- if (breezePerformanceCountersMap.has(metric.descriptor.name)) {
2156
- perfCounterName = breezePerformanceCountersMap.get(metric.descriptor.name);
2157
- }
2158
- const metricDataPoint = {
2159
- name: perfCounterName ? perfCounterName : metric.descriptor.name,
2160
- value: 0,
2161
- dataPointType: "Aggregation",
2162
- };
2163
- if (metric.dataPointType === sdkMetrics.DataPointType.SUM ||
2164
- metric.dataPointType === sdkMetrics.DataPointType.GAUGE) {
2165
- metricDataPoint.value = dataPoint.value;
2166
- metricDataPoint.count = 1;
2167
- }
2168
- else {
2169
- metricDataPoint.value = dataPoint.value.sum || 0;
2170
- metricDataPoint.count = dataPoint.value.count;
2171
- metricDataPoint.max = dataPoint.value.max;
2172
- metricDataPoint.min = dataPoint.value.min;
2173
- }
2174
- baseData.metrics.push(metricDataPoint);
2175
- const envelope = {
2176
- name: envelopeName,
2177
- time: time,
2178
- sampleRate: 100, // Metrics are never sampled
2179
- instrumentationKey: instrumentationKey,
2180
- tags: tags,
2181
- version: 1,
2182
- data: {
2183
- baseType: "MetricData",
2184
- baseData: Object.assign({}, baseData),
2185
- },
2186
- };
2187
- envelopes.push(envelope);
2188
- });
2189
- });
2190
- });
2191
- return envelopes;
2192
- }
2193
-
2194
- // Copyright (c) Microsoft Corporation.
2195
- // Licensed under the MIT License.
2196
- /**
2197
- * Azure Monitor Statsbeat Exporter
2198
- */
2199
- class AzureMonitorStatsbeatExporter extends AzureMonitorBaseExporter {
2200
- /**
2201
- * Initializes a new instance of the AzureMonitorStatsbeatExporter class.
2202
- * @param options - Exporter configuration
2203
- */
2204
- constructor(options) {
2205
- super(options, true);
2206
- /**
2207
- * Flag to determine if the Exporter is shutdown.
2208
- */
2209
- this._isShutdown = false;
2210
- this._sender = new HttpSender({
2211
- endpointUrl: this.endpointUrl,
2212
- instrumentationKey: this.instrumentationKey,
2213
- trackStatsbeat: this.trackStatsbeat,
2214
- exporterOptions: options,
2215
- isStatsbeatSender: true,
2216
- });
2217
- }
2218
- /**
2219
- * Export Statsbeat metrics.
2220
- */
2221
- // eslint-disable-next-line @typescript-eslint/require-await, @typescript-eslint/no-misused-promises
2222
- async export(metrics, resultCallback) {
2223
- if (this._isShutdown) {
2224
- setTimeout(() => resultCallback({ code: core.ExportResultCode.FAILED }), 0);
2225
- return;
2226
- }
2227
- const envelopes = resourceMetricsToEnvelope(metrics, this.instrumentationKey, true);
2228
- // Supress tracing until OpenTelemetry Metrics SDK support it
2229
- api.context.with(core.suppressTracing(api.context.active()), async () => {
2230
- resultCallback(await this._sender.exportEnvelopes(envelopes));
2231
- });
2232
- }
2233
- /**
2234
- * Shutdown AzureMonitorStatsbeatExporter.
2235
- */
2236
- async shutdown() {
2237
- this._isShutdown = true;
2238
- return this._sender.shutdown();
2239
- }
2240
- /**
2241
- * Force flush.
2242
- */
2243
- async forceFlush() {
2244
- return Promise.resolve();
2245
- }
2246
- }
2247
-
2248
- // Copyright (c) Microsoft Corporation.
2249
- // Licensed under the MIT License.
2250
- class NetworkStatsbeatMetrics extends StatsbeatMetrics {
2251
- constructor(options) {
2252
- super();
2253
- this.disableNonEssentialStatsbeat = !!process.env[ENV_DISABLE_STATSBEAT];
2254
- this.isInitialized = false;
2255
- this.statsCollectionShortInterval = 900000; // 15 minutes
2256
- this.networkStatsbeatCollection = [];
2257
- this.attach = "Manual";
2258
- this.connectionString = super.getConnectionString(options.endpointUrl);
2259
- this.networkStatsbeatMeterProvider = new sdkMetrics.MeterProvider();
2260
- const exporterConfig = {
2261
- connectionString: this.connectionString,
2262
- };
2263
- this.networkAzureExporter = new AzureMonitorStatsbeatExporter(exporterConfig);
2264
- // Exports Network Statsbeat every 15 minutes
2265
- const networkMetricReaderOptions = {
2266
- exporter: this.networkAzureExporter,
2267
- exportIntervalMillis: options.networkCollectionInterval || this.statsCollectionShortInterval, // 15 minutes
2268
- };
2269
- this.networkMetricReader = new sdkMetrics.PeriodicExportingMetricReader(networkMetricReaderOptions);
2270
- this.networkStatsbeatMeterProvider.addMetricReader(this.networkMetricReader);
2271
- this.networkStatsbeatMeter = this.networkStatsbeatMeterProvider.getMeter("Azure Monitor Network Statsbeat");
2272
- this.endpointUrl = options.endpointUrl;
2273
- this.runtimeVersion = process.version;
2274
- this.language = STATSBEAT_LANGUAGE;
2275
- this.version = packageVersion;
2276
- this.host = this.getShortHost(options.endpointUrl);
2277
- this.cikey = options.instrumentationKey;
2278
- this.successCountGauge = this.networkStatsbeatMeter.createObservableGauge(StatsbeatCounter.SUCCESS_COUNT);
2279
- this.failureCountGauge = this.networkStatsbeatMeter.createObservableGauge(StatsbeatCounter.FAILURE_COUNT);
2280
- this.retryCountGauge = this.networkStatsbeatMeter.createObservableGauge(StatsbeatCounter.RETRY_COUNT);
2281
- this.throttleCountGauge = this.networkStatsbeatMeter.createObservableGauge(StatsbeatCounter.THROTTLE_COUNT);
2282
- this.exceptionCountGauge = this.networkStatsbeatMeter.createObservableGauge(StatsbeatCounter.EXCEPTION_COUNT);
2283
- this.averageDurationGauge = this.networkStatsbeatMeter.createObservableGauge(StatsbeatCounter.AVERAGE_DURATION);
2284
- if (!this.disableNonEssentialStatsbeat) {
2285
- this.readFailureGauge = this.networkStatsbeatMeter.createObservableGauge(StatsbeatCounter.READ_FAILURE_COUNT);
2286
- this.writeFailureGauge = this.networkStatsbeatMeter.createObservableGauge(StatsbeatCounter.WRITE_FAILURE_COUNT);
2287
- }
2288
- this.commonProperties = {
2289
- os: this.os,
2290
- rp: this.resourceProvider,
2291
- cikey: this.cikey,
2292
- runtimeVersion: this.runtimeVersion,
2293
- language: this.language,
2294
- version: this.version,
2295
- attach: this.attach,
2296
- };
2297
- this.networkProperties = {
2298
- endpoint: this.endpointUrl,
2299
- host: this.host,
2300
- };
2301
- this.isInitialized = true;
2302
- this.initialize();
2303
- }
2304
- shutdown() {
2305
- return this.networkStatsbeatMeterProvider.shutdown();
2306
- }
2307
- async initialize() {
2308
- var _a, _b;
2309
- try {
2310
- await super.getResourceProvider();
2311
- // Add network observable callbacks
2312
- this.successCountGauge.addCallback(this.successCallback.bind(this));
2313
- this.networkStatsbeatMeter.addBatchObservableCallback(this.failureCallback.bind(this), [
2314
- this.failureCountGauge,
2315
- ]);
2316
- this.networkStatsbeatMeter.addBatchObservableCallback(this.retryCallback.bind(this), [
2317
- this.retryCountGauge,
2318
- ]);
2319
- this.networkStatsbeatMeter.addBatchObservableCallback(this.throttleCallback.bind(this), [
2320
- this.throttleCountGauge,
2321
- ]);
2322
- this.networkStatsbeatMeter.addBatchObservableCallback(this.exceptionCallback.bind(this), [
2323
- this.exceptionCountGauge,
2324
- ]);
2325
- if (!this.disableNonEssentialStatsbeat) {
2326
- (_a = this.readFailureGauge) === null || _a === void 0 ? void 0 : _a.addCallback(this.readFailureCallback.bind(this));
2327
- (_b = this.writeFailureGauge) === null || _b === void 0 ? void 0 : _b.addCallback(this.writeFailureCallback.bind(this));
2328
- }
2329
- this.averageDurationGauge.addCallback(this.durationCallback.bind(this));
2330
- }
2331
- catch (error) {
2332
- api.diag.debug("Call to get the resource provider failed.");
2333
- }
2334
- }
2335
- // Observable gauge callbacks
2336
- successCallback(observableResult) {
2337
- const counter = this.getNetworkStatsbeatCounter(this.endpointUrl, this.host);
2338
- const attributes = Object.assign(Object.assign({}, this.commonProperties), this.networkProperties);
2339
- observableResult.observe(counter.totalSuccesfulRequestCount, attributes);
2340
- counter.totalSuccesfulRequestCount = 0;
2341
- }
2342
- failureCallback(observableResult) {
2343
- const counter = this.getNetworkStatsbeatCounter(this.endpointUrl, this.host);
2344
- /*
2345
- Takes the failureCountGauge, value (of the counter), and attributes
2346
- create a unqiue counter based on statusCode as well
2347
- append statusCode to attributes so the newly created attributes are unique.
2348
- */
2349
- const attributes = Object.assign(Object.assign(Object.assign({}, this.networkProperties), this.commonProperties), { statusCode: 0 });
2350
- // For each { statusCode -> count } mapping, call observe, passing the count and attributes that include the statusCode
2351
- for (let i = 0; i < counter.totalFailedRequestCount.length; i++) {
2352
- attributes.statusCode = counter.totalFailedRequestCount[i].statusCode;
2353
- observableResult.observe(this.failureCountGauge, counter.totalFailedRequestCount[i].count, Object.assign({}, attributes));
2354
- counter.totalFailedRequestCount[i].count = 0;
2355
- }
2356
- }
2357
- retryCallback(observableResult) {
2358
- const counter = this.getNetworkStatsbeatCounter(this.endpointUrl, this.host);
2359
- const attributes = Object.assign(Object.assign(Object.assign({}, this.networkProperties), this.commonProperties), { statusCode: 0 });
2360
- for (let i = 0; i < counter.retryCount.length; i++) {
2361
- attributes.statusCode = counter.retryCount[i].statusCode;
2362
- observableResult.observe(this.retryCountGauge, counter.retryCount[i].count, Object.assign({}, attributes));
2363
- counter.retryCount[i].count = 0;
2364
- }
2365
- }
2366
- throttleCallback(observableResult) {
2367
- const counter = this.getNetworkStatsbeatCounter(this.endpointUrl, this.host);
2368
- const attributes = Object.assign(Object.assign(Object.assign({}, this.networkProperties), this.commonProperties), { statusCode: 0 });
2369
- for (let i = 0; i < counter.throttleCount.length; i++) {
2370
- attributes.statusCode = counter.throttleCount[i].statusCode;
2371
- observableResult.observe(this.throttleCountGauge, counter.throttleCount[i].count, Object.assign({}, attributes));
2372
- counter.throttleCount[i].count = 0;
2373
- }
2374
- }
2375
- exceptionCallback(observableResult) {
2376
- const counter = this.getNetworkStatsbeatCounter(this.endpointUrl, this.host);
2377
- const attributes = Object.assign(Object.assign(Object.assign({}, this.networkProperties), this.commonProperties), { exceptionType: "" });
2378
- for (let i = 0; i < counter.exceptionCount.length; i++) {
2379
- attributes.exceptionType = counter.exceptionCount[i].exceptionType;
2380
- observableResult.observe(this.exceptionCountGauge, counter.exceptionCount[i].count, Object.assign({}, attributes));
2381
- counter.exceptionCount[i].count = 0;
2382
- }
2383
- }
2384
- durationCallback(observableResult) {
2385
- const counter = this.getNetworkStatsbeatCounter(this.endpointUrl, this.host);
2386
- const attributes = Object.assign(Object.assign({}, this.networkProperties), this.commonProperties);
2387
- for (let i = 0; i < this.networkStatsbeatCollection.length; i++) {
2388
- const currentCounter = this.networkStatsbeatCollection[i];
2389
- currentCounter.time = Number(new Date());
2390
- const intervalRequests = currentCounter.totalRequestCount - currentCounter.lastRequestCount || 0;
2391
- currentCounter.averageRequestExecutionTime =
2392
- (currentCounter.intervalRequestExecutionTime -
2393
- currentCounter.lastIntervalRequestExecutionTime) /
2394
- intervalRequests || 0;
2395
- currentCounter.lastIntervalRequestExecutionTime = currentCounter.intervalRequestExecutionTime; // reset
2396
- currentCounter.lastRequestCount = currentCounter.totalRequestCount;
2397
- currentCounter.lastTime = currentCounter.time;
2398
- }
2399
- observableResult.observe(counter.averageRequestExecutionTime, attributes);
2400
- counter.averageRequestExecutionTime = 0;
2401
- }
2402
- readFailureCallback(observableResult) {
2403
- const counter = this.getNetworkStatsbeatCounter(this.endpointUrl, this.host);
2404
- const attributes = Object.assign(Object.assign({}, this.commonProperties), this.networkProperties);
2405
- observableResult.observe(counter.totalReadFailureCount, attributes);
2406
- counter.totalReadFailureCount = 0;
2407
- }
2408
- writeFailureCallback(observableResult) {
2409
- const counter = this.getNetworkStatsbeatCounter(this.endpointUrl, this.host);
2410
- const attributes = Object.assign(Object.assign({}, this.commonProperties), this.networkProperties);
2411
- observableResult.observe(counter.totalWriteFailureCount, attributes);
2412
- counter.totalWriteFailureCount = 0;
2413
- }
2414
- // Public methods to increase counters
2415
- countSuccess(duration) {
2416
- if (!this.isInitialized) {
2417
- return;
2418
- }
2419
- const counter = this.getNetworkStatsbeatCounter(this.endpointUrl, this.host);
2420
- counter.totalRequestCount++;
2421
- counter.totalSuccesfulRequestCount++;
2422
- counter.intervalRequestExecutionTime += duration;
2423
- }
2424
- countFailure(duration, statusCode) {
2425
- if (!this.isInitialized) {
2426
- return;
2427
- }
2428
- const counter = this.getNetworkStatsbeatCounter(this.endpointUrl, this.host);
2429
- const currentStatusCounter = counter.totalFailedRequestCount.find((statusCounter) => statusCode === statusCounter.statusCode);
2430
- if (currentStatusCounter) {
2431
- currentStatusCounter.count++;
2432
- }
2433
- else {
2434
- counter.totalFailedRequestCount.push({ statusCode: statusCode, count: 1 });
2435
- }
2436
- counter.totalRequestCount++;
2437
- counter.intervalRequestExecutionTime += duration;
2438
- }
2439
- countRetry(statusCode) {
2440
- if (!this.isInitialized) {
2441
- return;
2442
- }
2443
- const counter = this.getNetworkStatsbeatCounter(this.endpointUrl, this.host);
2444
- const currentStatusCounter = counter.retryCount.find((statusCounter) => statusCode === statusCounter.statusCode);
2445
- if (currentStatusCounter) {
2446
- currentStatusCounter.count++;
2447
- }
2448
- else {
2449
- counter.retryCount.push({ statusCode: statusCode, count: 1 });
2450
- }
2451
- }
2452
- countThrottle(statusCode) {
2453
- if (!this.isInitialized) {
2454
- return;
2455
- }
2456
- const counter = this.getNetworkStatsbeatCounter(this.endpointUrl, this.host);
2457
- const currentStatusCounter = counter.throttleCount.find((statusCounter) => statusCode === statusCounter.statusCode);
2458
- if (currentStatusCounter) {
2459
- currentStatusCounter.count++;
2460
- }
2461
- else {
2462
- counter.throttleCount.push({ statusCode: statusCode, count: 1 });
2463
- }
2464
- }
2465
- countReadFailure() {
2466
- if (!this.isInitialized || this.disableNonEssentialStatsbeat) {
2467
- return;
2468
- }
2469
- const counter = this.getNetworkStatsbeatCounter(this.endpointUrl, this.host);
2470
- counter.totalReadFailureCount++;
2471
- }
2472
- countWriteFailure() {
2473
- if (!this.isInitialized || this.disableNonEssentialStatsbeat) {
2474
- return;
2475
- }
2476
- const counter = this.getNetworkStatsbeatCounter(this.endpointUrl, this.host);
2477
- counter.totalWriteFailureCount++;
2478
- }
2479
- countException(exceptionType) {
2480
- if (!this.isInitialized) {
2481
- return;
2482
- }
2483
- const counter = this.getNetworkStatsbeatCounter(this.endpointUrl, this.host);
2484
- const currentErrorCounter = counter.exceptionCount.find((exceptionCounter) => exceptionType.name === exceptionCounter.exceptionType);
2485
- if (currentErrorCounter) {
2486
- currentErrorCounter.count++;
2487
- }
2488
- else {
2489
- counter.exceptionCount.push({ exceptionType: exceptionType.name, count: 1 });
2490
- }
2491
- }
2492
- // Gets a networkStatsbeat counter if one exists for the given endpoint
2493
- getNetworkStatsbeatCounter(endpoint, host) {
2494
- // Check if the counter is available
2495
- for (let i = 0; i < this.networkStatsbeatCollection.length; i++) {
2496
- // Same object
2497
- if (endpoint === this.networkStatsbeatCollection[i].endpoint &&
2498
- host === this.networkStatsbeatCollection[i].host) {
2499
- return this.networkStatsbeatCollection[i];
2500
- }
2501
- }
2502
- // Create a new counter if not found
2503
- const newCounter = new NetworkStatsbeat(endpoint, host);
2504
- this.networkStatsbeatCollection.push(newCounter);
2505
- return newCounter;
2506
- }
2507
- getShortHost(originalHost) {
2508
- let shortHost = originalHost;
2509
- try {
2510
- const hostRegex = new RegExp(/^https?:\/\/(?:www\.)?([^/.-]+)/);
2511
- const res = hostRegex.exec(originalHost);
2512
- if (res !== null && res.length > 1) {
2513
- shortHost = res[1];
2514
- }
2515
- shortHost = shortHost.replace(".in.applicationinsights.azure.com", "");
2516
- }
2517
- catch (error) {
2518
- api.diag.debug("Failed to get the short host name.");
2519
- }
2520
- return shortHost;
2521
- }
2522
- }
2523
-
2524
- // Copyright (c) Microsoft Corporation.
2525
- // Licensed under the MIT License.
2526
- let instance$1 = null;
2527
- /**
2528
- * Long Interval Statsbeat Metrics
2529
- * @internal
2530
- */
2531
- class LongIntervalStatsbeatMetrics extends StatsbeatMetrics {
2532
- constructor(options) {
2533
- super();
2534
- this.statsCollectionLongInterval = 86400000; // 1 day
2535
- this.attach = "Manual";
2536
- this.feature = 0;
2537
- this.instrumentation = 0;
2538
- this.isInitialized = false;
2539
- this.connectionString = super.getConnectionString(options.endpointUrl);
2540
- const exporterConfig = {
2541
- connectionString: this.connectionString,
2542
- disableOfflineStorage: options.disableOfflineStorage,
2543
- };
2544
- this.setFeatures();
2545
- this.longIntervalStatsbeatMeterProvider = new sdkMetrics.MeterProvider();
2546
- this.longIntervalAzureExporter = new AzureMonitorStatsbeatExporter(exporterConfig);
2547
- // Export Long Interval Statsbeats every day
2548
- const longIntervalMetricReaderOptions = {
2549
- exporter: this.longIntervalAzureExporter,
2550
- exportIntervalMillis: Number(process.env.LONG_INTERVAL_EXPORT_MILLIS) || this.statsCollectionLongInterval, // 1 day
2551
- };
2552
- this.longIntervalMetricReader = new sdkMetrics.PeriodicExportingMetricReader(longIntervalMetricReaderOptions);
2553
- this.longIntervalStatsbeatMeterProvider.addMetricReader(this.longIntervalMetricReader);
2554
- this.longIntervalStatsbeatMeter = this.longIntervalStatsbeatMeterProvider.getMeter("Azure Monitor Long Interval Statsbeat");
2555
- // Assign Common Properties
2556
- this.runtimeVersion = process.version;
2557
- this.language = STATSBEAT_LANGUAGE;
2558
- this.version = packageVersion;
2559
- this.cikey = options.instrumentationKey;
2560
- this.featureStatsbeatGauge = this.longIntervalStatsbeatMeter.createObservableGauge(StatsbeatCounter.FEATURE);
2561
- this.attachStatsbeatGauge = this.longIntervalStatsbeatMeter.createObservableGauge(StatsbeatCounter.ATTACH);
2562
- this.commonProperties = {
2563
- os: this.os,
2564
- rp: this.resourceProvider,
2565
- cikey: this.cikey,
2566
- runtimeVersion: this.runtimeVersion,
2567
- language: this.language,
2568
- version: this.version,
2569
- attach: this.attach,
2570
- };
2571
- this.attachProperties = {
2572
- rpId: this.resourceIdentifier,
2573
- };
2574
- this.isInitialized = true;
2575
- this.initialize();
2576
- }
2577
- async initialize() {
2578
- try {
2579
- await this.getResourceProvider();
2580
- // Add long interval observable callbacks
2581
- this.attachStatsbeatGauge.addCallback(this.attachCallback.bind(this));
2582
- this.longIntervalStatsbeatMeter.addBatchObservableCallback(this.getEnvironmentStatus.bind(this), [this.featureStatsbeatGauge]);
2583
- // Export Feature/Attach Statsbeat once upon app initialization
2584
- this.longIntervalAzureExporter.export((await this.longIntervalMetricReader.collect()).resourceMetrics, (result) => {
2585
- if (result.code !== core.ExportResultCode.SUCCESS) {
2586
- api.diag.error(`LongIntervalStatsbeat: metrics export failed (error ${result.error})`);
2587
- }
2588
- });
2589
- }
2590
- catch (error) {
2591
- api.diag.debug("Call to get the resource provider failed.");
2592
- }
2593
- }
2594
- getEnvironmentStatus(observableResult) {
2595
- this.setFeatures();
2596
- let attributes;
2597
- if (this.instrumentation) {
2598
- attributes = Object.assign(Object.assign({}, this.commonProperties), { feature: this.instrumentation, type: StatsbeatFeatureType.INSTRUMENTATION });
2599
- observableResult.observe(this.featureStatsbeatGauge, 1, Object.assign({}, attributes));
2600
- }
2601
- if (this.feature) {
2602
- attributes = Object.assign(Object.assign({}, this.commonProperties), { feature: this.feature, type: StatsbeatFeatureType.FEATURE });
2603
- observableResult.observe(this.featureStatsbeatGauge, 1, Object.assign({}, attributes));
2604
- }
2605
- }
2606
- setFeatures() {
2607
- const statsbeatFeatures = process.env.AZURE_MONITOR_STATSBEAT_FEATURES;
2608
- if (statsbeatFeatures) {
2609
- try {
2610
- this.feature = JSON.parse(statsbeatFeatures).feature;
2611
- this.instrumentation = JSON.parse(statsbeatFeatures).instrumentation;
2612
- }
2613
- catch (error) {
2614
- api.diag.error(`LongIntervalStatsbeat: Failed to parse features/instrumentations (error ${error})`);
2615
- }
2616
- }
2617
- }
2618
- attachCallback(observableResult) {
2619
- const attributes = Object.assign(Object.assign({}, this.commonProperties), this.attachProperties);
2620
- observableResult.observe(1, attributes);
2621
- }
2622
- shutdown() {
2623
- return this.longIntervalStatsbeatMeterProvider.shutdown();
2624
- }
2625
- }
2626
- /**
2627
- * Singleton LongIntervalStatsbeatMetrics instance.
2628
- * @internal
2629
- */
2630
- function getInstance$1(options) {
2631
- if (!instance$1) {
2632
- instance$1 = new LongIntervalStatsbeatMetrics(options);
2633
- }
2634
- return instance$1;
2635
- }
2636
-
2637
- // Copyright (c) Microsoft Corporation.
2638
- // Licensed under the MIT License.
2639
- /**
2640
- * Breeze retriable status codes.
2641
- * @internal
2642
- */
2643
- function isRetriable(statusCode) {
2644
- return (statusCode === 206 || // Partial Accept
2645
- statusCode === 401 || // Unauthorized
2646
- statusCode === 403 || // Forbidden
2647
- statusCode === 408 || // Timeout
2648
- statusCode === 429 || // Too many requests
2649
- statusCode === 439 || // Daily quota exceeded (legacy)
2650
- statusCode === 500 || // Server Error
2651
- statusCode === 502 || // Bad Gateway
2652
- statusCode === 503 || // Server Unavailable
2653
- statusCode === 504 // Gateway Timeout
2654
- );
2655
- }
2656
- // Convert ms to c# time span format DD.HH:MM:SS.MMMMMM
2657
- function msToTimeSpan(totalms) {
2658
- if (isNaN(totalms) || totalms < 0) {
2659
- totalms = 0;
2660
- }
2661
- let sec = ((totalms / 1000) % 60).toFixed(7).replace(/0{0,4}$/, "");
2662
- let min = "" + (Math.floor(totalms / (1000 * 60)) % 60);
2663
- let hour = "" + (Math.floor(totalms / (1000 * 60 * 60)) % 24);
2664
- const days = Math.floor(totalms / (1000 * 60 * 60 * 24));
2665
- sec = sec.indexOf(".") < 2 ? "0" + sec : sec;
2666
- min = min.length < 2 ? "0" + min : min;
2667
- hour = hour.length < 2 ? "0" + hour : hour;
2668
- const daysText = days > 0 ? days + "." : "";
2669
- return daysText + hour + ":" + min + ":" + sec;
2670
- }
2671
-
2672
- // Copyright (c) Microsoft Corporation.
2673
- // Licensed under the MIT License.
2674
- const DEFAULT_BATCH_SEND_RETRY_INTERVAL_MS = 60000;
2675
- /**
2676
- * Base sender class
2677
- * @internal
2678
- */
2679
- class BaseSender {
2680
- constructor(options) {
2681
- this.statsbeatFailureCount = 0;
2682
- this.batchSendRetryIntervalMs = DEFAULT_BATCH_SEND_RETRY_INTERVAL_MS;
2683
- this.numConsecutiveRedirects = 0;
2684
- this.disableOfflineStorage = options.exporterOptions.disableOfflineStorage || false;
2685
- this.persister = new FileSystemPersist(options.instrumentationKey, options.exporterOptions);
2686
- if (options.trackStatsbeat) {
2687
- // Initialize statsbeatMetrics
2688
- this.networkStatsbeatMetrics = new NetworkStatsbeatMetrics({
2689
- instrumentationKey: options.instrumentationKey,
2690
- endpointUrl: options.endpointUrl,
2691
- disableOfflineStorage: this.disableOfflineStorage,
2692
- });
2693
- this.longIntervalStatsbeatMetrics = getInstance$1({
2694
- instrumentationKey: options.instrumentationKey,
2695
- endpointUrl: options.endpointUrl,
2696
- disableOfflineStorage: this.disableOfflineStorage,
2697
- });
2698
- }
2699
- this.retryTimer = null;
2700
- this.isStatsbeatSender = options.isStatsbeatSender || false;
2701
- }
2702
- /**
2703
- * Export envelopes
2704
- */
2705
- async exportEnvelopes(envelopes) {
2706
- var _a, _b, _c, _d, _e, _f, _g, _h, _j;
2707
- api.diag.info(`Exporting ${envelopes.length} envelope(s)`);
2708
- if (envelopes.length < 1) {
2709
- return { code: core.ExportResultCode.SUCCESS };
2710
- }
2711
- try {
2712
- const startTime = new Date().getTime();
2713
- const { result, statusCode } = await this.send(envelopes);
2714
- const endTime = new Date().getTime();
2715
- const duration = endTime - startTime;
2716
- this.numConsecutiveRedirects = 0;
2717
- if (statusCode === 200) {
2718
- // Success -- @todo: start retry timer
2719
- if (!this.retryTimer) {
2720
- this.retryTimer = setTimeout(() => {
2721
- this.retryTimer = null;
2722
- this.sendFirstPersistedFile();
2723
- }, this.batchSendRetryIntervalMs);
2724
- this.retryTimer.unref();
2725
- }
2726
- // If we are not exportings statsbeat and statsbeat is not disabled -- count success
2727
- (_a = this.networkStatsbeatMetrics) === null || _a === void 0 ? void 0 : _a.countSuccess(duration);
2728
- return { code: core.ExportResultCode.SUCCESS };
2729
- }
2730
- else if (statusCode && isRetriable(statusCode)) {
2731
- // Failed -- persist failed data
2732
- if (statusCode === 429 || statusCode === 439) {
2733
- (_b = this.networkStatsbeatMetrics) === null || _b === void 0 ? void 0 : _b.countThrottle(statusCode);
2734
- }
2735
- if (result) {
2736
- api.diag.info(result);
2737
- const breezeResponse = JSON.parse(result);
2738
- const filteredEnvelopes = [];
2739
- if (breezeResponse.errors) {
2740
- breezeResponse.errors.forEach((error) => {
2741
- if (error.statusCode && isRetriable(error.statusCode)) {
2742
- filteredEnvelopes.push(envelopes[error.index]);
2743
- }
2744
- });
2745
- }
2746
- if (filteredEnvelopes.length > 0) {
2747
- (_c = this.networkStatsbeatMetrics) === null || _c === void 0 ? void 0 : _c.countRetry(statusCode);
2748
- // calls resultCallback(ExportResult) based on result of persister.push
2749
- return await this.persist(filteredEnvelopes);
2750
- }
2751
- // Failed -- not retriable
2752
- (_d = this.networkStatsbeatMetrics) === null || _d === void 0 ? void 0 : _d.countFailure(duration, statusCode);
2753
- return {
2754
- code: core.ExportResultCode.FAILED,
2755
- };
2756
- }
2757
- else {
2758
- // calls resultCallback(ExportResult) based on result of persister.push
2759
- (_e = this.networkStatsbeatMetrics) === null || _e === void 0 ? void 0 : _e.countRetry(statusCode);
2760
- return await this.persist(envelopes);
2761
- }
2762
- }
2763
- else {
2764
- // Failed -- not retriable
2765
- if (this.networkStatsbeatMetrics) {
2766
- if (statusCode) {
2767
- this.networkStatsbeatMetrics.countFailure(duration, statusCode);
2768
- }
2769
- }
2770
- else {
2771
- // Handles all other status codes or client exceptions for Statsbeat
2772
- this.incrementStatsbeatFailure();
2773
- }
2774
- return {
2775
- code: core.ExportResultCode.FAILED,
2776
- };
2777
- }
2778
- }
2779
- catch (error) {
2780
- const restError = error;
2781
- if (restError.statusCode &&
2782
- (restError.statusCode === 307 || // Temporary redirect
2783
- restError.statusCode === 308)) {
2784
- // Permanent redirect
2785
- this.numConsecutiveRedirects++;
2786
- // To prevent circular redirects
2787
- if (this.numConsecutiveRedirects < 10) {
2788
- if (restError.response && restError.response.headers) {
2789
- const location = restError.response.headers.get("location");
2790
- if (location) {
2791
- // Update sender URL
2792
- this.handlePermanentRedirect(location);
2793
- // Send to redirect endpoint as HTTPs library doesn't handle redirect automatically
2794
- return this.exportEnvelopes(envelopes);
2795
- }
2796
- }
2797
- }
2798
- else {
2799
- const redirectError = new Error("Circular redirect");
2800
- (_f = this.networkStatsbeatMetrics) === null || _f === void 0 ? void 0 : _f.countException(redirectError);
2801
- return { code: core.ExportResultCode.FAILED, error: redirectError };
2802
- }
2803
- }
2804
- else if (restError.statusCode &&
2805
- isRetriable(restError.statusCode) &&
2806
- !this.isStatsbeatSender) {
2807
- (_g = this.networkStatsbeatMetrics) === null || _g === void 0 ? void 0 : _g.countRetry(restError.statusCode);
2808
- return this.persist(envelopes);
2809
- }
2810
- else if (restError.statusCode === 400 &&
2811
- restError.message.includes("Invalid instrumentation key")) {
2812
- // Invalid instrumentation key, shutdown statsbeat, fail silently
2813
- this.shutdownStatsbeat();
2814
- return { code: core.ExportResultCode.SUCCESS };
2815
- }
2816
- else if (restError.statusCode &&
2817
- this.isStatsbeatSender &&
2818
- isStatsbeatShutdownStatus(restError.statusCode)) {
2819
- // If the status code is a shutdown status code for statsbeat, shutdown statsbeat and fail silently
2820
- this.incrementStatsbeatFailure();
2821
- return { code: core.ExportResultCode.SUCCESS };
2822
- }
2823
- if (this.isNetworkError(restError)) {
2824
- if (restError.statusCode) {
2825
- (_h = this.networkStatsbeatMetrics) === null || _h === void 0 ? void 0 : _h.countRetry(restError.statusCode);
2826
- }
2827
- if (!this.isStatsbeatSender) {
2828
- api.diag.error("Retrying due to transient client side error. Error message:", restError.message);
2829
- }
2830
- return this.persist(envelopes);
2831
- }
2832
- (_j = this.networkStatsbeatMetrics) === null || _j === void 0 ? void 0 : _j.countException(restError);
2833
- if (!this.isStatsbeatSender) {
2834
- api.diag.error("Envelopes could not be exported and are not retriable. Error message:", restError.message);
2835
- }
2836
- return { code: core.ExportResultCode.FAILED, error: restError };
2837
- }
2838
- }
2839
- /**
2840
- * Persist envelopes to disk
2841
- */
2842
- async persist(envelopes) {
2843
- var _a;
2844
- try {
2845
- const success = await this.persister.push(envelopes);
2846
- return success
2847
- ? { code: core.ExportResultCode.SUCCESS }
2848
- : {
2849
- code: core.ExportResultCode.FAILED,
2850
- error: new Error("Failed to persist envelope in disk."),
2851
- };
2852
- }
2853
- catch (ex) {
2854
- (_a = this.networkStatsbeatMetrics) === null || _a === void 0 ? void 0 : _a.countWriteFailure();
2855
- return { code: core.ExportResultCode.FAILED, error: ex };
2856
- }
2857
- }
2858
- /**
2859
- * Disable collection of statsbeat metrics after max failures
2860
- */
2861
- incrementStatsbeatFailure() {
2862
- this.statsbeatFailureCount++;
2863
- if (this.statsbeatFailureCount > MAX_STATSBEAT_FAILURES) {
2864
- this.shutdownStatsbeat();
2865
- }
2866
- }
2867
- /**
2868
- * Shutdown statsbeat metrics
2869
- */
2870
- shutdownStatsbeat() {
2871
- var _a, _b;
2872
- (_a = this.networkStatsbeatMetrics) === null || _a === void 0 ? void 0 : _a.shutdown();
2873
- (_b = this.longIntervalStatsbeatMetrics) === null || _b === void 0 ? void 0 : _b.shutdown();
2874
- this.networkStatsbeatMetrics = undefined;
2875
- this.statsbeatFailureCount = 0;
2876
- }
2877
- async sendFirstPersistedFile() {
2878
- var _a;
2879
- try {
2880
- const envelopes = (await this.persister.shift());
2881
- if (envelopes) {
2882
- await this.send(envelopes);
2883
- }
2884
- }
2885
- catch (err) {
2886
- (_a = this.networkStatsbeatMetrics) === null || _a === void 0 ? void 0 : _a.countReadFailure();
2887
- api.diag.warn(`Failed to fetch persisted file`, err);
2888
- }
2889
- }
2890
- isNetworkError(error) {
2891
- if (error && error.code && error.code === "REQUEST_SEND_ERROR") {
2892
- return true;
2893
- }
2894
- return false;
2895
- }
2896
- }
2897
-
2898
- // Copyright (c) Microsoft Corporation.
2899
- // Licensed under the MIT License.
2900
- const applicationInsightsResource = "https://monitor.azure.com//.default";
2901
- /**
2902
- * Exporter HTTP sender class
2903
- * @internal
2904
- */
2905
- class HttpSender extends BaseSender {
2906
- constructor(options) {
2907
- super(options);
2908
- // Build endpoint using provided configuration or default values
2909
- this.appInsightsClientOptions = Object.assign({ host: options.endpointUrl }, options.exporterOptions);
2910
- if (this.appInsightsClientOptions.credential) {
2911
- // Add credentialScopes
2912
- if (options.aadAudience) {
2913
- this.appInsightsClientOptions.credentialScopes = [options.aadAudience];
2914
- }
2915
- else {
2916
- // Default
2917
- this.appInsightsClientOptions.credentialScopes = [applicationInsightsResource];
2918
- }
2919
- }
2920
- this.appInsightsClient = new ApplicationInsightsClient(this.appInsightsClientOptions);
2921
- // Handle redirects in HTTP Sender
2922
- this.appInsightsClient.pipeline.removePolicy({ name: coreRestPipeline.redirectPolicyName });
2923
- }
2924
- /**
2925
- * Send Azure envelopes
2926
- * @internal
2927
- */
2928
- async send(envelopes) {
2929
- var _a;
2930
- const options = {};
2931
- let response;
2932
- function onResponse(rawResponse, flatResponse) {
2933
- response = rawResponse;
2934
- if (options.onResponse) {
2935
- options.onResponse(rawResponse, flatResponse);
2936
- }
2937
- }
2938
- await this.appInsightsClient.track(envelopes, Object.assign(Object.assign({}, options), { onResponse }));
2939
- return { statusCode: response === null || response === void 0 ? void 0 : response.status, result: (_a = response === null || response === void 0 ? void 0 : response.bodyAsText) !== null && _a !== void 0 ? _a : "" };
2940
- }
2941
- /**
2942
- * Shutdown sender
2943
- * @internal
2944
- */
2945
- // eslint-disable-next-line @typescript-eslint/require-await
2946
- async shutdown() {
2947
- api.diag.info("HttpSender shutting down");
2948
- }
2949
- handlePermanentRedirect(location) {
2950
- if (location) {
2951
- const locUrl = new url.URL(location);
2952
- if (locUrl && locUrl.host) {
2953
- this.appInsightsClient.host = "https://" + locUrl.host;
2954
- }
2955
- }
2956
- }
2957
- }
2958
-
2959
- // Copyright (c) Microsoft Corporation.
2960
- // Licensed under the MIT License.
2961
- let instance = null;
2962
- /**
2963
- * Azure Telemetry context.
2964
- * @internal
2965
- */
2966
- class Context {
2967
- constructor() {
2968
- this.tags = {};
2969
- this._loadDeviceContext();
2970
- this._loadInternalContext();
2971
- }
2972
- _loadDeviceContext() {
2973
- this.tags[KnownContextTagKeys.AiDeviceOsVersion] = os__namespace && `${os__namespace.type()} ${os__namespace.release()}`;
2974
- }
2975
- _loadInternalContext() {
2976
- const { node } = process.versions;
2977
- [Context.nodeVersion] = node.split(".");
2978
- Context.opentelemetryVersion = core.SDK_INFO[semanticConventions.SemanticResourceAttributes.TELEMETRY_SDK_VERSION];
2979
- Context.sdkVersion = packageVersion;
2980
- const prefix = process.env["AZURE_MONITOR_PREFIX"] ? process.env["AZURE_MONITOR_PREFIX"] : "";
2981
- const version = process.env["AZURE_MONITOR_DISTRO_VERSION"]
2982
- ? `ext${process.env["AZURE_MONITOR_DISTRO_VERSION"]}`
2983
- : `ext${Context.sdkVersion}`;
2984
- const internalSdkVersion = `${prefix}node${Context.nodeVersion}:otel${Context.opentelemetryVersion}:${version}`;
2985
- this.tags[KnownContextTagKeys.AiInternalSdkVersion] = internalSdkVersion;
2986
- }
2987
- }
2988
- Context.sdkVersion = null;
2989
- Context.opentelemetryVersion = null;
2990
- Context.nodeVersion = "";
2991
- /**
2992
- * Singleton Context instance
2993
- * @internal
2994
- */
2995
- function getInstance() {
2996
- if (!instance) {
2997
- instance = new Context();
2998
- }
2999
- return instance;
3000
- }
3001
-
3002
- // Copyright (c) Microsoft Corporation.
3003
- // Licensed under the MIT License.
3004
- function hrTimeToDate(hrTime) {
3005
- return new Date(core.hrTimeToNanoseconds(hrTime) / 1000000);
3006
- }
3007
- function createTagsFromResource(resource) {
3008
- const context = getInstance();
3009
- const tags = Object.assign({}, context.tags);
3010
- if (resource && resource.attributes) {
3011
- tags[KnownContextTagKeys.AiCloudRole] = getCloudRole(resource);
3012
- tags[KnownContextTagKeys.AiCloudRoleInstance] = getCloudRoleInstance(resource);
3013
- if (resource.attributes[semanticConventions.SEMRESATTRS_DEVICE_ID]) {
3014
- tags[KnownContextTagKeys.AiDeviceId] = String(resource.attributes[semanticConventions.SEMRESATTRS_DEVICE_ID]);
3015
- }
3016
- if (resource.attributes[semanticConventions.SEMRESATTRS_DEVICE_MODEL_NAME]) {
3017
- tags[KnownContextTagKeys.AiDeviceModel] = String(resource.attributes[semanticConventions.SEMRESATTRS_DEVICE_MODEL_NAME]);
3018
- }
3019
- if (resource.attributes[semanticConventions.SEMRESATTRS_SERVICE_VERSION]) {
3020
- tags[KnownContextTagKeys.AiApplicationVer] = String(resource.attributes[semanticConventions.SEMRESATTRS_SERVICE_VERSION]);
3021
- }
3022
- }
3023
- return tags;
3024
- }
3025
- function getCloudRole(resource) {
3026
- let cloudRole = "";
3027
- // Service attributes
3028
- const serviceName = resource.attributes[semanticConventions.SEMRESATTRS_SERVICE_NAME];
3029
- const serviceNamespace = resource.attributes[semanticConventions.SEMRESATTRS_SERVICE_NAMESPACE];
3030
- if (serviceName) {
3031
- // Custom Service name provided by customer is highest precedence
3032
- if (!String(serviceName).startsWith("unknown_service")) {
3033
- if (serviceNamespace) {
3034
- return `${serviceNamespace}.${serviceName}`;
3035
- }
3036
- else {
3037
- return String(serviceName);
3038
- }
3039
- }
3040
- else {
3041
- // Service attributes will be only used if K8S attributes are not present
3042
- if (serviceNamespace) {
3043
- cloudRole = `${serviceNamespace}.${serviceName}`;
3044
- }
3045
- else {
3046
- cloudRole = String(serviceName);
3047
- }
3048
- }
3049
- }
3050
- // Kubernetes attributes should take precedence
3051
- const kubernetesDeploymentName = resource.attributes[semanticConventions.SEMRESATTRS_K8S_DEPLOYMENT_NAME];
3052
- if (kubernetesDeploymentName) {
3053
- return String(kubernetesDeploymentName);
3054
- }
3055
- const kuberneteReplicasetName = resource.attributes[semanticConventions.SEMRESATTRS_K8S_REPLICASET_NAME];
3056
- if (kuberneteReplicasetName) {
3057
- return String(kuberneteReplicasetName);
3058
- }
3059
- const kubernetesStatefulSetName = resource.attributes[semanticConventions.SEMRESATTRS_K8S_STATEFULSET_NAME];
3060
- if (kubernetesStatefulSetName) {
3061
- return String(kubernetesStatefulSetName);
3062
- }
3063
- const kubernetesJobName = resource.attributes[semanticConventions.SEMRESATTRS_K8S_JOB_NAME];
3064
- if (kubernetesJobName) {
3065
- return String(kubernetesJobName);
3066
- }
3067
- const kubernetesCronjobName = resource.attributes[semanticConventions.SEMRESATTRS_K8S_CRONJOB_NAME];
3068
- if (kubernetesCronjobName) {
3069
- return String(kubernetesCronjobName);
3070
- }
3071
- const kubernetesDaemonsetName = resource.attributes[semanticConventions.SEMRESATTRS_K8S_DAEMONSET_NAME];
3072
- if (kubernetesDaemonsetName) {
3073
- return String(kubernetesDaemonsetName);
3074
- }
3075
- return cloudRole;
3076
- }
3077
- function getCloudRoleInstance(resource) {
3078
- // Kubernetes attributes should take precedence
3079
- const kubernetesPodName = resource.attributes[semanticConventions.SEMRESATTRS_K8S_POD_NAME];
3080
- if (kubernetesPodName) {
3081
- return String(kubernetesPodName);
3082
- }
3083
- // Service attributes
3084
- const serviceInstanceId = resource.attributes[semanticConventions.SEMRESATTRS_SERVICE_INSTANCE_ID];
3085
- if (serviceInstanceId) {
3086
- return String(serviceInstanceId);
3087
- }
3088
- // Default
3089
- return os$1 && os$1.hostname();
3090
- }
3091
- function isSqlDB(dbSystem) {
3092
- return (dbSystem === semanticConventions.DBSYSTEMVALUES_DB2 ||
3093
- dbSystem === semanticConventions.DBSYSTEMVALUES_DERBY ||
3094
- dbSystem === semanticConventions.DBSYSTEMVALUES_MARIADB ||
3095
- dbSystem === semanticConventions.DBSYSTEMVALUES_MSSQL ||
3096
- dbSystem === semanticConventions.DBSYSTEMVALUES_ORACLE ||
3097
- dbSystem === semanticConventions.DBSYSTEMVALUES_SQLITE ||
3098
- dbSystem === semanticConventions.DBSYSTEMVALUES_OTHER_SQL ||
3099
- dbSystem === semanticConventions.DBSYSTEMVALUES_HSQLDB ||
3100
- dbSystem === semanticConventions.DBSYSTEMVALUES_H2);
3101
- }
3102
- function getUrl(attributes) {
3103
- if (!attributes) {
3104
- return "";
3105
- }
3106
- const httpMethod = attributes[semanticConventions.SEMATTRS_HTTP_METHOD];
3107
- if (httpMethod) {
3108
- const httpUrl = attributes[semanticConventions.SEMATTRS_HTTP_URL];
3109
- if (httpUrl) {
3110
- return String(httpUrl);
3111
- }
3112
- else {
3113
- const httpScheme = attributes[semanticConventions.SEMATTRS_HTTP_SCHEME];
3114
- const httpTarget = attributes[semanticConventions.SEMATTRS_HTTP_TARGET];
3115
- if (httpScheme && httpTarget) {
3116
- const httpHost = attributes[semanticConventions.SEMATTRS_HTTP_HOST];
3117
- if (httpHost) {
3118
- return `${httpScheme}://${httpHost}${httpTarget}`;
3119
- }
3120
- else {
3121
- const netPeerPort = attributes[semanticConventions.SEMATTRS_NET_PEER_PORT];
3122
- if (netPeerPort) {
3123
- const netPeerName = attributes[semanticConventions.SEMATTRS_NET_PEER_NAME];
3124
- if (netPeerName) {
3125
- return `${httpScheme}://${netPeerName}:${netPeerPort}${httpTarget}`;
3126
- }
3127
- else {
3128
- const netPeerIp = attributes[semanticConventions.SEMATTRS_NET_PEER_IP];
3129
- if (netPeerIp) {
3130
- return `${httpScheme}://${netPeerIp}:${netPeerPort}${httpTarget}`;
3131
- }
3132
- }
3133
- }
3134
- }
3135
- }
3136
- }
3137
- }
3138
- return "";
3139
- }
3140
- function getDependencyTarget(attributes) {
3141
- if (!attributes) {
3142
- return "";
3143
- }
3144
- const peerService = attributes[semanticConventions.SEMATTRS_PEER_SERVICE];
3145
- const httpHost = attributes[semanticConventions.SEMATTRS_HTTP_HOST];
3146
- const httpUrl = attributes[semanticConventions.SEMATTRS_HTTP_URL];
3147
- const netPeerName = attributes[semanticConventions.SEMATTRS_NET_PEER_NAME];
3148
- const netPeerIp = attributes[semanticConventions.SEMATTRS_NET_PEER_IP];
3149
- if (peerService) {
3150
- return String(peerService);
3151
- }
3152
- else if (httpHost) {
3153
- return String(httpHost);
3154
- }
3155
- else if (httpUrl) {
3156
- return String(httpUrl);
3157
- }
3158
- else if (netPeerName) {
3159
- return String(netPeerName);
3160
- }
3161
- else if (netPeerIp) {
3162
- return String(netPeerIp);
3163
- }
3164
- return "";
3165
- }
3166
- function createResourceMetricEnvelope(resource, instrumentationKey) {
3167
- if (resource && resource.attributes) {
3168
- const tags = createTagsFromResource(resource);
3169
- const resourceAttributes = {};
3170
- for (const key of Object.keys(resource.attributes)) {
3171
- // Avoid duplication ignoring fields already mapped.
3172
- if (!(key.startsWith("_MS.") ||
3173
- key === semanticConventions.SEMRESATTRS_TELEMETRY_SDK_VERSION ||
3174
- key === semanticConventions.SEMRESATTRS_TELEMETRY_SDK_LANGUAGE ||
3175
- key === semanticConventions.SEMRESATTRS_TELEMETRY_SDK_NAME)) {
3176
- resourceAttributes[key] = resource.attributes[key];
3177
- }
3178
- }
3179
- // Only send event when resource attributes are available
3180
- if (Object.keys(resourceAttributes).length > 0) {
3181
- const baseData = {
3182
- version: 2,
3183
- metrics: [{ name: "_OTELRESOURCE_", value: 1 }],
3184
- properties: resourceAttributes,
3185
- };
3186
- const envelope = {
3187
- name: "Microsoft.ApplicationInsights.Metric",
3188
- time: new Date(),
3189
- sampleRate: 100, // Metrics are never sampled
3190
- instrumentationKey: instrumentationKey,
3191
- version: 1,
3192
- data: {
3193
- baseType: "MetricData",
3194
- baseData: baseData,
3195
- },
3196
- tags: tags,
3197
- };
3198
- return envelope;
3199
- }
3200
- }
3201
- return;
3202
- }
3203
- function serializeAttribute(value) {
3204
- if (typeof value === "object") {
3205
- if (value instanceof Error) {
3206
- try {
3207
- return JSON.stringify(value, Object.getOwnPropertyNames(value));
3208
- }
3209
- catch (err) {
3210
- // Failed to serialize, return string cast
3211
- return String(value);
3212
- }
3213
- }
3214
- else if (value instanceof Uint8Array) {
3215
- return String(value);
3216
- }
3217
- else {
3218
- try {
3219
- return JSON.stringify(value);
3220
- }
3221
- catch (err) {
3222
- // Failed to serialize, return string cast
3223
- return String(value);
3224
- }
3225
- }
3226
- }
3227
- // Return scalar and undefined values
3228
- return String(value);
3229
- }
3230
- function shouldCreateResourceMetric() {
3231
- var _a;
3232
- return !(((_a = process.env.ENV_OPENTELEMETRY_RESOURCE_METRIC_DISABLED) === null || _a === void 0 ? void 0 : _a.toLowerCase()) === "true");
3233
- }
3234
-
3235
- // Copyright (c) Microsoft Corporation.
3236
- // Licensed under the MIT License.
3237
- /**
3238
- * Azure SDK namespace.
3239
- * @internal
3240
- */
3241
- const AzNamespace = "az.namespace";
3242
- /**
3243
- * Azure SDK Eventhub.
3244
- * @internal
3245
- */
3246
- const MicrosoftEventHub = "Microsoft.EventHub";
3247
- /**
3248
- * Azure SDK message bus destination.
3249
- * @internal
3250
- */
3251
- const MessageBusDestination = "message_bus.destination";
3252
-
3253
- // Copyright (c) Microsoft Corporation.
3254
- // Licensed under the MIT License.
3255
- /**
3256
- * Average span.links[].attributes.enqueuedTime
3257
- */
3258
- const getTimeSinceEnqueued = (span) => {
3259
- let countEnqueueDiffs = 0;
3260
- let sumEnqueueDiffs = 0;
3261
- const startTimeMs = core.hrTimeToMilliseconds(span.startTime);
3262
- span.links.forEach(({ attributes }) => {
3263
- const enqueuedTime = attributes === null || attributes === void 0 ? void 0 : attributes[ENQUEUED_TIME];
3264
- if (enqueuedTime) {
3265
- countEnqueueDiffs += 1;
3266
- sumEnqueueDiffs += startTimeMs - (parseFloat(enqueuedTime.toString()) || 0);
3267
- }
3268
- });
3269
- return Math.max(sumEnqueueDiffs / (countEnqueueDiffs || 1), 0);
3270
- };
3271
- /**
3272
- * Implementation of Mapping to Azure Monitor
3273
- *
3274
- * https://gist.github.com/lmolkova/e4215c0f44a49ef824983382762e6b92#mapping-to-azure-monitor-application-insights-telemetry
3275
- * @internal
3276
- */
3277
- const parseEventHubSpan = (span, baseData) => {
3278
- const namespace = span.attributes[AzNamespace];
3279
- const peerAddress = (span.attributes[semanticConventions.SEMATTRS_NET_PEER_NAME] ||
3280
- span.attributes["peer.address"] ||
3281
- "unknown").replace(/\/$/g, ""); // remove trailing "/"
3282
- const messageBusDestination = (span.attributes[MessageBusDestination] || "unknown");
3283
- switch (span.kind) {
3284
- case api.SpanKind.CLIENT:
3285
- baseData.type = namespace;
3286
- baseData.target = `${peerAddress}/${messageBusDestination}`;
3287
- break;
3288
- case api.SpanKind.PRODUCER:
3289
- baseData.type = `Queue Message | ${namespace}`;
3290
- baseData.target = `${peerAddress}/${messageBusDestination}`;
3291
- break;
3292
- case api.SpanKind.CONSUMER:
3293
- baseData.type = `Queue Message | ${namespace}`;
3294
- baseData.source = `${peerAddress}/${messageBusDestination}`;
3295
- baseData.measurements = Object.assign(Object.assign({}, baseData.measurements), { [TIME_SINCE_ENQUEUED]: getTimeSinceEnqueued(span) });
3296
- break;
3297
- }
3298
- };
3299
-
3300
- // Copyright (c) Microsoft Corporation.
3301
- // Licensed under the MIT License.
3302
- function createTagsFromSpan(span) {
3303
- const tags = createTagsFromResource(span.resource);
3304
- tags[KnownContextTagKeys.AiOperationId] = span.spanContext().traceId;
3305
- if (span.parentSpanId) {
3306
- tags[KnownContextTagKeys.AiOperationParentId] = span.parentSpanId;
3307
- }
3308
- const endUserId = span.attributes[semanticConventions.SEMATTRS_ENDUSER_ID];
3309
- if (endUserId) {
3310
- tags[KnownContextTagKeys.AiUserId] = String(endUserId);
3311
- }
3312
- const httpUserAgent = span.attributes[semanticConventions.SEMATTRS_HTTP_USER_AGENT];
3313
- if (httpUserAgent) {
3314
- // TODO: Not exposed in Swagger, need to update def
3315
- tags["ai.user.userAgent"] = String(httpUserAgent);
3316
- }
3317
- if (span.kind === api.SpanKind.SERVER) {
3318
- const httpMethod = span.attributes[semanticConventions.SEMATTRS_HTTP_METHOD];
3319
- const httpClientIp = span.attributes[semanticConventions.SEMATTRS_HTTP_CLIENT_IP];
3320
- const netPeerIp = span.attributes[semanticConventions.SEMATTRS_NET_PEER_IP];
3321
- if (httpMethod) {
3322
- const httpRoute = span.attributes[semanticConventions.SEMATTRS_HTTP_ROUTE];
3323
- const httpUrl = span.attributes[semanticConventions.SEMATTRS_HTTP_URL];
3324
- tags[KnownContextTagKeys.AiOperationName] = span.name; // Default
3325
- if (httpRoute) {
3326
- tags[KnownContextTagKeys.AiOperationName] = `${httpMethod} ${httpRoute}`;
3327
- }
3328
- else if (httpUrl) {
3329
- try {
3330
- const url = new URL(String(httpUrl));
3331
- tags[KnownContextTagKeys.AiOperationName] = `${httpMethod} ${url.pathname}`;
3332
- }
3333
- catch (_a) {
3334
- /* no-op */
3335
- }
3336
- }
3337
- if (httpClientIp) {
3338
- tags[KnownContextTagKeys.AiLocationIp] = String(httpClientIp);
3339
- }
3340
- else if (netPeerIp) {
3341
- tags[KnownContextTagKeys.AiLocationIp] = String(netPeerIp);
3342
- }
3343
- }
3344
- else {
3345
- tags[KnownContextTagKeys.AiOperationName] = span.name;
3346
- if (netPeerIp) {
3347
- tags[KnownContextTagKeys.AiLocationIp] = String(netPeerIp);
3348
- }
3349
- }
3350
- }
3351
- // TODO: Operation Name and Location IP TBD for non server spans
3352
- return tags;
3353
- }
3354
- function createPropertiesFromSpanAttributes(attributes) {
3355
- const properties = {};
3356
- if (attributes) {
3357
- for (const key of Object.keys(attributes)) {
3358
- // Avoid duplication ignoring fields already mapped.
3359
- if (!(key.startsWith("_MS.") ||
3360
- key.startsWith("microsoft.") ||
3361
- key === semanticConventions.SEMATTRS_NET_PEER_IP ||
3362
- key === semanticConventions.SEMATTRS_NET_PEER_NAME ||
3363
- key === semanticConventions.SEMATTRS_PEER_SERVICE ||
3364
- key === semanticConventions.SEMATTRS_HTTP_METHOD ||
3365
- key === semanticConventions.SEMATTRS_HTTP_URL ||
3366
- key === semanticConventions.SEMATTRS_HTTP_STATUS_CODE ||
3367
- key === semanticConventions.SEMATTRS_HTTP_ROUTE ||
3368
- key === semanticConventions.SEMATTRS_HTTP_HOST ||
3369
- key === semanticConventions.SEMATTRS_HTTP_URL ||
3370
- key === semanticConventions.SEMATTRS_DB_SYSTEM ||
3371
- key === semanticConventions.SEMATTRS_DB_STATEMENT ||
3372
- key === semanticConventions.SEMATTRS_DB_OPERATION ||
3373
- key === semanticConventions.SEMATTRS_DB_NAME ||
3374
- key === semanticConventions.SEMATTRS_RPC_SYSTEM ||
3375
- key === semanticConventions.SEMATTRS_RPC_GRPC_STATUS_CODE ||
3376
- key === semanticConventions.SEMATTRS_EXCEPTION_TYPE ||
3377
- key === semanticConventions.SEMATTRS_EXCEPTION_MESSAGE ||
3378
- key === semanticConventions.SEMATTRS_EXCEPTION_STACKTRACE)) {
3379
- properties[key] = serializeAttribute(attributes[key]);
3380
- }
3381
- }
3382
- }
3383
- return properties;
3384
- }
3385
- function createPropertiesFromSpan(span) {
3386
- const properties = createPropertiesFromSpanAttributes(span.attributes);
3387
- const measurements = {};
3388
- const links = span.links.map((link) => ({
3389
- operation_Id: link.context.traceId,
3390
- id: link.context.spanId,
3391
- }));
3392
- if (links.length > 0) {
3393
- properties[MS_LINKS] = JSON.stringify(links);
3394
- }
3395
- return [properties, measurements];
3396
- }
3397
- function createDependencyData(span) {
3398
- var _a;
3399
- const remoteDependencyData = {
3400
- name: span.name, // Default
3401
- id: `${span.spanContext().spanId}`,
3402
- success: ((_a = span.status) === null || _a === void 0 ? void 0 : _a.code) !== api.SpanStatusCode.ERROR,
3403
- resultCode: "0",
3404
- type: "Dependency",
3405
- duration: msToTimeSpan(core.hrTimeToMilliseconds(span.duration)),
3406
- version: 2,
3407
- };
3408
- if (span.kind === api.SpanKind.PRODUCER) {
3409
- remoteDependencyData.type = DependencyTypes.QueueMessage;
3410
- }
3411
- if (span.kind === api.SpanKind.INTERNAL && span.parentSpanId) {
3412
- remoteDependencyData.type = DependencyTypes.InProc;
3413
- }
3414
- const httpMethod = span.attributes[semanticConventions.SEMATTRS_HTTP_METHOD];
3415
- const dbSystem = span.attributes[semanticConventions.SEMATTRS_DB_SYSTEM];
3416
- const rpcSystem = span.attributes[semanticConventions.SEMATTRS_RPC_SYSTEM];
3417
- // HTTP Dependency
3418
- if (httpMethod) {
3419
- const httpUrl = span.attributes[semanticConventions.SEMATTRS_HTTP_URL];
3420
- if (httpUrl) {
3421
- try {
3422
- const dependencyUrl = new URL(String(httpUrl));
3423
- remoteDependencyData.name = `${httpMethod} ${dependencyUrl.pathname}`;
3424
- }
3425
- catch (_b) {
3426
- /* no-op */
3427
- }
3428
- }
3429
- remoteDependencyData.type = DependencyTypes.Http;
3430
- remoteDependencyData.data = getUrl(span.attributes);
3431
- const httpStatusCode = span.attributes[semanticConventions.SEMATTRS_HTTP_STATUS_CODE];
3432
- if (httpStatusCode) {
3433
- remoteDependencyData.resultCode = String(httpStatusCode);
3434
- }
3435
- let target = getDependencyTarget(span.attributes);
3436
- if (target) {
3437
- try {
3438
- // Remove default port
3439
- const portRegex = new RegExp(/(https?)(:\/\/.*)(:\d+)(\S*)/);
3440
- const res = portRegex.exec(target);
3441
- if (res !== null) {
3442
- const protocol = res[1];
3443
- const port = res[3];
3444
- if ((protocol === "https" && port === ":443") ||
3445
- (protocol === "http" && port === ":80")) {
3446
- // Drop port
3447
- target = res[1] + res[2] + res[4];
3448
- }
3449
- }
3450
- }
3451
- catch (_c) {
3452
- /* no-op */
3453
- }
3454
- remoteDependencyData.target = `${target}`;
3455
- }
3456
- }
3457
- // DB Dependency
3458
- else if (dbSystem) {
3459
- // TODO: Remove special logic when Azure UX supports OpenTelemetry dbSystem
3460
- if (String(dbSystem) === semanticConventions.DBSYSTEMVALUES_MYSQL) {
3461
- remoteDependencyData.type = "mysql";
3462
- }
3463
- else if (String(dbSystem) === semanticConventions.DBSYSTEMVALUES_POSTGRESQL) {
3464
- remoteDependencyData.type = "postgresql";
3465
- }
3466
- else if (String(dbSystem) === semanticConventions.DBSYSTEMVALUES_MONGODB) {
3467
- remoteDependencyData.type = "mongodb";
3468
- }
3469
- else if (String(dbSystem) === semanticConventions.DBSYSTEMVALUES_REDIS) {
3470
- remoteDependencyData.type = "redis";
3471
- }
3472
- else if (isSqlDB(String(dbSystem))) {
3473
- remoteDependencyData.type = "SQL";
3474
- }
3475
- else {
3476
- remoteDependencyData.type = String(dbSystem);
3477
- }
3478
- const dbStatement = span.attributes[semanticConventions.SEMATTRS_DB_STATEMENT];
3479
- const dbOperation = span.attributes[semanticConventions.SEMATTRS_DB_OPERATION];
3480
- if (dbStatement) {
3481
- remoteDependencyData.data = String(dbStatement);
3482
- }
3483
- else if (dbOperation) {
3484
- remoteDependencyData.data = String(dbOperation);
3485
- }
3486
- const target = getDependencyTarget(span.attributes);
3487
- const dbName = span.attributes[semanticConventions.SEMATTRS_DB_NAME];
3488
- if (target) {
3489
- remoteDependencyData.target = dbName ? `${target}|${dbName}` : `${target}`;
3490
- }
3491
- else {
3492
- remoteDependencyData.target = dbName ? `${dbName}` : `${dbSystem}`;
3493
- }
3494
- }
3495
- // grpc Dependency
3496
- else if (rpcSystem) {
3497
- if (rpcSystem === DependencyTypes.Wcf) {
3498
- remoteDependencyData.type = DependencyTypes.Wcf;
3499
- }
3500
- else {
3501
- remoteDependencyData.type = DependencyTypes.Grpc;
3502
- }
3503
- const grpcStatusCode = span.attributes[semanticConventions.SEMATTRS_RPC_GRPC_STATUS_CODE];
3504
- if (grpcStatusCode) {
3505
- remoteDependencyData.resultCode = String(grpcStatusCode);
3506
- }
3507
- const target = getDependencyTarget(span.attributes);
3508
- if (target) {
3509
- remoteDependencyData.target = `${target}`;
3510
- }
3511
- else if (rpcSystem) {
3512
- remoteDependencyData.target = String(rpcSystem);
3513
- }
3514
- }
3515
- return remoteDependencyData;
3516
- }
3517
- function createRequestData(span) {
3518
- const requestData = {
3519
- id: `${span.spanContext().spanId}`,
3520
- success: span.status.code !== api.SpanStatusCode.ERROR &&
3521
- (Number(span.attributes[semanticConventions.SEMATTRS_HTTP_STATUS_CODE]) || 0) < 400,
3522
- responseCode: "0",
3523
- duration: msToTimeSpan(core.hrTimeToMilliseconds(span.duration)),
3524
- version: 2,
3525
- source: undefined,
3526
- };
3527
- const httpMethod = span.attributes[semanticConventions.SEMATTRS_HTTP_METHOD];
3528
- const grpcStatusCode = span.attributes[semanticConventions.SEMATTRS_RPC_GRPC_STATUS_CODE];
3529
- if (httpMethod) {
3530
- requestData.url = getUrl(span.attributes);
3531
- const httpStatusCode = span.attributes[semanticConventions.SEMATTRS_HTTP_STATUS_CODE];
3532
- if (httpStatusCode) {
3533
- requestData.responseCode = String(httpStatusCode);
3534
- }
3535
- }
3536
- else if (grpcStatusCode) {
3537
- requestData.responseCode = String(grpcStatusCode);
3538
- }
3539
- return requestData;
3540
- }
3541
- /**
3542
- * Span to Azure envelope parsing.
3543
- * @internal
3544
- */
3545
- function readableSpanToEnvelope(span, ikey) {
3546
- let name;
3547
- let baseType;
3548
- let baseData;
3549
- const time = hrTimeToDate(span.startTime);
3550
- const instrumentationKey = ikey;
3551
- const tags = createTagsFromSpan(span);
3552
- const [properties, measurements] = createPropertiesFromSpan(span);
3553
- switch (span.kind) {
3554
- case api.SpanKind.CLIENT:
3555
- case api.SpanKind.PRODUCER:
3556
- case api.SpanKind.INTERNAL:
3557
- name = "Microsoft.ApplicationInsights.RemoteDependency";
3558
- baseType = "RemoteDependencyData";
3559
- baseData = createDependencyData(span);
3560
- break;
3561
- case api.SpanKind.SERVER:
3562
- case api.SpanKind.CONSUMER:
3563
- name = "Microsoft.ApplicationInsights.Request";
3564
- baseType = "RequestData";
3565
- baseData = createRequestData(span);
3566
- baseData.name = tags[KnownContextTagKeys.AiOperationName];
3567
- break;
3568
- default:
3569
- // never
3570
- api.diag.error(`Unsupported span kind ${span.kind}`);
3571
- throw new Error(`Unsupported span kind ${span.kind}`);
3572
- }
3573
- let sampleRate = 100;
3574
- if (span.attributes[AzureMonitorSampleRate]) {
3575
- sampleRate = Number(span.attributes[AzureMonitorSampleRate]);
3576
- }
3577
- // Azure SDK
3578
- if (span.attributes[AzNamespace]) {
3579
- if (span.kind === api.SpanKind.INTERNAL) {
3580
- baseData.type = `${DependencyTypes.InProc} | ${span.attributes[AzNamespace]}`;
3581
- }
3582
- if (span.attributes[AzNamespace] === MicrosoftEventHub) {
3583
- parseEventHubSpan(span, baseData);
3584
- }
3585
- }
3586
- // Truncate properties
3587
- if (baseData.id) {
3588
- baseData.id = baseData.id.substring(0, MaxPropertyLengths.NINE_BIT);
3589
- }
3590
- if (baseData.name) {
3591
- baseData.name = baseData.name.substring(0, MaxPropertyLengths.TEN_BIT);
3592
- }
3593
- if (baseData.resultCode) {
3594
- baseData.resultCode = String(baseData.resultCode).substring(0, MaxPropertyLengths.TEN_BIT);
3595
- }
3596
- if (baseData.data) {
3597
- baseData.data = String(baseData.data).substring(0, MaxPropertyLengths.THIRTEEN_BIT);
3598
- }
3599
- if (baseData.type) {
3600
- baseData.type = String(baseData.type).substring(0, MaxPropertyLengths.TEN_BIT);
3601
- }
3602
- if (baseData.target) {
3603
- baseData.target = String(baseData.target).substring(0, MaxPropertyLengths.TEN_BIT);
3604
- }
3605
- if (baseData.properties) {
3606
- for (const key of Object.keys(baseData.properties)) {
3607
- baseData.properties[key] = baseData.properties[key].substring(0, MaxPropertyLengths.THIRTEEN_BIT);
3608
- }
3609
- }
3610
- return {
3611
- name,
3612
- sampleRate,
3613
- time,
3614
- instrumentationKey,
3615
- tags,
3616
- version: 1,
3617
- data: {
3618
- baseType,
3619
- baseData: Object.assign(Object.assign({}, baseData), { properties,
3620
- measurements }),
3621
- },
3622
- };
3623
- }
3624
- /**
3625
- * Span Events to Azure envelopes parsing.
3626
- * @internal
3627
- */
3628
- function spanEventsToEnvelopes(span, ikey) {
3629
- const envelopes = [];
3630
- if (span.events) {
3631
- span.events.forEach((event) => {
3632
- var _a;
3633
- let baseType;
3634
- const time = hrTimeToDate(event.time);
3635
- let name = "";
3636
- let baseData;
3637
- const properties = createPropertiesFromSpanAttributes(event.attributes);
3638
- const tags = createTagsFromResource(span.resource);
3639
- tags[KnownContextTagKeys.AiOperationId] = span.spanContext().traceId;
3640
- const spanId = (_a = span.spanContext()) === null || _a === void 0 ? void 0 : _a.spanId;
3641
- if (spanId) {
3642
- tags[KnownContextTagKeys.AiOperationParentId] = spanId;
3643
- }
3644
- // Only generate exception telemetry for incoming requests
3645
- if (event.name === "exception") {
3646
- let isValidParent = false;
3647
- const parentSpanContext = span.parentSpanId
3648
- ? span.spanContext()
3649
- : undefined;
3650
- if (parentSpanContext) {
3651
- isValidParent =
3652
- api.isValidTraceId(parentSpanContext.traceId) && api.isValidSpanId(parentSpanContext.spanId);
3653
- }
3654
- /*
3655
- * Only generate exception telemetry for children of a remote span,
3656
- * internal spans, and top level spans. This is to avoid unresolvable exceptions from outgoing calls.
3657
- */
3658
- if (!isValidParent || (parentSpanContext === null || parentSpanContext === void 0 ? void 0 : parentSpanContext.isRemote) || span.kind === api.SpanKind.INTERNAL) {
3659
- name = "Microsoft.ApplicationInsights.Exception";
3660
- baseType = "ExceptionData";
3661
- let typeName = "";
3662
- let message = "Exception";
3663
- let stack = "";
3664
- let hasFullStack = false;
3665
- if (event.attributes) {
3666
- typeName = String(event.attributes[semanticConventions.SEMATTRS_EXCEPTION_TYPE]);
3667
- stack = String(event.attributes[semanticConventions.SEMATTRS_EXCEPTION_STACKTRACE]);
3668
- if (stack) {
3669
- hasFullStack = true;
3670
- }
3671
- const exceptionMsg = event.attributes[semanticConventions.SEMATTRS_EXCEPTION_MESSAGE];
3672
- if (exceptionMsg) {
3673
- message = String(exceptionMsg);
3674
- }
3675
- const escaped = event.attributes[semanticConventions.SEMATTRS_EXCEPTION_ESCAPED];
3676
- if (escaped !== undefined) {
3677
- properties[semanticConventions.SEMATTRS_EXCEPTION_ESCAPED] = String(escaped);
3678
- }
3679
- }
3680
- const exceptionDetails = {
3681
- typeName: typeName,
3682
- message: message,
3683
- stack: stack,
3684
- hasFullStack: hasFullStack,
3685
- };
3686
- const exceptionData = {
3687
- exceptions: [exceptionDetails],
3688
- version: 2,
3689
- properties: properties,
3690
- };
3691
- baseData = exceptionData;
3692
- }
3693
- else {
3694
- // Drop non-server exception span events
3695
- return;
3696
- }
3697
- }
3698
- else {
3699
- name = "Microsoft.ApplicationInsights.Message";
3700
- baseType = "MessageData";
3701
- const messageData = {
3702
- message: event.name,
3703
- version: 2,
3704
- properties: properties,
3705
- };
3706
- baseData = messageData;
3707
- }
3708
- let sampleRate = 100;
3709
- if (span.attributes[AzureMonitorSampleRate]) {
3710
- sampleRate = Number(span.attributes[AzureMonitorSampleRate]);
3711
- }
3712
- // Truncate properties
3713
- if (baseData.message) {
3714
- baseData.message = String(baseData.message).substring(0, MaxPropertyLengths.FIFTEEN_BIT);
3715
- }
3716
- if (baseData.properties) {
3717
- for (const key of Object.keys(baseData.properties)) {
3718
- baseData.properties[key] = baseData.properties[key].substring(0, MaxPropertyLengths.THIRTEEN_BIT);
3719
- }
3720
- }
3721
- const env = {
3722
- name: name,
3723
- time: time,
3724
- instrumentationKey: ikey,
3725
- version: 1,
3726
- sampleRate: sampleRate,
3727
- data: {
3728
- baseType: baseType,
3729
- baseData: baseData,
3730
- },
3731
- tags: tags,
3732
- };
3733
- envelopes.push(env);
3734
- });
3735
- }
3736
- return envelopes;
3737
- }
3738
-
3739
- // Copyright (c) Microsoft Corporation.
3740
- // Licensed under the MIT License.
3741
- /**
3742
- * Azure Monitor OpenTelemetry Trace Exporter.
3743
- */
3744
- class AzureMonitorTraceExporter extends AzureMonitorBaseExporter {
3745
- /**
3746
- * Initializes a new instance of the AzureMonitorTraceExporter class.
3747
- * @param AzureExporterConfig - Exporter configuration.
3748
- */
3749
- constructor(options = {}) {
3750
- super(options);
3751
- /**
3752
- * Flag to determine if Exporter is shutdown.
3753
- */
3754
- this.isShutdown = false;
3755
- this.shouldCreateResourceMetric = shouldCreateResourceMetric();
3756
- this.sender = new HttpSender({
3757
- endpointUrl: this.endpointUrl,
3758
- instrumentationKey: this.instrumentationKey,
3759
- trackStatsbeat: this.trackStatsbeat,
3760
- exporterOptions: options,
3761
- aadAudience: this.aadAudience,
3762
- });
3763
- api.diag.debug("AzureMonitorTraceExporter was successfully setup");
3764
- }
3765
- /**
3766
- * Export OpenTelemetry spans.
3767
- * @param spans - Spans to export.
3768
- * @param resultCallback - Result callback.
3769
- */
3770
- // eslint-disable-next-line @typescript-eslint/no-misused-promises
3771
- async export(spans, resultCallback) {
3772
- if (this.isShutdown) {
3773
- api.diag.info("Exporter shut down. Failed to export spans.");
3774
- setTimeout(() => resultCallback({ code: core.ExportResultCode.FAILED }), 0);
3775
- return;
3776
- }
3777
- api.diag.info(`Exporting ${spans.length} span(s). Converting to envelopes...`);
3778
- if (spans.length > 0) {
3779
- const envelopes = [];
3780
- const resourceMetricEnvelope = createResourceMetricEnvelope(spans[0].resource, this.instrumentationKey);
3781
- if (resourceMetricEnvelope && this.shouldCreateResourceMetric) {
3782
- envelopes.push(resourceMetricEnvelope);
3783
- }
3784
- spans.forEach((span) => {
3785
- envelopes.push(readableSpanToEnvelope(span, this.instrumentationKey));
3786
- const spanEventEnvelopes = spanEventsToEnvelopes(span, this.instrumentationKey);
3787
- if (spanEventEnvelopes.length > 0) {
3788
- envelopes.push(...spanEventEnvelopes);
3789
- }
3790
- });
3791
- resultCallback(await this.sender.exportEnvelopes(envelopes));
3792
- }
3793
- // No data to export
3794
- resultCallback({ code: core.ExportResultCode.SUCCESS });
3795
- }
3796
- /**
3797
- * Shutdown AzureMonitorTraceExporter.
3798
- */
3799
- async shutdown() {
3800
- this.isShutdown = true;
3801
- api.diag.info("AzureMonitorTraceExporter shutting down");
3802
- return this.sender.shutdown();
3803
- }
3804
- }
3805
-
3806
- // Copyright (c) Microsoft Corporation.
3807
- // Licensed under the MIT License.
3808
- /**
3809
- * Azure Monitor OpenTelemetry Metric Exporter.
3810
- */
3811
- class AzureMonitorMetricExporter extends AzureMonitorBaseExporter {
3812
- /**
3813
- * Initializes a new instance of the AzureMonitorMetricExporter class.
3814
- * @param AzureExporterConfig - Exporter configuration.
3815
- */
3816
- constructor(options = {}) {
3817
- super(options);
3818
- /**
3819
- * Flag to determine if Exporter is shutdown.
3820
- */
3821
- this._isShutdown = false;
3822
- this._sender = new HttpSender({
3823
- endpointUrl: this.endpointUrl,
3824
- instrumentationKey: this.instrumentationKey,
3825
- trackStatsbeat: this.trackStatsbeat,
3826
- exporterOptions: options,
3827
- aadAudience: this.aadAudience,
3828
- });
3829
- api.diag.debug("AzureMonitorMetricExporter was successfully setup");
3830
- }
3831
- /**
3832
- * Export OpenTelemetry resource metrics.
3833
- * @param metrics - Resource metrics to export.
3834
- * @param resultCallback - Result callback.
3835
- */
3836
- // eslint-disable-next-line @typescript-eslint/no-misused-promises
3837
- async export(metrics, resultCallback) {
3838
- if (this._isShutdown) {
3839
- api.diag.info("Exporter shut down. Failed to export spans.");
3840
- setTimeout(() => resultCallback({ code: core.ExportResultCode.FAILED }), 0);
3841
- return;
3842
- }
3843
- api.diag.info(`Exporting ${metrics.scopeMetrics.length} metrics(s). Converting to envelopes...`);
3844
- const envelopes = resourceMetricsToEnvelope(metrics, this.instrumentationKey);
3845
- // Supress tracing until OpenTelemetry Metrics SDK support it
3846
- await api.context.with(core.suppressTracing(api.context.active()), async () => {
3847
- resultCallback(await this._sender.exportEnvelopes(envelopes));
3848
- });
3849
- }
3850
- /**
3851
- * Shutdown AzureMonitorMetricExporter.
3852
- */
3853
- async shutdown() {
3854
- this._isShutdown = true;
3855
- api.diag.info("AzureMonitorMetricExporter shutting down");
3856
- return this._sender.shutdown();
3857
- }
3858
- /**
3859
- * Select aggregation temporality
3860
- */
3861
- selectAggregationTemporality(instrumentType) {
3862
- if (instrumentType === sdkMetrics.InstrumentType.UP_DOWN_COUNTER ||
3863
- instrumentType === sdkMetrics.InstrumentType.OBSERVABLE_UP_DOWN_COUNTER) {
3864
- return sdkMetrics.AggregationTemporality.CUMULATIVE;
3865
- }
3866
- return sdkMetrics.AggregationTemporality.DELTA;
3867
- }
3868
- /**
3869
- * Force flush
3870
- */
3871
- async forceFlush() {
3872
- return Promise.resolve();
3873
- }
3874
- }
3875
-
3876
- // Copyright (c) Microsoft Corporation.
3877
- // Licensed under the MIT License.
3878
- /**
3879
- * Log to Azure envelope parsing.
3880
- * @internal
3881
- */
3882
- function logToEnvelope(log, ikey) {
3883
- const time = hrTimeToDate(log.hrTime);
3884
- const sampleRate = 100;
3885
- const instrumentationKey = ikey;
3886
- const tags = createTagsFromLog(log);
3887
- // eslint-disable-next-line prefer-const
3888
- let [properties, measurements] = createPropertiesFromLog(log);
3889
- let name;
3890
- let baseType;
3891
- let baseData;
3892
- if (!log.attributes[ApplicationInsightsBaseType]) {
3893
- // Get Exception attributes if available
3894
- const exceptionType = log.attributes[semanticConventions.SEMATTRS_EXCEPTION_TYPE];
3895
- if (exceptionType) {
3896
- const exceptionMessage = log.attributes[semanticConventions.SEMATTRS_EXCEPTION_MESSAGE];
3897
- const exceptionStacktrace = log.attributes[semanticConventions.SEMATTRS_EXCEPTION_STACKTRACE];
3898
- name = ApplicationInsightsExceptionName;
3899
- baseType = ApplicationInsightsExceptionBaseType;
3900
- const exceptionDetails = {
3901
- typeName: String(exceptionType),
3902
- message: String(exceptionMessage),
3903
- hasFullStack: exceptionStacktrace ? true : false,
3904
- stack: String(exceptionStacktrace),
3905
- };
3906
- const exceptionData = {
3907
- exceptions: [exceptionDetails],
3908
- severityLevel: String(getSeverity(log.severityNumber)),
3909
- version: 2,
3910
- };
3911
- baseData = exceptionData;
3912
- }
3913
- else {
3914
- name = ApplicationInsightsMessageName;
3915
- baseType = ApplicationInsightsMessageBaseType;
3916
- const messageData = {
3917
- message: String(log.body),
3918
- severityLevel: String(getSeverity(log.severityNumber)),
3919
- version: 2,
3920
- };
3921
- baseData = messageData;
3922
- }
3923
- }
3924
- else {
3925
- // If Legacy Application Insights Log
3926
- baseType = String(log.attributes[ApplicationInsightsBaseType]);
3927
- name = getLegacyApplicationInsightsName(log);
3928
- baseData = getLegacyApplicationInsightsBaseData(log);
3929
- measurements = getLegacyApplicationInsightsMeasurements(log);
3930
- if (!baseData) {
3931
- // Failed to parse log
3932
- return;
3933
- }
3934
- }
3935
- // Truncate properties
3936
- if (baseData.message) {
3937
- baseData.message = String(baseData.message).substring(0, MaxPropertyLengths.FIFTEEN_BIT);
3938
- }
3939
- if (properties) {
3940
- for (const key of Object.keys(properties)) {
3941
- properties[key] = String(properties[key]).substring(0, MaxPropertyLengths.THIRTEEN_BIT);
3942
- }
3943
- }
3944
- return {
3945
- name,
3946
- sampleRate,
3947
- time,
3948
- instrumentationKey,
3949
- tags,
3950
- version: 1,
3951
- data: {
3952
- baseType,
3953
- baseData: Object.assign(Object.assign({}, baseData), { properties,
3954
- measurements }),
3955
- },
3956
- };
3957
- }
3958
- function createTagsFromLog(log) {
3959
- var _a, _b;
3960
- const tags = createTagsFromResource(log.resource);
3961
- if ((_a = log.spanContext) === null || _a === void 0 ? void 0 : _a.traceId) {
3962
- tags[KnownContextTagKeys.AiOperationId] = log.spanContext.traceId;
3963
- }
3964
- if ((_b = log.spanContext) === null || _b === void 0 ? void 0 : _b.spanId) {
3965
- tags[KnownContextTagKeys.AiOperationParentId] = log.spanContext.spanId;
3966
- }
3967
- return tags;
3968
- }
3969
- function createPropertiesFromLog(log) {
3970
- const measurements = {};
3971
- const properties = {};
3972
- if (log.attributes) {
3973
- for (const key of Object.keys(log.attributes)) {
3974
- // Avoid duplication ignoring fields already mapped.
3975
- if (!(key.startsWith("_MS.") ||
3976
- key === semanticConventions.SEMATTRS_EXCEPTION_TYPE ||
3977
- key === semanticConventions.SEMATTRS_EXCEPTION_MESSAGE ||
3978
- key === semanticConventions.SEMATTRS_EXCEPTION_STACKTRACE)) {
3979
- properties[key] = serializeAttribute(log.attributes[key]);
3980
- }
3981
- }
3982
- }
3983
- return [properties, measurements];
3984
- }
3985
- // https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/logs/data-model.md#field-severitynumber
3986
- function getSeverity(severityNumber) {
3987
- if (severityNumber) {
3988
- if (severityNumber > 0 && severityNumber < 9) {
3989
- return KnownSeverityLevel.Verbose;
3990
- }
3991
- else if (severityNumber >= 9 && severityNumber < 13) {
3992
- return KnownSeverityLevel.Information;
3993
- }
3994
- else if (severityNumber >= 13 && severityNumber < 17) {
3995
- return KnownSeverityLevel.Warning;
3996
- }
3997
- else if (severityNumber >= 17 && severityNumber < 21) {
3998
- return KnownSeverityLevel.Error;
3999
- }
4000
- else if (severityNumber >= 21 && severityNumber < 25) {
4001
- return KnownSeverityLevel.Critical;
4002
- }
4003
- }
4004
- return;
4005
- }
4006
- function getLegacyApplicationInsightsName(log) {
4007
- let name = "";
4008
- switch (log.attributes[ApplicationInsightsBaseType]) {
4009
- case ApplicationInsightsAvailabilityBaseType:
4010
- name = ApplicationInsightsAvailabilityName;
4011
- break;
4012
- case ApplicationInsightsExceptionBaseType:
4013
- name = ApplicationInsightsExceptionName;
4014
- break;
4015
- case ApplicationInsightsMessageBaseType:
4016
- name = ApplicationInsightsMessageName;
4017
- break;
4018
- case ApplicationInsightsPageViewBaseType:
4019
- name = ApplicationInsightsPageViewName;
4020
- break;
4021
- case ApplicationInsightsEventBaseType:
4022
- name = ApplicationInsightsEventName;
4023
- break;
4024
- }
4025
- return name;
4026
- }
4027
- function getLegacyApplicationInsightsMeasurements(log) {
4028
- var _a;
4029
- let measurements = {};
4030
- if ((_a = log.body) === null || _a === void 0 ? void 0 : _a.measurements) {
4031
- measurements = Object.assign({}, log.body.measurements);
4032
- }
4033
- return measurements;
4034
- }
4035
- function getLegacyApplicationInsightsBaseData(log) {
4036
- let baseData = {
4037
- version: 2,
4038
- };
4039
- if (log.body) {
4040
- try {
4041
- switch (log.attributes[ApplicationInsightsBaseType]) {
4042
- case ApplicationInsightsAvailabilityBaseType:
4043
- baseData = log.body;
4044
- break;
4045
- case ApplicationInsightsExceptionBaseType:
4046
- baseData = log.body;
4047
- break;
4048
- case ApplicationInsightsMessageBaseType:
4049
- baseData = log.body;
4050
- break;
4051
- case ApplicationInsightsPageViewBaseType:
4052
- baseData = log.body;
4053
- break;
4054
- case ApplicationInsightsEventBaseType:
4055
- baseData = log.body;
4056
- break;
4057
- }
4058
- if (typeof (baseData === null || baseData === void 0 ? void 0 : baseData.message) === "object") {
4059
- baseData.message = JSON.stringify(baseData.message);
4060
- }
4061
- }
4062
- catch (err) {
4063
- api.diag.error("AzureMonitorLogExporter failed to parse Application Insights Telemetry");
4064
- }
4065
- }
4066
- return baseData;
4067
- }
4068
-
4069
- // Copyright (c) Microsoft Corporation.
4070
- // Licensed under the MIT License.
4071
- /**
4072
- * Azure Monitor OpenTelemetry Log Exporter.
4073
- */
4074
- class AzureMonitorLogExporter extends AzureMonitorBaseExporter {
4075
- /**
4076
- * Initializes a new instance of the AzureMonitorLogExporter class.
4077
- * @param AzureExporterConfig - Exporter configuration.
4078
- */
4079
- constructor(options = {}) {
4080
- super(options);
4081
- /**
4082
- * Flag to determine if Exporter is shutdown.
4083
- */
4084
- this._isShutdown = false;
4085
- this._sender = new HttpSender({
4086
- endpointUrl: this.endpointUrl,
4087
- instrumentationKey: this.instrumentationKey,
4088
- trackStatsbeat: this.trackStatsbeat,
4089
- exporterOptions: options,
4090
- aadAudience: this.aadAudience,
4091
- });
4092
- api.diag.debug("AzureMonitorLogExporter was successfully setup");
4093
- }
4094
- /**
4095
- * Export OpenTelemetry logs.
4096
- * @param logs - Logs to export.
4097
- * @param resultCallback - Result callback.
4098
- */
4099
- // eslint-disable-next-line @typescript-eslint/no-misused-promises
4100
- async export(logs, resultCallback) {
4101
- if (this._isShutdown) {
4102
- api.diag.info("Exporter shut down. Failed to export spans.");
4103
- setTimeout(() => resultCallback({ code: core.ExportResultCode.FAILED }), 0);
4104
- return;
4105
- }
4106
- api.diag.info(`Exporting ${logs.length} logs(s). Converting to envelopes...`);
4107
- const envelopes = [];
4108
- logs.forEach((log) => {
4109
- const envelope = logToEnvelope(log, this.instrumentationKey);
4110
- if (envelope) {
4111
- envelopes.push(envelope);
4112
- }
4113
- });
4114
- // Supress tracing until OpenTelemetry Logs SDK support it
4115
- await api.context.with(core.suppressTracing(api.context.active()), async () => {
4116
- resultCallback(await this._sender.exportEnvelopes(envelopes));
4117
- });
4118
- }
4119
- /**
4120
- * Shutdown AzureMonitorLogExporter.
4121
- */
4122
- async shutdown() {
4123
- this._isShutdown = true;
4124
- api.diag.info("AzureMonitorLogExporter shutting down");
4125
- return this._sender.shutdown();
4126
- }
4127
- }
4128
-
4129
- exports.ApplicationInsightsSampler = ApplicationInsightsSampler;
4130
- exports.AzureMonitorBaseExporter = AzureMonitorBaseExporter;
4131
- exports.AzureMonitorLogExporter = AzureMonitorLogExporter;
4132
- exports.AzureMonitorMetricExporter = AzureMonitorMetricExporter;
4133
- exports.AzureMonitorTraceExporter = AzureMonitorTraceExporter;
4134
- //# sourceMappingURL=index.js.map