@azure/msal-common 14.14.0 → 14.14.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (185) hide show
  1. package/dist/account/AccountInfo.d.ts +66 -66
  2. package/dist/account/AccountInfo.mjs +77 -77
  3. package/dist/account/AuthToken.d.ts +17 -17
  4. package/dist/account/AuthToken.mjs +58 -58
  5. package/dist/account/CcsCredential.d.ts +9 -9
  6. package/dist/account/CcsCredential.mjs +8 -8
  7. package/dist/account/ClientCredentials.d.ts +19 -19
  8. package/dist/account/ClientInfo.d.ts +18 -18
  9. package/dist/account/ClientInfo.mjs +37 -37
  10. package/dist/account/TokenClaims.d.ts +83 -83
  11. package/dist/account/TokenClaims.mjs +20 -20
  12. package/dist/authority/Authority.d.ts +254 -254
  13. package/dist/authority/Authority.mjs +836 -836
  14. package/dist/authority/AuthorityFactory.d.ts +18 -18
  15. package/dist/authority/AuthorityFactory.mjs +28 -28
  16. package/dist/authority/AuthorityMetadata.d.ts +43 -43
  17. package/dist/authority/AuthorityMetadata.mjs +137 -137
  18. package/dist/authority/AuthorityOptions.d.ts +27 -27
  19. package/dist/authority/AuthorityOptions.mjs +18 -18
  20. package/dist/authority/AuthorityType.d.ts +10 -10
  21. package/dist/authority/AuthorityType.mjs +13 -13
  22. package/dist/authority/AzureRegion.d.ts +1 -1
  23. package/dist/authority/AzureRegionConfiguration.d.ts +5 -5
  24. package/dist/authority/CloudDiscoveryMetadata.d.ts +5 -5
  25. package/dist/authority/CloudInstanceDiscoveryErrorResponse.d.ts +13 -13
  26. package/dist/authority/CloudInstanceDiscoveryErrorResponse.mjs +8 -8
  27. package/dist/authority/CloudInstanceDiscoveryResponse.d.ts +9 -9
  28. package/dist/authority/CloudInstanceDiscoveryResponse.mjs +8 -8
  29. package/dist/authority/ImdsOptions.d.ts +5 -5
  30. package/dist/authority/OIDCOptions.d.ts +8 -8
  31. package/dist/authority/OpenIdConfigResponse.d.ts +11 -11
  32. package/dist/authority/OpenIdConfigResponse.mjs +10 -10
  33. package/dist/authority/ProtocolMode.d.ts +8 -8
  34. package/dist/authority/ProtocolMode.mjs +11 -11
  35. package/dist/authority/RegionDiscovery.d.ts +32 -32
  36. package/dist/authority/RegionDiscovery.mjs +106 -106
  37. package/dist/authority/RegionDiscoveryMetadata.d.ts +6 -6
  38. package/dist/broker/nativeBroker/INativeBrokerPlugin.d.ts +15 -15
  39. package/dist/cache/CacheManager.d.ts +497 -497
  40. package/dist/cache/CacheManager.mjs +1249 -1249
  41. package/dist/cache/entities/AccessTokenEntity.d.ts +25 -25
  42. package/dist/cache/entities/AccountEntity.d.ts +106 -106
  43. package/dist/cache/entities/AccountEntity.mjs +240 -240
  44. package/dist/cache/entities/AppMetadataEntity.d.ts +11 -11
  45. package/dist/cache/entities/AuthorityMetadataEntity.d.ts +15 -15
  46. package/dist/cache/entities/CacheRecord.d.ts +13 -13
  47. package/dist/cache/entities/CredentialEntity.d.ts +30 -30
  48. package/dist/cache/entities/IdTokenEntity.d.ts +8 -8
  49. package/dist/cache/entities/RefreshTokenEntity.d.ts +7 -7
  50. package/dist/cache/entities/ServerTelemetryEntity.d.ts +6 -6
  51. package/dist/cache/entities/ThrottlingEntity.d.ts +7 -7
  52. package/dist/cache/interface/ICacheManager.d.ts +166 -166
  53. package/dist/cache/interface/ICachePlugin.d.ts +5 -5
  54. package/dist/cache/interface/ISerializableTokenCache.d.ts +4 -4
  55. package/dist/cache/persistence/TokenCacheContext.d.ts +23 -23
  56. package/dist/cache/persistence/TokenCacheContext.mjs +25 -25
  57. package/dist/cache/utils/CacheHelpers.d.ts +94 -94
  58. package/dist/cache/utils/CacheHelpers.mjs +324 -324
  59. package/dist/cache/utils/CacheTypes.d.ts +69 -69
  60. package/dist/client/AuthorizationCodeClient.d.ts +74 -74
  61. package/dist/client/AuthorizationCodeClient.mjs +420 -420
  62. package/dist/client/BaseClient.d.ts +51 -51
  63. package/dist/client/BaseClient.mjs +100 -100
  64. package/dist/client/RefreshTokenClient.d.ts +35 -35
  65. package/dist/client/RefreshTokenClient.mjs +211 -211
  66. package/dist/client/SilentFlowClient.d.ts +27 -27
  67. package/dist/client/SilentFlowClient.mjs +133 -133
  68. package/dist/config/AppTokenProvider.d.ts +38 -38
  69. package/dist/config/ClientConfiguration.d.ts +150 -150
  70. package/dist/config/ClientConfiguration.mjs +95 -95
  71. package/dist/constants/AADServerParamKeys.d.ts +53 -53
  72. package/dist/constants/AADServerParamKeys.mjs +57 -57
  73. package/dist/crypto/ICrypto.d.ts +68 -68
  74. package/dist/crypto/ICrypto.mjs +36 -36
  75. package/dist/crypto/IGuidGenerator.d.ts +4 -4
  76. package/dist/crypto/JoseHeader.d.ts +22 -22
  77. package/dist/crypto/JoseHeader.mjs +37 -37
  78. package/dist/crypto/PopTokenGenerator.d.ts +59 -59
  79. package/dist/crypto/PopTokenGenerator.mjs +81 -81
  80. package/dist/crypto/SignedHttpRequest.d.ts +15 -15
  81. package/dist/error/AuthError.d.ts +44 -44
  82. package/dist/error/AuthError.mjs +46 -46
  83. package/dist/error/AuthErrorCodes.d.ts +5 -5
  84. package/dist/error/AuthErrorCodes.mjs +9 -9
  85. package/dist/error/CacheError.d.ts +20 -20
  86. package/dist/error/CacheError.mjs +24 -24
  87. package/dist/error/CacheErrorCodes.d.ts +2 -2
  88. package/dist/error/CacheErrorCodes.mjs +6 -6
  89. package/dist/error/ClientAuthError.d.ts +237 -237
  90. package/dist/error/ClientAuthError.mjs +249 -249
  91. package/dist/error/ClientAuthErrorCodes.d.ts +44 -44
  92. package/dist/error/ClientAuthErrorCodes.mjs +48 -48
  93. package/dist/error/ClientConfigurationError.d.ts +128 -128
  94. package/dist/error/ClientConfigurationError.mjs +135 -135
  95. package/dist/error/ClientConfigurationErrorCodes.d.ts +22 -22
  96. package/dist/error/ClientConfigurationErrorCodes.mjs +26 -26
  97. package/dist/error/InteractionRequiredAuthError.d.ts +65 -65
  98. package/dist/error/InteractionRequiredAuthError.mjs +85 -85
  99. package/dist/error/InteractionRequiredAuthErrorCodes.d.ts +7 -7
  100. package/dist/error/InteractionRequiredAuthErrorCodes.mjs +13 -13
  101. package/dist/error/JoseHeaderError.d.ts +15 -15
  102. package/dist/error/JoseHeaderError.mjs +22 -22
  103. package/dist/error/JoseHeaderErrorCodes.d.ts +2 -2
  104. package/dist/error/JoseHeaderErrorCodes.mjs +6 -6
  105. package/dist/error/ServerError.d.ts +15 -15
  106. package/dist/error/ServerError.mjs +16 -16
  107. package/dist/index.cjs +8662 -8658
  108. package/dist/index.cjs.map +1 -1
  109. package/dist/index.d.ts +107 -107
  110. package/dist/index.mjs +1 -1
  111. package/dist/logger/Logger.d.ts +95 -95
  112. package/dist/logger/Logger.mjs +188 -188
  113. package/dist/network/INetworkModule.d.ts +29 -29
  114. package/dist/network/INetworkModule.mjs +12 -12
  115. package/dist/network/NetworkManager.d.ts +33 -33
  116. package/dist/network/NetworkManager.mjs +34 -34
  117. package/dist/network/RequestThumbprint.d.ts +18 -18
  118. package/dist/network/ThrottlingUtils.d.ts +42 -42
  119. package/dist/network/ThrottlingUtils.mjs +95 -95
  120. package/dist/packageMetadata.d.ts +2 -2
  121. package/dist/packageMetadata.mjs +4 -4
  122. package/dist/request/AuthenticationHeaderParser.d.ts +19 -19
  123. package/dist/request/AuthenticationHeaderParser.mjs +55 -55
  124. package/dist/request/BaseAuthRequest.d.ts +47 -47
  125. package/dist/request/CommonAuthorizationCodeRequest.d.ts +27 -27
  126. package/dist/request/CommonAuthorizationUrlRequest.d.ts +50 -50
  127. package/dist/request/CommonClientCredentialRequest.d.ts +17 -17
  128. package/dist/request/CommonDeviceCodeRequest.d.ts +21 -21
  129. package/dist/request/CommonEndSessionRequest.d.ts +21 -21
  130. package/dist/request/CommonOnBehalfOfRequest.d.ts +13 -13
  131. package/dist/request/CommonRefreshTokenRequest.d.ts +22 -22
  132. package/dist/request/CommonSilentFlowRequest.d.ts +27 -27
  133. package/dist/request/CommonUsernamePasswordRequest.d.ts +17 -17
  134. package/dist/request/NativeRequest.d.ts +19 -19
  135. package/dist/request/NativeSignOutRequest.d.ts +5 -5
  136. package/dist/request/RequestParameterBuilder.d.ts +217 -217
  137. package/dist/request/RequestParameterBuilder.mjs +382 -382
  138. package/dist/request/RequestValidator.d.ts +27 -27
  139. package/dist/request/RequestValidator.mjs +64 -64
  140. package/dist/request/ScopeSet.d.ts +88 -88
  141. package/dist/request/ScopeSet.mjs +197 -197
  142. package/dist/request/StoreInCache.d.ts +8 -8
  143. package/dist/response/AuthenticationResult.d.ts +41 -41
  144. package/dist/response/AuthorizationCodePayload.d.ts +13 -13
  145. package/dist/response/DeviceCodeResponse.d.ts +25 -25
  146. package/dist/response/ExternalTokenResponse.d.ts +15 -15
  147. package/dist/response/IMDSBadResponse.d.ts +4 -4
  148. package/dist/response/ResponseHandler.d.ts +69 -69
  149. package/dist/response/ResponseHandler.mjs +374 -374
  150. package/dist/response/ServerAuthorizationCodeResponse.d.ts +26 -26
  151. package/dist/response/ServerAuthorizationTokenResponse.d.ts +47 -47
  152. package/dist/telemetry/performance/IPerformanceClient.d.ts +57 -57
  153. package/dist/telemetry/performance/IPerformanceMeasurement.d.ts +5 -5
  154. package/dist/telemetry/performance/PerformanceClient.d.ts +242 -242
  155. package/dist/telemetry/performance/PerformanceClient.mjs +587 -587
  156. package/dist/telemetry/performance/PerformanceEvent.d.ts +515 -505
  157. package/dist/telemetry/performance/PerformanceEvent.d.ts.map +1 -1
  158. package/dist/telemetry/performance/PerformanceEvent.mjs +484 -480
  159. package/dist/telemetry/performance/PerformanceEvent.mjs.map +1 -1
  160. package/dist/telemetry/performance/StubPerformanceClient.d.ts +24 -24
  161. package/dist/telemetry/performance/StubPerformanceClient.mjs +76 -76
  162. package/dist/telemetry/server/ServerTelemetryManager.d.ts +78 -78
  163. package/dist/telemetry/server/ServerTelemetryManager.mjs +260 -260
  164. package/dist/telemetry/server/ServerTelemetryRequest.d.ts +8 -8
  165. package/dist/url/IUri.d.ts +12 -12
  166. package/dist/url/UrlString.d.ts +48 -48
  167. package/dist/url/UrlString.mjs +161 -161
  168. package/dist/utils/ClientAssertionUtils.d.ts +2 -2
  169. package/dist/utils/ClientAssertionUtils.mjs +16 -16
  170. package/dist/utils/Constants.d.ts +309 -309
  171. package/dist/utils/Constants.mjs +322 -322
  172. package/dist/utils/FunctionWrappers.d.ts +27 -27
  173. package/dist/utils/FunctionWrappers.mjs +94 -94
  174. package/dist/utils/MsalTypes.d.ts +6 -6
  175. package/dist/utils/ProtocolUtils.d.ts +42 -42
  176. package/dist/utils/ProtocolUtils.mjs +69 -69
  177. package/dist/utils/StringUtils.d.ts +40 -40
  178. package/dist/utils/StringUtils.mjs +95 -95
  179. package/dist/utils/TimeUtils.d.ts +25 -25
  180. package/dist/utils/TimeUtils.mjs +43 -43
  181. package/dist/utils/UrlUtils.d.ts +10 -10
  182. package/dist/utils/UrlUtils.mjs +44 -44
  183. package/package.json +1 -1
  184. package/src/packageMetadata.ts +1 -1
  185. package/src/telemetry/performance/PerformanceEvent.ts +12 -0
@@ -1,4 +1,4 @@
1
- /*! @azure/msal-common v14.14.0 2024-07-23 */
1
+ /*! @azure/msal-common v14.14.1 2024-08-13 */
2
2
  'use strict';
3
3
  import { IntFields, PerformanceEventAbbreviations, PerformanceEventStatus } from './PerformanceEvent.mjs';
4
4
  import { StubPerformanceMeasurement } from './StubPerformanceClient.mjs';
@@ -7,592 +7,592 @@ import { CacheError } from '../../error/CacheError.mjs';
7
7
  import { ServerError } from '../../error/ServerError.mjs';
8
8
  import { InteractionRequiredAuthError } from '../../error/InteractionRequiredAuthError.mjs';
9
9
 
10
- /*
11
- * Copyright (c) Microsoft Corporation. All rights reserved.
12
- * Licensed under the MIT License.
13
- */
14
- /**
15
- * Starts context by adding payload to the stack
16
- * @param event {PerformanceEvent}
17
- * @param abbreviations {Map<string, string>} event name abbreviations
18
- * @param stack {?PerformanceEventStackedContext[]} stack
19
- */
20
- function startContext(event, abbreviations, stack) {
21
- if (!stack) {
22
- return;
23
- }
24
- stack.push({
25
- name: abbreviations.get(event.name) || event.name,
26
- });
27
- }
28
- /**
29
- * Ends context by removing payload from the stack and returning parent or self, if stack is empty, payload
30
- *
31
- * @param event {PerformanceEvent}
32
- * @param abbreviations {Map<string, string>} event name abbreviations
33
- * @param stack {?PerformanceEventStackedContext[]} stack
34
- * @param error {?unknown} error
35
- */
36
- function endContext(event, abbreviations, stack, error) {
37
- if (!stack?.length) {
38
- return;
39
- }
40
- const peek = (stack) => {
41
- return stack.length ? stack[stack.length - 1] : undefined;
42
- };
43
- const abbrEventName = abbreviations.get(event.name) || event.name;
44
- const top = peek(stack);
45
- if (top?.name !== abbrEventName) {
46
- return;
47
- }
48
- const current = stack?.pop();
49
- if (!current) {
50
- return;
51
- }
52
- const errorCode = error instanceof AuthError
53
- ? error.errorCode
54
- : error instanceof Error
55
- ? error.name
56
- : undefined;
57
- const subErr = error instanceof AuthError ? error.subError : undefined;
58
- if (errorCode && current.childErr !== errorCode) {
59
- current.err = errorCode;
60
- if (subErr) {
61
- current.subErr = subErr;
62
- }
63
- }
64
- delete current.name;
65
- delete current.childErr;
66
- const context = {
67
- ...current,
68
- dur: event.durationMs,
69
- };
70
- if (!event.success) {
71
- context.fail = 1;
72
- }
73
- const parent = peek(stack);
74
- if (!parent) {
75
- return { [abbrEventName]: context };
76
- }
77
- if (errorCode) {
78
- parent.childErr = errorCode;
79
- }
80
- let childName;
81
- if (!parent[abbrEventName]) {
82
- childName = abbrEventName;
83
- }
84
- else {
85
- const siblings = Object.keys(parent).filter((key) => key.startsWith(abbrEventName)).length;
86
- childName = `${abbrEventName}_${siblings + 1}`;
87
- }
88
- parent[childName] = context;
89
- return parent;
90
- }
91
- /**
92
- * Adds error name and stack trace to the telemetry event
93
- * @param error {Error}
94
- * @param logger {Logger}
95
- * @param event {PerformanceEvent}
96
- * @param stackMaxSize {number} max error stack size to capture
97
- */
98
- function addError(error, logger, event, stackMaxSize = 5) {
99
- if (!(error instanceof Error)) {
100
- logger.trace("PerformanceClient.addErrorStack: Input error is not instance of Error", event.correlationId);
101
- return;
102
- }
103
- else if (error instanceof AuthError) {
104
- event.errorCode = error.errorCode;
105
- event.subErrorCode = error.subError;
106
- if (error instanceof ServerError ||
107
- error instanceof InteractionRequiredAuthError) {
108
- event.serverErrorNo = error.errorNo;
109
- }
110
- return;
111
- }
112
- else if (error instanceof CacheError) {
113
- event.errorCode = error.errorCode;
114
- return;
115
- }
116
- else if (event.errorStack?.length) {
117
- logger.trace("PerformanceClient.addErrorStack: Stack already exist", event.correlationId);
118
- return;
119
- }
120
- else if (!error.stack?.length) {
121
- logger.trace("PerformanceClient.addErrorStack: Input stack is empty", event.correlationId);
122
- return;
123
- }
124
- if (error.stack) {
125
- event.errorStack = compactStack(error.stack, stackMaxSize);
126
- }
127
- event.errorName = error.name;
128
- }
129
- /**
130
- * Compacts error stack into array by fetching N first entries
131
- * @param stack {string} error stack
132
- * @param stackMaxSize {number} max error stack size to capture
133
- * @returns {string[]}
134
- */
135
- function compactStack(stack, stackMaxSize) {
136
- if (stackMaxSize < 0) {
137
- return [];
138
- }
139
- const stackArr = stack.split("\n") || [];
140
- if (stackArr.length < 2) {
141
- return [];
142
- }
143
- const res = [];
144
- // Get top N stack lines
145
- for (
146
- // Skip first line as it may contain PII data
147
- let ix = Math.max(stackArr.length - stackMaxSize - 1, 1); ix < stackArr.length; ix++) {
148
- const line = stackArr[ix];
149
- if (res.length >= stackMaxSize) {
150
- break;
151
- }
152
- res.push(compactStackLine(line));
153
- }
154
- return res;
155
- }
156
- /**
157
- * Compacts error stack line by shortening file path
158
- * Example: https://localhost/msal-common/src/authority/Authority.js:100:1 -> Authority.js:100:1
159
- * @param line {string} stack line
160
- * @returns {string}
161
- */
162
- function compactStackLine(line) {
163
- const filePathIx = line.lastIndexOf(" ") + 1;
164
- if (filePathIx < 1) {
165
- return line;
166
- }
167
- const filePath = line.substring(filePathIx);
168
- let fileNameIx = filePath.lastIndexOf("/");
169
- fileNameIx = fileNameIx < 0 ? filePath.lastIndexOf("\\") : fileNameIx;
170
- if (fileNameIx >= 0) {
171
- return (line.substring(0, filePathIx) +
172
- "(" +
173
- filePath.substring(fileNameIx + 1) +
174
- (filePath.charAt(filePath.length - 1) === ")" ? "" : ")")).trimStart();
175
- }
176
- return line.trimStart();
177
- }
178
- class PerformanceClient {
179
- /**
180
- * Creates an instance of PerformanceClient,
181
- * an abstract class containing core performance telemetry logic.
182
- *
183
- * @constructor
184
- * @param {string} clientId Client ID of the application
185
- * @param {string} authority Authority used by the application
186
- * @param {Logger} logger Logger used by the application
187
- * @param {string} libraryName Name of the library
188
- * @param {string} libraryVersion Version of the library
189
- * @param {ApplicationTelemetry} applicationTelemetry application name and version
190
- * @param {Set<String>} intFields integer fields to be truncated
191
- * @param {Map<string, string>} abbreviations event name abbreviations
192
- */
193
- constructor(clientId, authority, logger, libraryName, libraryVersion, applicationTelemetry, intFields, abbreviations) {
194
- this.authority = authority;
195
- this.libraryName = libraryName;
196
- this.libraryVersion = libraryVersion;
197
- this.applicationTelemetry = applicationTelemetry;
198
- this.clientId = clientId;
199
- this.logger = logger;
200
- this.callbacks = new Map();
201
- this.eventsByCorrelationId = new Map();
202
- this.eventStack = new Map();
203
- this.queueMeasurements = new Map();
204
- this.preQueueTimeByCorrelationId = new Map();
205
- this.intFields = intFields || new Set();
206
- for (const item of IntFields) {
207
- this.intFields.add(item);
208
- }
209
- this.abbreviations = abbreviations || new Map();
210
- for (const [key, value] of PerformanceEventAbbreviations) {
211
- this.abbreviations.set(key, value);
212
- }
213
- }
214
- /**
215
- * Starts and returns an platform-specific implementation of IPerformanceMeasurement.
216
- * Note: this function can be changed to abstract at the next major version bump.
217
- *
218
- * @param {string} measureName
219
- * @param {string} correlationId
220
- * @returns {IPerformanceMeasurement}
221
- * @deprecated This method will be removed in the next major version
222
- */
223
- startPerformanceMeasurement(measureName, // eslint-disable-line @typescript-eslint/no-unused-vars
224
- correlationId // eslint-disable-line @typescript-eslint/no-unused-vars
225
- ) {
226
- return {};
227
- }
228
- /**
229
- * Gets map of pre-queue times by correlation Id
230
- *
231
- * @param {PerformanceEvents} eventName
232
- * @param {string} correlationId
233
- * @returns {number}
234
- */
235
- getPreQueueTime(eventName, correlationId) {
236
- const preQueueEvent = this.preQueueTimeByCorrelationId.get(correlationId);
237
- if (!preQueueEvent) {
238
- this.logger.trace(`PerformanceClient.getPreQueueTime: no pre-queue times found for correlationId: ${correlationId}, unable to add queue measurement`);
239
- return;
240
- }
241
- else if (preQueueEvent.name !== eventName) {
242
- this.logger.trace(`PerformanceClient.getPreQueueTime: no pre-queue time found for ${eventName}, unable to add queue measurement`);
243
- return;
244
- }
245
- return preQueueEvent.time;
246
- }
247
- /**
248
- * Calculates the difference between current time and time when function was queued.
249
- * Note: It is possible to have 0 as the queue time if the current time and the queued time was the same.
250
- *
251
- * @param {number} preQueueTime
252
- * @param {number} currentTime
253
- * @returns {number}
254
- */
255
- calculateQueuedTime(preQueueTime, currentTime) {
256
- if (preQueueTime < 1) {
257
- this.logger.trace(`PerformanceClient: preQueueTime should be a positive integer and not ${preQueueTime}`);
258
- return 0;
259
- }
260
- if (currentTime < 1) {
261
- this.logger.trace(`PerformanceClient: currentTime should be a positive integer and not ${currentTime}`);
262
- return 0;
263
- }
264
- if (currentTime < preQueueTime) {
265
- this.logger.trace("PerformanceClient: currentTime is less than preQueueTime, check how time is being retrieved");
266
- return 0;
267
- }
268
- return currentTime - preQueueTime;
269
- }
270
- /**
271
- * Adds queue measurement time to QueueMeasurements array for given correlation ID.
272
- *
273
- * @param {PerformanceEvents} eventName
274
- * @param {?string} correlationId
275
- * @param {?number} queueTime
276
- * @param {?boolean} manuallyCompleted - indicator for manually completed queue measurements
277
- * @returns
278
- */
279
- addQueueMeasurement(eventName, correlationId, queueTime, manuallyCompleted) {
280
- if (!correlationId) {
281
- this.logger.trace(`PerformanceClient.addQueueMeasurement: correlationId not provided for ${eventName}, cannot add queue measurement`);
282
- return;
283
- }
284
- if (queueTime === 0) {
285
- // Possible for there to be no queue time after calculation
286
- this.logger.trace(`PerformanceClient.addQueueMeasurement: queue time provided for ${eventName} is ${queueTime}`);
287
- }
288
- else if (!queueTime) {
289
- this.logger.trace(`PerformanceClient.addQueueMeasurement: no queue time provided for ${eventName}`);
290
- return;
291
- }
292
- const queueMeasurement = {
293
- eventName,
294
- // Always default queue time to 0 for manually completed (improperly instrumented)
295
- queueTime: manuallyCompleted ? 0 : queueTime,
296
- manuallyCompleted,
297
- };
298
- // Adds to existing correlation Id if present in queueMeasurements
299
- const existingMeasurements = this.queueMeasurements.get(correlationId);
300
- if (existingMeasurements) {
301
- existingMeasurements.push(queueMeasurement);
302
- this.queueMeasurements.set(correlationId, existingMeasurements);
303
- }
304
- else {
305
- // Sets new correlation Id if not present in queueMeasurements
306
- this.logger.trace(`PerformanceClient.addQueueMeasurement: adding correlationId ${correlationId} to queue measurements`);
307
- const measurementArray = [queueMeasurement];
308
- this.queueMeasurements.set(correlationId, measurementArray);
309
- }
310
- // Delete processed pre-queue event.
311
- this.preQueueTimeByCorrelationId.delete(correlationId);
312
- }
313
- /**
314
- * Starts measuring performance for a given operation. Returns a function that should be used to end the measurement.
315
- *
316
- * @param {PerformanceEvents} measureName
317
- * @param {?string} [correlationId]
318
- * @returns {InProgressPerformanceEvent}
319
- */
320
- startMeasurement(measureName, correlationId) {
321
- // Generate a placeholder correlation if the request does not provide one
322
- const eventCorrelationId = correlationId || this.generateId();
323
- if (!correlationId) {
324
- this.logger.info(`PerformanceClient: No correlation id provided for ${measureName}, generating`, eventCorrelationId);
325
- }
326
- this.logger.trace(`PerformanceClient: Performance measurement started for ${measureName}`, eventCorrelationId);
327
- const inProgressEvent = {
328
- eventId: this.generateId(),
329
- status: PerformanceEventStatus.InProgress,
330
- authority: this.authority,
331
- libraryName: this.libraryName,
332
- libraryVersion: this.libraryVersion,
333
- clientId: this.clientId,
334
- name: measureName,
335
- startTimeMs: Date.now(),
336
- correlationId: eventCorrelationId,
337
- appName: this.applicationTelemetry?.appName,
338
- appVersion: this.applicationTelemetry?.appVersion,
339
- };
340
- // Store in progress events so they can be discarded if not ended properly
341
- this.cacheEventByCorrelationId(inProgressEvent);
342
- startContext(inProgressEvent, this.abbreviations, this.eventStack.get(eventCorrelationId));
343
- // Return the event and functions the caller can use to properly end/flush the measurement
344
- return {
345
- end: (event, error) => {
346
- return this.endMeasurement({
347
- // Initial set of event properties
348
- ...inProgressEvent,
349
- // Properties set when event ends
350
- ...event,
351
- }, error);
352
- },
353
- discard: () => {
354
- return this.discardMeasurements(inProgressEvent.correlationId);
355
- },
356
- add: (fields) => {
357
- return this.addFields(fields, inProgressEvent.correlationId);
358
- },
359
- increment: (fields) => {
360
- return this.incrementFields(fields, inProgressEvent.correlationId);
361
- },
362
- event: inProgressEvent,
363
- measurement: new StubPerformanceMeasurement(),
364
- };
365
- }
366
- /**
367
- * Stops measuring the performance for an operation. Should only be called directly by PerformanceClient classes,
368
- * as consumers should instead use the function returned by startMeasurement.
369
- * Adds a new field named as "[event name]DurationMs" for sub-measurements, completes and emits an event
370
- * otherwise.
371
- *
372
- * @param {PerformanceEvent} event
373
- * @param {unknown} error
374
- * @returns {(PerformanceEvent | null)}
375
- */
376
- endMeasurement(event, error) {
377
- const rootEvent = this.eventsByCorrelationId.get(event.correlationId);
378
- if (!rootEvent) {
379
- this.logger.trace(`PerformanceClient: Measurement not found for ${event.eventId}`, event.correlationId);
380
- return null;
381
- }
382
- const isRoot = event.eventId === rootEvent.eventId;
383
- let queueInfo = {
384
- totalQueueTime: 0,
385
- totalQueueCount: 0,
386
- manuallyCompletedCount: 0,
387
- };
388
- event.durationMs = Math.round(event.durationMs || this.getDurationMs(event.startTimeMs));
389
- const context = JSON.stringify(endContext(event, this.abbreviations, this.eventStack.get(rootEvent.correlationId), error));
390
- if (isRoot) {
391
- queueInfo = this.getQueueInfo(event.correlationId);
392
- this.discardMeasurements(rootEvent.correlationId);
393
- }
394
- else {
395
- rootEvent.incompleteSubMeasurements?.delete(event.eventId);
396
- }
397
- this.logger.trace(`PerformanceClient: Performance measurement ended for ${event.name}: ${event.durationMs} ms`, event.correlationId);
398
- // Add sub-measurement attribute to root event.
399
- if (!isRoot) {
400
- rootEvent[event.name + "DurationMs"] = Math.floor(event.durationMs);
401
- return { ...rootEvent };
402
- }
403
- if (error) {
404
- addError(error, this.logger, rootEvent);
405
- }
406
- let finalEvent = { ...rootEvent, ...event };
407
- let incompleteSubsCount = 0;
408
- // Incomplete sub-measurements are discarded. They are likely an instrumentation bug that should be fixed.
409
- finalEvent.incompleteSubMeasurements?.forEach((subMeasurement) => {
410
- this.logger.trace(`PerformanceClient: Incomplete submeasurement ${subMeasurement.name} found for ${event.name}`, finalEvent.correlationId);
411
- incompleteSubsCount++;
412
- });
413
- finalEvent.incompleteSubMeasurements = undefined;
414
- finalEvent = {
415
- ...finalEvent,
416
- queuedTimeMs: queueInfo.totalQueueTime,
417
- queuedCount: queueInfo.totalQueueCount,
418
- queuedManuallyCompletedCount: queueInfo.manuallyCompletedCount,
419
- status: PerformanceEventStatus.Completed,
420
- incompleteSubsCount,
421
- context,
422
- };
423
- this.truncateIntegralFields(finalEvent);
424
- this.emitEvents([finalEvent], event.correlationId);
425
- return finalEvent;
426
- }
427
- /**
428
- * Saves extra information to be emitted when the measurements are flushed
429
- * @param fields
430
- * @param correlationId
431
- */
432
- addFields(fields, correlationId) {
433
- this.logger.trace("PerformanceClient: Updating static fields");
434
- const event = this.eventsByCorrelationId.get(correlationId);
435
- if (event) {
436
- this.eventsByCorrelationId.set(correlationId, {
437
- ...event,
438
- ...fields,
439
- });
440
- }
441
- else {
442
- this.logger.trace("PerformanceClient: Event not found for", correlationId);
443
- }
444
- }
445
- /**
446
- * Increment counters to be emitted when the measurements are flushed
447
- * @param fields {string[]}
448
- * @param correlationId {string} correlation identifier
449
- */
450
- incrementFields(fields, correlationId) {
451
- this.logger.trace("PerformanceClient: Updating counters");
452
- const event = this.eventsByCorrelationId.get(correlationId);
453
- if (event) {
454
- for (const counter in fields) {
455
- if (!event.hasOwnProperty(counter)) {
456
- event[counter] = 0;
457
- }
458
- else if (isNaN(Number(event[counter]))) {
459
- return;
460
- }
461
- event[counter] += fields[counter];
462
- }
463
- }
464
- else {
465
- this.logger.trace("PerformanceClient: Event not found for", correlationId);
466
- }
467
- }
468
- /**
469
- * Upserts event into event cache.
470
- * First key is the correlation id, second key is the event id.
471
- * Allows for events to be grouped by correlation id,
472
- * and to easily allow for properties on them to be updated.
473
- *
474
- * @private
475
- * @param {PerformanceEvent} event
476
- */
477
- cacheEventByCorrelationId(event) {
478
- const rootEvent = this.eventsByCorrelationId.get(event.correlationId);
479
- if (rootEvent) {
480
- this.logger.trace(`PerformanceClient: Performance measurement for ${event.name} added/updated`, event.correlationId);
481
- rootEvent.incompleteSubMeasurements =
482
- rootEvent.incompleteSubMeasurements || new Map();
483
- rootEvent.incompleteSubMeasurements.set(event.eventId, {
484
- name: event.name,
485
- startTimeMs: event.startTimeMs,
486
- });
487
- }
488
- else {
489
- this.logger.trace(`PerformanceClient: Performance measurement for ${event.name} started`, event.correlationId);
490
- this.eventsByCorrelationId.set(event.correlationId, { ...event });
491
- this.eventStack.set(event.correlationId, []);
492
- }
493
- }
494
- getQueueInfo(correlationId) {
495
- const queueMeasurementForCorrelationId = this.queueMeasurements.get(correlationId);
496
- if (!queueMeasurementForCorrelationId) {
497
- this.logger.trace(`PerformanceClient: no queue measurements found for for correlationId: ${correlationId}`);
498
- }
499
- let totalQueueTime = 0;
500
- let totalQueueCount = 0;
501
- let manuallyCompletedCount = 0;
502
- queueMeasurementForCorrelationId?.forEach((measurement) => {
503
- totalQueueTime += measurement.queueTime;
504
- totalQueueCount++;
505
- manuallyCompletedCount += measurement.manuallyCompleted ? 1 : 0;
506
- });
507
- return {
508
- totalQueueTime,
509
- totalQueueCount,
510
- manuallyCompletedCount,
511
- };
512
- }
513
- /**
514
- * Removes measurements and aux data for a given correlation id.
515
- *
516
- * @param {string} correlationId
517
- */
518
- discardMeasurements(correlationId) {
519
- this.logger.trace("PerformanceClient: Performance measurements discarded", correlationId);
520
- this.eventsByCorrelationId.delete(correlationId);
521
- this.logger.trace("PerformanceClient: QueueMeasurements discarded", correlationId);
522
- this.queueMeasurements.delete(correlationId);
523
- this.logger.trace("PerformanceClient: Pre-queue times discarded", correlationId);
524
- this.preQueueTimeByCorrelationId.delete(correlationId);
525
- this.logger.trace("PerformanceClient: Event stack discarded", correlationId);
526
- this.eventStack.delete(correlationId);
527
- }
528
- /**
529
- * Registers a callback function to receive performance events.
530
- *
531
- * @param {PerformanceCallbackFunction} callback
532
- * @returns {string}
533
- */
534
- addPerformanceCallback(callback) {
535
- for (const [id, cb] of this.callbacks) {
536
- if (cb.toString() === callback.toString()) {
537
- this.logger.warning(`PerformanceClient: Performance callback is already registered with id: ${id}`);
538
- return id;
539
- }
540
- }
541
- const callbackId = this.generateId();
542
- this.callbacks.set(callbackId, callback);
543
- this.logger.verbose(`PerformanceClient: Performance callback registered with id: ${callbackId}`);
544
- return callbackId;
545
- }
546
- /**
547
- * Removes a callback registered with addPerformanceCallback.
548
- *
549
- * @param {string} callbackId
550
- * @returns {boolean}
551
- */
552
- removePerformanceCallback(callbackId) {
553
- const result = this.callbacks.delete(callbackId);
554
- if (result) {
555
- this.logger.verbose(`PerformanceClient: Performance callback ${callbackId} removed.`);
556
- }
557
- else {
558
- this.logger.verbose(`PerformanceClient: Performance callback ${callbackId} not removed.`);
559
- }
560
- return result;
561
- }
562
- /**
563
- * Emits events to all registered callbacks.
564
- *
565
- * @param {PerformanceEvent[]} events
566
- * @param {?string} [correlationId]
567
- */
568
- emitEvents(events, correlationId) {
569
- this.logger.verbose("PerformanceClient: Emitting performance events", correlationId);
570
- this.callbacks.forEach((callback, callbackId) => {
571
- this.logger.trace(`PerformanceClient: Emitting event to callback ${callbackId}`, correlationId);
572
- callback.apply(null, [events]);
573
- });
574
- }
575
- /**
576
- * Enforce truncation of integral fields in performance event.
577
- * @param {PerformanceEvent} event performance event to update.
578
- */
579
- truncateIntegralFields(event) {
580
- this.intFields.forEach((key) => {
581
- if (key in event && typeof event[key] === "number") {
582
- event[key] = Math.floor(event[key]);
583
- }
584
- });
585
- }
586
- /**
587
- * Returns event duration in milliseconds
588
- * @param startTimeMs {number}
589
- * @returns {number}
590
- */
591
- getDurationMs(startTimeMs) {
592
- const durationMs = Date.now() - startTimeMs;
593
- // Handle clock skew
594
- return durationMs < 0 ? durationMs : 0;
595
- }
10
+ /*
11
+ * Copyright (c) Microsoft Corporation. All rights reserved.
12
+ * Licensed under the MIT License.
13
+ */
14
+ /**
15
+ * Starts context by adding payload to the stack
16
+ * @param event {PerformanceEvent}
17
+ * @param abbreviations {Map<string, string>} event name abbreviations
18
+ * @param stack {?PerformanceEventStackedContext[]} stack
19
+ */
20
+ function startContext(event, abbreviations, stack) {
21
+ if (!stack) {
22
+ return;
23
+ }
24
+ stack.push({
25
+ name: abbreviations.get(event.name) || event.name,
26
+ });
27
+ }
28
+ /**
29
+ * Ends context by removing payload from the stack and returning parent or self, if stack is empty, payload
30
+ *
31
+ * @param event {PerformanceEvent}
32
+ * @param abbreviations {Map<string, string>} event name abbreviations
33
+ * @param stack {?PerformanceEventStackedContext[]} stack
34
+ * @param error {?unknown} error
35
+ */
36
+ function endContext(event, abbreviations, stack, error) {
37
+ if (!stack?.length) {
38
+ return;
39
+ }
40
+ const peek = (stack) => {
41
+ return stack.length ? stack[stack.length - 1] : undefined;
42
+ };
43
+ const abbrEventName = abbreviations.get(event.name) || event.name;
44
+ const top = peek(stack);
45
+ if (top?.name !== abbrEventName) {
46
+ return;
47
+ }
48
+ const current = stack?.pop();
49
+ if (!current) {
50
+ return;
51
+ }
52
+ const errorCode = error instanceof AuthError
53
+ ? error.errorCode
54
+ : error instanceof Error
55
+ ? error.name
56
+ : undefined;
57
+ const subErr = error instanceof AuthError ? error.subError : undefined;
58
+ if (errorCode && current.childErr !== errorCode) {
59
+ current.err = errorCode;
60
+ if (subErr) {
61
+ current.subErr = subErr;
62
+ }
63
+ }
64
+ delete current.name;
65
+ delete current.childErr;
66
+ const context = {
67
+ ...current,
68
+ dur: event.durationMs,
69
+ };
70
+ if (!event.success) {
71
+ context.fail = 1;
72
+ }
73
+ const parent = peek(stack);
74
+ if (!parent) {
75
+ return { [abbrEventName]: context };
76
+ }
77
+ if (errorCode) {
78
+ parent.childErr = errorCode;
79
+ }
80
+ let childName;
81
+ if (!parent[abbrEventName]) {
82
+ childName = abbrEventName;
83
+ }
84
+ else {
85
+ const siblings = Object.keys(parent).filter((key) => key.startsWith(abbrEventName)).length;
86
+ childName = `${abbrEventName}_${siblings + 1}`;
87
+ }
88
+ parent[childName] = context;
89
+ return parent;
90
+ }
91
+ /**
92
+ * Adds error name and stack trace to the telemetry event
93
+ * @param error {Error}
94
+ * @param logger {Logger}
95
+ * @param event {PerformanceEvent}
96
+ * @param stackMaxSize {number} max error stack size to capture
97
+ */
98
+ function addError(error, logger, event, stackMaxSize = 5) {
99
+ if (!(error instanceof Error)) {
100
+ logger.trace("PerformanceClient.addErrorStack: Input error is not instance of Error", event.correlationId);
101
+ return;
102
+ }
103
+ else if (error instanceof AuthError) {
104
+ event.errorCode = error.errorCode;
105
+ event.subErrorCode = error.subError;
106
+ if (error instanceof ServerError ||
107
+ error instanceof InteractionRequiredAuthError) {
108
+ event.serverErrorNo = error.errorNo;
109
+ }
110
+ return;
111
+ }
112
+ else if (error instanceof CacheError) {
113
+ event.errorCode = error.errorCode;
114
+ return;
115
+ }
116
+ else if (event.errorStack?.length) {
117
+ logger.trace("PerformanceClient.addErrorStack: Stack already exist", event.correlationId);
118
+ return;
119
+ }
120
+ else if (!error.stack?.length) {
121
+ logger.trace("PerformanceClient.addErrorStack: Input stack is empty", event.correlationId);
122
+ return;
123
+ }
124
+ if (error.stack) {
125
+ event.errorStack = compactStack(error.stack, stackMaxSize);
126
+ }
127
+ event.errorName = error.name;
128
+ }
129
+ /**
130
+ * Compacts error stack into array by fetching N first entries
131
+ * @param stack {string} error stack
132
+ * @param stackMaxSize {number} max error stack size to capture
133
+ * @returns {string[]}
134
+ */
135
+ function compactStack(stack, stackMaxSize) {
136
+ if (stackMaxSize < 0) {
137
+ return [];
138
+ }
139
+ const stackArr = stack.split("\n") || [];
140
+ if (stackArr.length < 2) {
141
+ return [];
142
+ }
143
+ const res = [];
144
+ // Get top N stack lines
145
+ for (
146
+ // Skip first line as it may contain PII data
147
+ let ix = Math.max(stackArr.length - stackMaxSize - 1, 1); ix < stackArr.length; ix++) {
148
+ const line = stackArr[ix];
149
+ if (res.length >= stackMaxSize) {
150
+ break;
151
+ }
152
+ res.push(compactStackLine(line));
153
+ }
154
+ return res;
155
+ }
156
+ /**
157
+ * Compacts error stack line by shortening file path
158
+ * Example: https://localhost/msal-common/src/authority/Authority.js:100:1 -> Authority.js:100:1
159
+ * @param line {string} stack line
160
+ * @returns {string}
161
+ */
162
+ function compactStackLine(line) {
163
+ const filePathIx = line.lastIndexOf(" ") + 1;
164
+ if (filePathIx < 1) {
165
+ return line;
166
+ }
167
+ const filePath = line.substring(filePathIx);
168
+ let fileNameIx = filePath.lastIndexOf("/");
169
+ fileNameIx = fileNameIx < 0 ? filePath.lastIndexOf("\\") : fileNameIx;
170
+ if (fileNameIx >= 0) {
171
+ return (line.substring(0, filePathIx) +
172
+ "(" +
173
+ filePath.substring(fileNameIx + 1) +
174
+ (filePath.charAt(filePath.length - 1) === ")" ? "" : ")")).trimStart();
175
+ }
176
+ return line.trimStart();
177
+ }
178
+ class PerformanceClient {
179
+ /**
180
+ * Creates an instance of PerformanceClient,
181
+ * an abstract class containing core performance telemetry logic.
182
+ *
183
+ * @constructor
184
+ * @param {string} clientId Client ID of the application
185
+ * @param {string} authority Authority used by the application
186
+ * @param {Logger} logger Logger used by the application
187
+ * @param {string} libraryName Name of the library
188
+ * @param {string} libraryVersion Version of the library
189
+ * @param {ApplicationTelemetry} applicationTelemetry application name and version
190
+ * @param {Set<String>} intFields integer fields to be truncated
191
+ * @param {Map<string, string>} abbreviations event name abbreviations
192
+ */
193
+ constructor(clientId, authority, logger, libraryName, libraryVersion, applicationTelemetry, intFields, abbreviations) {
194
+ this.authority = authority;
195
+ this.libraryName = libraryName;
196
+ this.libraryVersion = libraryVersion;
197
+ this.applicationTelemetry = applicationTelemetry;
198
+ this.clientId = clientId;
199
+ this.logger = logger;
200
+ this.callbacks = new Map();
201
+ this.eventsByCorrelationId = new Map();
202
+ this.eventStack = new Map();
203
+ this.queueMeasurements = new Map();
204
+ this.preQueueTimeByCorrelationId = new Map();
205
+ this.intFields = intFields || new Set();
206
+ for (const item of IntFields) {
207
+ this.intFields.add(item);
208
+ }
209
+ this.abbreviations = abbreviations || new Map();
210
+ for (const [key, value] of PerformanceEventAbbreviations) {
211
+ this.abbreviations.set(key, value);
212
+ }
213
+ }
214
+ /**
215
+ * Starts and returns an platform-specific implementation of IPerformanceMeasurement.
216
+ * Note: this function can be changed to abstract at the next major version bump.
217
+ *
218
+ * @param {string} measureName
219
+ * @param {string} correlationId
220
+ * @returns {IPerformanceMeasurement}
221
+ * @deprecated This method will be removed in the next major version
222
+ */
223
+ startPerformanceMeasurement(measureName, // eslint-disable-line @typescript-eslint/no-unused-vars
224
+ correlationId // eslint-disable-line @typescript-eslint/no-unused-vars
225
+ ) {
226
+ return {};
227
+ }
228
+ /**
229
+ * Gets map of pre-queue times by correlation Id
230
+ *
231
+ * @param {PerformanceEvents} eventName
232
+ * @param {string} correlationId
233
+ * @returns {number}
234
+ */
235
+ getPreQueueTime(eventName, correlationId) {
236
+ const preQueueEvent = this.preQueueTimeByCorrelationId.get(correlationId);
237
+ if (!preQueueEvent) {
238
+ this.logger.trace(`PerformanceClient.getPreQueueTime: no pre-queue times found for correlationId: ${correlationId}, unable to add queue measurement`);
239
+ return;
240
+ }
241
+ else if (preQueueEvent.name !== eventName) {
242
+ this.logger.trace(`PerformanceClient.getPreQueueTime: no pre-queue time found for ${eventName}, unable to add queue measurement`);
243
+ return;
244
+ }
245
+ return preQueueEvent.time;
246
+ }
247
+ /**
248
+ * Calculates the difference between current time and time when function was queued.
249
+ * Note: It is possible to have 0 as the queue time if the current time and the queued time was the same.
250
+ *
251
+ * @param {number} preQueueTime
252
+ * @param {number} currentTime
253
+ * @returns {number}
254
+ */
255
+ calculateQueuedTime(preQueueTime, currentTime) {
256
+ if (preQueueTime < 1) {
257
+ this.logger.trace(`PerformanceClient: preQueueTime should be a positive integer and not ${preQueueTime}`);
258
+ return 0;
259
+ }
260
+ if (currentTime < 1) {
261
+ this.logger.trace(`PerformanceClient: currentTime should be a positive integer and not ${currentTime}`);
262
+ return 0;
263
+ }
264
+ if (currentTime < preQueueTime) {
265
+ this.logger.trace("PerformanceClient: currentTime is less than preQueueTime, check how time is being retrieved");
266
+ return 0;
267
+ }
268
+ return currentTime - preQueueTime;
269
+ }
270
+ /**
271
+ * Adds queue measurement time to QueueMeasurements array for given correlation ID.
272
+ *
273
+ * @param {PerformanceEvents} eventName
274
+ * @param {?string} correlationId
275
+ * @param {?number} queueTime
276
+ * @param {?boolean} manuallyCompleted - indicator for manually completed queue measurements
277
+ * @returns
278
+ */
279
+ addQueueMeasurement(eventName, correlationId, queueTime, manuallyCompleted) {
280
+ if (!correlationId) {
281
+ this.logger.trace(`PerformanceClient.addQueueMeasurement: correlationId not provided for ${eventName}, cannot add queue measurement`);
282
+ return;
283
+ }
284
+ if (queueTime === 0) {
285
+ // Possible for there to be no queue time after calculation
286
+ this.logger.trace(`PerformanceClient.addQueueMeasurement: queue time provided for ${eventName} is ${queueTime}`);
287
+ }
288
+ else if (!queueTime) {
289
+ this.logger.trace(`PerformanceClient.addQueueMeasurement: no queue time provided for ${eventName}`);
290
+ return;
291
+ }
292
+ const queueMeasurement = {
293
+ eventName,
294
+ // Always default queue time to 0 for manually completed (improperly instrumented)
295
+ queueTime: manuallyCompleted ? 0 : queueTime,
296
+ manuallyCompleted,
297
+ };
298
+ // Adds to existing correlation Id if present in queueMeasurements
299
+ const existingMeasurements = this.queueMeasurements.get(correlationId);
300
+ if (existingMeasurements) {
301
+ existingMeasurements.push(queueMeasurement);
302
+ this.queueMeasurements.set(correlationId, existingMeasurements);
303
+ }
304
+ else {
305
+ // Sets new correlation Id if not present in queueMeasurements
306
+ this.logger.trace(`PerformanceClient.addQueueMeasurement: adding correlationId ${correlationId} to queue measurements`);
307
+ const measurementArray = [queueMeasurement];
308
+ this.queueMeasurements.set(correlationId, measurementArray);
309
+ }
310
+ // Delete processed pre-queue event.
311
+ this.preQueueTimeByCorrelationId.delete(correlationId);
312
+ }
313
+ /**
314
+ * Starts measuring performance for a given operation. Returns a function that should be used to end the measurement.
315
+ *
316
+ * @param {PerformanceEvents} measureName
317
+ * @param {?string} [correlationId]
318
+ * @returns {InProgressPerformanceEvent}
319
+ */
320
+ startMeasurement(measureName, correlationId) {
321
+ // Generate a placeholder correlation if the request does not provide one
322
+ const eventCorrelationId = correlationId || this.generateId();
323
+ if (!correlationId) {
324
+ this.logger.info(`PerformanceClient: No correlation id provided for ${measureName}, generating`, eventCorrelationId);
325
+ }
326
+ this.logger.trace(`PerformanceClient: Performance measurement started for ${measureName}`, eventCorrelationId);
327
+ const inProgressEvent = {
328
+ eventId: this.generateId(),
329
+ status: PerformanceEventStatus.InProgress,
330
+ authority: this.authority,
331
+ libraryName: this.libraryName,
332
+ libraryVersion: this.libraryVersion,
333
+ clientId: this.clientId,
334
+ name: measureName,
335
+ startTimeMs: Date.now(),
336
+ correlationId: eventCorrelationId,
337
+ appName: this.applicationTelemetry?.appName,
338
+ appVersion: this.applicationTelemetry?.appVersion,
339
+ };
340
+ // Store in progress events so they can be discarded if not ended properly
341
+ this.cacheEventByCorrelationId(inProgressEvent);
342
+ startContext(inProgressEvent, this.abbreviations, this.eventStack.get(eventCorrelationId));
343
+ // Return the event and functions the caller can use to properly end/flush the measurement
344
+ return {
345
+ end: (event, error) => {
346
+ return this.endMeasurement({
347
+ // Initial set of event properties
348
+ ...inProgressEvent,
349
+ // Properties set when event ends
350
+ ...event,
351
+ }, error);
352
+ },
353
+ discard: () => {
354
+ return this.discardMeasurements(inProgressEvent.correlationId);
355
+ },
356
+ add: (fields) => {
357
+ return this.addFields(fields, inProgressEvent.correlationId);
358
+ },
359
+ increment: (fields) => {
360
+ return this.incrementFields(fields, inProgressEvent.correlationId);
361
+ },
362
+ event: inProgressEvent,
363
+ measurement: new StubPerformanceMeasurement(),
364
+ };
365
+ }
366
+ /**
367
+ * Stops measuring the performance for an operation. Should only be called directly by PerformanceClient classes,
368
+ * as consumers should instead use the function returned by startMeasurement.
369
+ * Adds a new field named as "[event name]DurationMs" for sub-measurements, completes and emits an event
370
+ * otherwise.
371
+ *
372
+ * @param {PerformanceEvent} event
373
+ * @param {unknown} error
374
+ * @returns {(PerformanceEvent | null)}
375
+ */
376
+ endMeasurement(event, error) {
377
+ const rootEvent = this.eventsByCorrelationId.get(event.correlationId);
378
+ if (!rootEvent) {
379
+ this.logger.trace(`PerformanceClient: Measurement not found for ${event.eventId}`, event.correlationId);
380
+ return null;
381
+ }
382
+ const isRoot = event.eventId === rootEvent.eventId;
383
+ let queueInfo = {
384
+ totalQueueTime: 0,
385
+ totalQueueCount: 0,
386
+ manuallyCompletedCount: 0,
387
+ };
388
+ event.durationMs = Math.round(event.durationMs || this.getDurationMs(event.startTimeMs));
389
+ const context = JSON.stringify(endContext(event, this.abbreviations, this.eventStack.get(rootEvent.correlationId), error));
390
+ if (isRoot) {
391
+ queueInfo = this.getQueueInfo(event.correlationId);
392
+ this.discardMeasurements(rootEvent.correlationId);
393
+ }
394
+ else {
395
+ rootEvent.incompleteSubMeasurements?.delete(event.eventId);
396
+ }
397
+ this.logger.trace(`PerformanceClient: Performance measurement ended for ${event.name}: ${event.durationMs} ms`, event.correlationId);
398
+ // Add sub-measurement attribute to root event.
399
+ if (!isRoot) {
400
+ rootEvent[event.name + "DurationMs"] = Math.floor(event.durationMs);
401
+ return { ...rootEvent };
402
+ }
403
+ if (error) {
404
+ addError(error, this.logger, rootEvent);
405
+ }
406
+ let finalEvent = { ...rootEvent, ...event };
407
+ let incompleteSubsCount = 0;
408
+ // Incomplete sub-measurements are discarded. They are likely an instrumentation bug that should be fixed.
409
+ finalEvent.incompleteSubMeasurements?.forEach((subMeasurement) => {
410
+ this.logger.trace(`PerformanceClient: Incomplete submeasurement ${subMeasurement.name} found for ${event.name}`, finalEvent.correlationId);
411
+ incompleteSubsCount++;
412
+ });
413
+ finalEvent.incompleteSubMeasurements = undefined;
414
+ finalEvent = {
415
+ ...finalEvent,
416
+ queuedTimeMs: queueInfo.totalQueueTime,
417
+ queuedCount: queueInfo.totalQueueCount,
418
+ queuedManuallyCompletedCount: queueInfo.manuallyCompletedCount,
419
+ status: PerformanceEventStatus.Completed,
420
+ incompleteSubsCount,
421
+ context,
422
+ };
423
+ this.truncateIntegralFields(finalEvent);
424
+ this.emitEvents([finalEvent], event.correlationId);
425
+ return finalEvent;
426
+ }
427
+ /**
428
+ * Saves extra information to be emitted when the measurements are flushed
429
+ * @param fields
430
+ * @param correlationId
431
+ */
432
+ addFields(fields, correlationId) {
433
+ this.logger.trace("PerformanceClient: Updating static fields");
434
+ const event = this.eventsByCorrelationId.get(correlationId);
435
+ if (event) {
436
+ this.eventsByCorrelationId.set(correlationId, {
437
+ ...event,
438
+ ...fields,
439
+ });
440
+ }
441
+ else {
442
+ this.logger.trace("PerformanceClient: Event not found for", correlationId);
443
+ }
444
+ }
445
+ /**
446
+ * Increment counters to be emitted when the measurements are flushed
447
+ * @param fields {string[]}
448
+ * @param correlationId {string} correlation identifier
449
+ */
450
+ incrementFields(fields, correlationId) {
451
+ this.logger.trace("PerformanceClient: Updating counters");
452
+ const event = this.eventsByCorrelationId.get(correlationId);
453
+ if (event) {
454
+ for (const counter in fields) {
455
+ if (!event.hasOwnProperty(counter)) {
456
+ event[counter] = 0;
457
+ }
458
+ else if (isNaN(Number(event[counter]))) {
459
+ return;
460
+ }
461
+ event[counter] += fields[counter];
462
+ }
463
+ }
464
+ else {
465
+ this.logger.trace("PerformanceClient: Event not found for", correlationId);
466
+ }
467
+ }
468
+ /**
469
+ * Upserts event into event cache.
470
+ * First key is the correlation id, second key is the event id.
471
+ * Allows for events to be grouped by correlation id,
472
+ * and to easily allow for properties on them to be updated.
473
+ *
474
+ * @private
475
+ * @param {PerformanceEvent} event
476
+ */
477
+ cacheEventByCorrelationId(event) {
478
+ const rootEvent = this.eventsByCorrelationId.get(event.correlationId);
479
+ if (rootEvent) {
480
+ this.logger.trace(`PerformanceClient: Performance measurement for ${event.name} added/updated`, event.correlationId);
481
+ rootEvent.incompleteSubMeasurements =
482
+ rootEvent.incompleteSubMeasurements || new Map();
483
+ rootEvent.incompleteSubMeasurements.set(event.eventId, {
484
+ name: event.name,
485
+ startTimeMs: event.startTimeMs,
486
+ });
487
+ }
488
+ else {
489
+ this.logger.trace(`PerformanceClient: Performance measurement for ${event.name} started`, event.correlationId);
490
+ this.eventsByCorrelationId.set(event.correlationId, { ...event });
491
+ this.eventStack.set(event.correlationId, []);
492
+ }
493
+ }
494
+ getQueueInfo(correlationId) {
495
+ const queueMeasurementForCorrelationId = this.queueMeasurements.get(correlationId);
496
+ if (!queueMeasurementForCorrelationId) {
497
+ this.logger.trace(`PerformanceClient: no queue measurements found for for correlationId: ${correlationId}`);
498
+ }
499
+ let totalQueueTime = 0;
500
+ let totalQueueCount = 0;
501
+ let manuallyCompletedCount = 0;
502
+ queueMeasurementForCorrelationId?.forEach((measurement) => {
503
+ totalQueueTime += measurement.queueTime;
504
+ totalQueueCount++;
505
+ manuallyCompletedCount += measurement.manuallyCompleted ? 1 : 0;
506
+ });
507
+ return {
508
+ totalQueueTime,
509
+ totalQueueCount,
510
+ manuallyCompletedCount,
511
+ };
512
+ }
513
+ /**
514
+ * Removes measurements and aux data for a given correlation id.
515
+ *
516
+ * @param {string} correlationId
517
+ */
518
+ discardMeasurements(correlationId) {
519
+ this.logger.trace("PerformanceClient: Performance measurements discarded", correlationId);
520
+ this.eventsByCorrelationId.delete(correlationId);
521
+ this.logger.trace("PerformanceClient: QueueMeasurements discarded", correlationId);
522
+ this.queueMeasurements.delete(correlationId);
523
+ this.logger.trace("PerformanceClient: Pre-queue times discarded", correlationId);
524
+ this.preQueueTimeByCorrelationId.delete(correlationId);
525
+ this.logger.trace("PerformanceClient: Event stack discarded", correlationId);
526
+ this.eventStack.delete(correlationId);
527
+ }
528
+ /**
529
+ * Registers a callback function to receive performance events.
530
+ *
531
+ * @param {PerformanceCallbackFunction} callback
532
+ * @returns {string}
533
+ */
534
+ addPerformanceCallback(callback) {
535
+ for (const [id, cb] of this.callbacks) {
536
+ if (cb.toString() === callback.toString()) {
537
+ this.logger.warning(`PerformanceClient: Performance callback is already registered with id: ${id}`);
538
+ return id;
539
+ }
540
+ }
541
+ const callbackId = this.generateId();
542
+ this.callbacks.set(callbackId, callback);
543
+ this.logger.verbose(`PerformanceClient: Performance callback registered with id: ${callbackId}`);
544
+ return callbackId;
545
+ }
546
+ /**
547
+ * Removes a callback registered with addPerformanceCallback.
548
+ *
549
+ * @param {string} callbackId
550
+ * @returns {boolean}
551
+ */
552
+ removePerformanceCallback(callbackId) {
553
+ const result = this.callbacks.delete(callbackId);
554
+ if (result) {
555
+ this.logger.verbose(`PerformanceClient: Performance callback ${callbackId} removed.`);
556
+ }
557
+ else {
558
+ this.logger.verbose(`PerformanceClient: Performance callback ${callbackId} not removed.`);
559
+ }
560
+ return result;
561
+ }
562
+ /**
563
+ * Emits events to all registered callbacks.
564
+ *
565
+ * @param {PerformanceEvent[]} events
566
+ * @param {?string} [correlationId]
567
+ */
568
+ emitEvents(events, correlationId) {
569
+ this.logger.verbose("PerformanceClient: Emitting performance events", correlationId);
570
+ this.callbacks.forEach((callback, callbackId) => {
571
+ this.logger.trace(`PerformanceClient: Emitting event to callback ${callbackId}`, correlationId);
572
+ callback.apply(null, [events]);
573
+ });
574
+ }
575
+ /**
576
+ * Enforce truncation of integral fields in performance event.
577
+ * @param {PerformanceEvent} event performance event to update.
578
+ */
579
+ truncateIntegralFields(event) {
580
+ this.intFields.forEach((key) => {
581
+ if (key in event && typeof event[key] === "number") {
582
+ event[key] = Math.floor(event[key]);
583
+ }
584
+ });
585
+ }
586
+ /**
587
+ * Returns event duration in milliseconds
588
+ * @param startTimeMs {number}
589
+ * @returns {number}
590
+ */
591
+ getDurationMs(startTimeMs) {
592
+ const durationMs = Date.now() - startTimeMs;
593
+ // Handle clock skew
594
+ return durationMs < 0 ? durationMs : 0;
595
+ }
596
596
  }
597
597
 
598
598
  export { PerformanceClient, addError, compactStack, compactStackLine, endContext, startContext };