@contrail/flexplm 3.0.0-alpha.fbb6338 → 4.0.0-alpha.99ba16b

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.
@@ -2,6 +2,30 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.FlexPLMConnect = void 0;
4
4
  const app_framework_1 = require("@contrail/app-framework");
5
+ const telemetry_1 = require("@contrail/telemetry");
6
+ const telemetry_attributes_1 = require("./telemetry-attributes");
7
+ const telemetry_utils_1 = require("./telemetry-utils");
8
+ // Telemetry: only the path is recorded, never the host or the query string (it can carry file paths).
9
+ const toUrlPath = (path) => (path || '').split('?')[0];
10
+ const MAX_LOGGED_RESPONSE_BODY = 2048;
11
+ const truncateForLog = (text) => text.length > MAX_LOGGED_RESPONSE_BODY ? text.substring(0, MAX_LOGGED_RESPONSE_BODY) + '...(truncated)' : text;
12
+ /** Reads the response body for an error log; never throws (the body may already be consumed). */
13
+ const readBodyForLog = async (response) => {
14
+ try {
15
+ return truncateForLog(await response.text());
16
+ }
17
+ catch (e) {
18
+ return '(response body unavailable)';
19
+ }
20
+ };
21
+ const logFlexPLMError = async (message, response, urlPath) => {
22
+ telemetry_1.logger.error({ flexplm: { status: response.status, url_path: urlPath, response_body: await readBodyForLog(response) } }, message);
23
+ };
24
+ /** Same as logFlexPLMError, for when the caller has already read the body (it can only be read once). */
25
+ const logFlexPLMErrorBody = (message, status, urlPath, responseBody) => {
26
+ const body = responseBody === undefined ? '(response body unavailable)' : truncateForLog(responseBody);
27
+ telemetry_1.logger.error({ flexplm: { status, url_path: urlPath, response_body: body } }, message);
28
+ };
5
29
  // Module-level on purpose: a new FlexPLMConnect is constructed for every event. Declaring for Session reusing use case.
6
30
  const sessionCache = new Map();
7
31
  // Upper bound so users/option combinations that are never requested again cannot accumulate cookies forever.
@@ -105,6 +129,14 @@ class FlexPLMConnect {
105
129
  }
106
130
  })();
107
131
  }
132
+ /** Marks the active span when this request is about to wait for another request's cold acquisition.
133
+ * Synchronous on purpose: it must not add an await to the wait loops (see waitForInFlightAcquisition).
134
+ */
135
+ recordWaitForInFlightAcquisition() {
136
+ if (inFlightAcquisitions.has(this.getSessionKey())) {
137
+ (0, telemetry_utils_1.setActiveSpanAttributes)({ [telemetry_attributes_1.ATTR_FLEXPLM_SESSION_WAITED]: true });
138
+ }
139
+ }
108
140
  /** Runs a cold acquisition and registers it so concurrent callers wait for it instead of opening their own session. */
109
141
  async runColdAcquisition(acquire) {
110
142
  const key = this.getSessionKey();
@@ -230,8 +262,11 @@ class FlexPLMConnect {
230
262
  // rejectedCookie: the cookie that was rejected by the caller, so a refresh already done by a concurrent event is not thrown away
231
263
  async getCSRF(getNewSession = false, rejectedCookie) {
232
264
  // Added for Session reuse - ET-390 - Starts
233
- if (!this.sessionOptions.enabled)
265
+ if (!this.sessionOptions.enabled) {
266
+ (0, telemetry_utils_1.setActiveSpanAttributes)({ [telemetry_attributes_1.ATTR_FLEXPLM_SESSION_SOURCE]: 'disabled' });
234
267
  return this.fetchCSRF(undefined);
268
+ }
269
+ this.recordWaitForInFlightAcquisition();
235
270
  for (let wait = this.waitForInFlightAcquisition(); wait; wait = this.waitForInFlightAcquisition())
236
271
  await wait;
237
272
  if (getNewSession) {
@@ -240,6 +275,8 @@ class FlexPLMConnect {
240
275
  this.clearSession();
241
276
  }
242
277
  const cached = this.getCachedSession();
278
+ // Set on the caller's span; a retry below overwrites it with the session that was finally used.
279
+ (0, telemetry_utils_1.setActiveSpanAttributes)({ [telemetry_attributes_1.ATTR_FLEXPLM_SESSION_SOURCE]: cached ? 'cached' : 'new' });
243
280
  if (cached) {
244
281
  try {
245
282
  return await this.fetchCSRF(cached);
@@ -261,50 +298,62 @@ class FlexPLMConnect {
261
298
  const csrfEndpoint = this.config.csrfEndpoint;
262
299
  const csrfURL = this.config.apiHost + urlContext + csrfEndpoint;
263
300
  console.info('csrfURL: ' + csrfURL);
264
- // getRequestOptions will be called with additional sentCookie parameter
265
- const csrfOptions = this.getRequestOptions('GET', sentCookie);
266
- const response = await fetch(csrfURL, csrfOptions);
267
- // Added for Session reuse - ET-390 - Starts
268
- if (sentCookie && this.sessionOptions.retryStatuses.includes(response.status)) {
269
- console.warn('Cached FlexPLM session rejected on csrf call (status ' + response.status + '). Retrying with a new session.');
270
- await this.discardBody(response);
301
+ const urlPath = toUrlPath(urlContext + csrfEndpoint);
302
+ const result = await (0, telemetry_1.traceSection)('fetch_flexplm_csrf', {
303
+ [telemetry_attributes_1.ATTR_FLEXPLM_REQUEST_KIND]: 'csrf',
304
+ [telemetry_attributes_1.ATTR_HTTP_REQUEST_METHOD]: 'GET',
305
+ [telemetry_attributes_1.ATTR_URL_PATH]: urlPath,
306
+ }, async (span) => {
307
+ // getRequestOptions will be called with additional sentCookie parameter
308
+ const csrfOptions = this.getRequestOptions('GET', sentCookie);
309
+ const response = await fetch(csrfURL, csrfOptions);
310
+ span.setAttribute(telemetry_attributes_1.ATTR_HTTP_RESPONSE_STATUS_CODE, response.status);
311
+ // Added for Session reuse - ET-390 - Starts
312
+ if (sentCookie && this.sessionOptions.retryStatuses.includes(response.status)) {
313
+ console.warn('Cached FlexPLM session rejected on csrf call (status ' + response.status + '). Retrying with a new session.');
314
+ // Expected and retried by getCSRF, so it is an event and the span stays OK.
315
+ span.addEvent('flexplm_session_rejected');
316
+ await this.discardBody(response);
317
+ return { sessionRejected: true };
318
+ }
319
+ // Added for Session reuse - ET-390 - Ends
320
+ if (response.status >= 300) {
321
+ const message = 'Error connecting to FlexPLM:status: ' + response.status;
322
+ await logFlexPLMError(message, response, urlPath);
323
+ const e = new Error(message);
324
+ e['httpResponseStatus'] = response.status;
325
+ throw e;
326
+ }
327
+ // Added for Session reuse - ET-390 - Starts
328
+ // If the cookie we sent was invalid, Windchill answers with a fresh Set-Cookie --> replace the cache.
329
+ let sessionCookie = sentCookie;
330
+ if (this.sessionOptions.enabled) {
331
+ sessionCookie = this.extractSessionCookie(response) ?? sentCookie;
332
+ if (sessionCookie)
333
+ this.storeSession(sessionCookie);
334
+ }
335
+ // Added for Session reuse - ET-390 - Ends
336
+ try {
337
+ const body = await response.json();
338
+ const nonce_key = body.items[0].attributes.nonce_key;
339
+ const nonce = body.items[0].attributes.nonce;
340
+ // ET-390 - adding sessionCookie to the return
341
+ return {
342
+ nonce_key,
343
+ nonce,
344
+ sessionCookie,
345
+ };
346
+ }
347
+ catch (e) {
348
+ const message = 'Error connecting to FlexPLM: ' + e.message;
349
+ await logFlexPLMError(message, response, urlPath);
350
+ throw new Error(message);
351
+ }
352
+ });
353
+ // Thrown outside the span so the expected rejection is not recorded as a span error.
354
+ if ('sessionRejected' in result)
271
355
  throw new SessionRejectedError();
272
- }
273
- // Added for Session reuse - ET-390 - Ends
274
- if (response.status >= 300) {
275
- const message = 'Error connecting to FlexPLM:status: ' + response.status;
276
- console.error(message);
277
- console.error(await response.text());
278
- const e = new Error(message);
279
- e['httpResponseStatus'] = response.status;
280
- throw e;
281
- }
282
- // Added for Session reuse - ET-390 - Starts
283
- // If the cookie we sent was invalid, Windchill answers with a fresh Set-Cookie --> replace the cache.
284
- let sessionCookie = sentCookie;
285
- if (this.sessionOptions.enabled) {
286
- sessionCookie = this.extractSessionCookie(response) ?? sentCookie;
287
- if (sessionCookie)
288
- this.storeSession(sessionCookie);
289
- }
290
- // Added for Session reuse - ET-390 - Ends
291
- try {
292
- const body = await response.json();
293
- const nonce_key = body.items[0].attributes.nonce_key;
294
- const nonce = body.items[0].attributes.nonce;
295
- // ET-390 - adding sessionCookie to the return
296
- return {
297
- nonce_key,
298
- nonce,
299
- sessionCookie,
300
- };
301
- }
302
- catch (e) {
303
- const message = 'Error connecting to FlexPLM: ' + e.message;
304
- console.error(message);
305
- console.error(await response.text());
306
- throw new Error(message);
307
- }
356
+ return result;
308
357
  }
309
358
  async sendRequest(csrf, payload) {
310
359
  if (this.payloadSendAsArray && !Array.isArray(payload)) {
@@ -332,70 +381,87 @@ class FlexPLMConnect {
332
381
  return eventResponse;
333
382
  }
334
383
  async processRequest(payload) {
335
- if (!payload) {
336
- const message = 'No payload to send to FlexPLM';
337
- console.error(message);
338
- throw new Error(message);
339
- }
340
- if (app_framework_1.Logger.isInfoOn()) {
341
- console.info('payload: ' + JSON.stringify(payload));
342
- }
343
- let csrf = await this.getCSRF();
344
- if (!csrf) {
345
- const message = 'Failed to get CSRF nonce';
346
- console.error(message);
347
- throw new Error(message);
348
- }
349
- /// Added for Session reuse - ET-390 - Starts
350
- // const response = await this.sendRequest(csrf, payload);
351
- let response = await this.sendRequest(csrf, payload);
352
- if (csrf.sessionCookie && this.sessionOptions.retryStatuses.includes(response.status)) {
353
- console.warn('FlexPLM rejected session/nonce (status ' + response.status + '). Getting a new session and retrying once.');
354
- await this.discardBody(response);
355
- csrf = await this.getCSRF(true, csrf.sessionCookie);
356
- response = await this.sendRequest(csrf, payload);
357
- }
358
- // Added for Session reuse - ET-390 - Ends
359
- const status = response.status;
360
- if (status >= 300) {
361
- let responseBody;
362
- try {
363
- responseBody = await response.text();
384
+ const urlPath = toUrlPath(this.config.urlContext + '/servlet/rest' + this.vibeEventEndpoint);
385
+ return (0, telemetry_1.traceSection)('send_to_flexplm', {
386
+ [telemetry_attributes_1.ATTR_FLEXPLM_REQUEST_KIND]: 'send',
387
+ [telemetry_attributes_1.ATTR_HTTP_REQUEST_METHOD]: 'POST',
388
+ [telemetry_attributes_1.ATTR_URL_PATH]: urlPath,
389
+ [telemetry_attributes_1.ATTR_FLEXPLM_PAYLOAD_COUNT]: Array.isArray(payload) ? payload.length : (payload ? 1 : 0),
390
+ [telemetry_attributes_1.ATTR_FLEXPLM_REQUEST_RETRIED]: false,
391
+ }, async (span) => {
392
+ if (!payload) {
393
+ const message = 'No payload to send to FlexPLM';
394
+ console.error(message);
395
+ throw new Error(message);
364
396
  }
365
- catch (e) {
366
- console.error('Error reading FlexPLM error response body: ' + e?.message);
397
+ if (app_framework_1.Logger.isInfoOn()) {
398
+ console.info('payload: ' + JSON.stringify(payload));
367
399
  }
368
- throw this.createResponseError('Error sending data to FlexPLM:status: ' + status, status, responseBody);
369
- }
370
- const res = {
371
- status,
372
- };
373
- if (![204, 205].includes(status)) {
374
- let responseBody;
375
- try {
376
- responseBody = await response.text();
377
- if (responseBody.trim() === '') {
378
- // An empty body is a valid success response.
379
- res.data = {};
400
+ let csrf = await this.getCSRF();
401
+ if (!csrf) {
402
+ const message = 'Failed to get CSRF nonce';
403
+ console.error(message);
404
+ throw new Error(message);
405
+ }
406
+ /// Added for Session reuse - ET-390 - Starts
407
+ // const response = await this.sendRequest(csrf, payload);
408
+ let response = await this.sendRequest(csrf, payload);
409
+ if (csrf.sessionCookie && this.sessionOptions.retryStatuses.includes(response.status)) {
410
+ console.warn('FlexPLM rejected session/nonce (status ' + response.status + '). Getting a new session and retrying once.');
411
+ span.setAttribute(telemetry_attributes_1.ATTR_FLEXPLM_REQUEST_RETRIED, true);
412
+ await this.discardBody(response);
413
+ csrf = await this.getCSRF(true, csrf.sessionCookie);
414
+ response = await this.sendRequest(csrf, payload);
415
+ }
416
+ // Added for Session reuse - ET-390 - Ends
417
+ const status = response.status;
418
+ span.setAttribute(telemetry_attributes_1.ATTR_HTTP_RESPONSE_STATUS_CODE, status);
419
+ if (status >= 300) {
420
+ // The body can only be read once, so read it here and share it between the log and the error.
421
+ let responseBody;
422
+ try {
423
+ responseBody = await response.text();
380
424
  }
381
- else {
382
- try {
383
- res.data = JSON.parse(responseBody);
425
+ catch (e) {
426
+ console.error('Error reading FlexPLM error response body: ' + e?.message);
427
+ }
428
+ const message = 'Error sending data to FlexPLM:status: ' + status;
429
+ logFlexPLMErrorBody(message, status, urlPath, responseBody);
430
+ // traceSection records the thrown error and sets the span status to ERROR.
431
+ throw this.createResponseError(message, status, responseBody);
432
+ }
433
+ const res = {
434
+ status,
435
+ };
436
+ if (![204, 205].includes(status)) {
437
+ let responseBody;
438
+ try {
439
+ responseBody = await response.text();
440
+ if (responseBody.trim() === '') {
441
+ // An empty body is a valid success response.
442
+ res.data = {};
384
443
  }
385
- catch (parseError) {
386
- if (!this.allowNonJsonResponse)
387
- throw parseError;
388
- console.warn('FlexPLM response is not JSON; allowNonJsonResponse is enabled, returning raw body. status: ' + status);
389
- res.data = { responseBody };
444
+ else {
445
+ try {
446
+ res.data = JSON.parse(responseBody);
447
+ }
448
+ catch (parseError) {
449
+ if (!this.allowNonJsonResponse)
450
+ throw parseError;
451
+ console.warn('FlexPLM response is not JSON; allowNonJsonResponse is enabled, returning raw body. status: ' + status);
452
+ res.data = { responseBody };
453
+ }
390
454
  }
391
455
  }
456
+ catch (e) {
457
+ const message = 'Error getting json data from FlexPLM:status: ' + status + ': ' + e?.message;
458
+ logFlexPLMErrorBody(message, status, urlPath, responseBody);
459
+ throw this.createResponseError(message, status, responseBody);
460
+ }
392
461
  }
393
- catch (e) {
394
- throw this.createResponseError('Error getting json data from FlexPLM:status: ' + status + ': ' + e?.message, status, responseBody);
395
- }
396
- }
397
- console.log('eventResponse.status: ' + status);
398
- return res;
462
+ console.log('eventResponse.status: ' + status);
463
+ return res;
464
+ });
399
465
  }
400
466
  /** Builds the error thrown for a failed FlexPLM response. The response body is put on
401
467
  * `details` so that it is surfaced as `errorDetails` in the event output.
@@ -436,54 +502,65 @@ class FlexPLMConnect {
436
502
  const urlContext = includeUrlContext ? this.config.urlContext : '';
437
503
  const path = urlPath || ('/servlet/rest' + this.vibeEventEndpoint);
438
504
  const vibeEventsURL = this.config.apiHost + urlContext + path;
439
- // Added for Session reuse - ET-390 - Starts
440
- const attempt = async () => {
441
- if (!this.sessionOptions.enabled) {
442
- return { response: await fetch(vibeEventsURL, this.getRequestOptions('GET')), sent: undefined };
443
- }
444
- for (let wait = this.waitForInFlightAcquisition(); wait; wait = this.waitForInFlightAcquisition())
445
- await wait;
446
- const sent = this.getCachedSession();
447
- const call = async () => {
448
- const res = await fetch(vibeEventsURL, this.getRequestOptions('GET', sent));
449
- // A rejected cookie must not be stored again; only keep a cookie that was accepted or newly issued.
450
- if (!(sent && this.sessionOptions.retryStatuses.includes(res.status))) {
451
- const cookie = this.extractSessionCookie(res) ?? sent;
452
- if (cookie)
453
- this.storeSession(cookie);
505
+ const spanUrlPath = toUrlPath(urlContext + path);
506
+ return (0, telemetry_1.traceSection)('get_from_flexplm', {
507
+ [telemetry_attributes_1.ATTR_FLEXPLM_REQUEST_KIND]: 'get',
508
+ [telemetry_attributes_1.ATTR_HTTP_REQUEST_METHOD]: 'GET',
509
+ [telemetry_attributes_1.ATTR_URL_PATH]: spanUrlPath,
510
+ [telemetry_attributes_1.ATTR_FLEXPLM_REQUEST_RETRIED]: false,
511
+ }, async (span) => {
512
+ // Added for Session reuse - ET-390 - Starts
513
+ const attempt = async () => {
514
+ if (!this.sessionOptions.enabled) {
515
+ span.setAttribute(telemetry_attributes_1.ATTR_FLEXPLM_SESSION_SOURCE, 'disabled');
516
+ return { response: await fetch(vibeEventsURL, this.getRequestOptions('GET')), sent: undefined };
454
517
  }
455
- return { response: res, sent };
518
+ this.recordWaitForInFlightAcquisition();
519
+ for (let wait = this.waitForInFlightAcquisition(); wait; wait = this.waitForInFlightAcquisition())
520
+ await wait;
521
+ const sent = this.getCachedSession();
522
+ span.setAttribute(telemetry_attributes_1.ATTR_FLEXPLM_SESSION_SOURCE, sent ? 'cached' : 'new');
523
+ const call = async () => {
524
+ const res = await fetch(vibeEventsURL, this.getRequestOptions('GET', sent));
525
+ // A rejected cookie must not be stored again; only keep a cookie that was accepted or newly issued.
526
+ if (!(sent && this.sessionOptions.retryStatuses.includes(res.status))) {
527
+ const cookie = this.extractSessionCookie(res) ?? sent;
528
+ if (cookie)
529
+ this.storeSession(cookie);
530
+ }
531
+ return { response: res, sent };
532
+ };
533
+ return sent ? call() : this.runColdAcquisition(call);
456
534
  };
457
- return sent ? call() : this.runColdAcquisition(call);
458
- };
459
- const first = await attempt();
460
- let response = first.response;
461
- if (first.sent && this.sessionOptions.retryStatuses.includes(response.status)) {
462
- await this.discardBody(response);
463
- if (this.getCachedSession() === first.sent)
464
- this.clearSession();
465
- response = (await attempt()).response;
466
- }
467
- // Added for Session reuse - ET-390 - Ends
468
- if (response.status >= 300) {
469
- const message = 'Error connecting to FlexPLM:status: ' + response.status;
470
- console.error(message);
471
- console.error(await response.text());
472
- throw new Error(message);
473
- }
474
- if (returnFullResponse) {
475
- return response;
476
- }
477
- try {
478
- const data = await response.json();
479
- return data;
480
- }
481
- catch (e) {
482
- const message = 'Error getting json data from FlexPLM: ' + e.message;
483
- console.error(message);
484
- console.error(await response.text());
485
- throw new Error(message);
486
- }
535
+ const first = await attempt();
536
+ let response = first.response;
537
+ if (first.sent && this.sessionOptions.retryStatuses.includes(response.status)) {
538
+ span.setAttribute(telemetry_attributes_1.ATTR_FLEXPLM_REQUEST_RETRIED, true);
539
+ await this.discardBody(response);
540
+ if (this.getCachedSession() === first.sent)
541
+ this.clearSession();
542
+ response = (await attempt()).response;
543
+ }
544
+ // Added for Session reuse - ET-390 - Ends
545
+ span.setAttribute(telemetry_attributes_1.ATTR_HTTP_RESPONSE_STATUS_CODE, response.status);
546
+ if (response.status >= 300) {
547
+ const message = 'Error connecting to FlexPLM:status: ' + response.status;
548
+ await logFlexPLMError(message, response, spanUrlPath);
549
+ throw new Error(message);
550
+ }
551
+ if (returnFullResponse) {
552
+ return response;
553
+ }
554
+ try {
555
+ const data = await response.json();
556
+ return data;
557
+ }
558
+ catch (e) {
559
+ const message = 'Error getting json data from FlexPLM: ' + e.message;
560
+ await logFlexPLMError(message, response, spanUrlPath);
561
+ throw new Error(message);
562
+ }
563
+ });
487
564
  }
488
565
  }
489
566
  exports.FlexPLMConnect = FlexPLMConnect;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,212 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const api_1 = require("@opentelemetry/api");
4
+ const telemetry_1 = require("@contrail/telemetry");
5
+ const flexplm_connect_1 = require("./flexplm-connect");
6
+ const telemetry_test_utils_1 = require("../__tests__/telemetry-test-utils");
7
+ const telemetry_attributes_1 = require("./telemetry-attributes");
8
+ // Same mocks as flexplm-connect.spec.ts
9
+ const csrfBody = { items: [{ attributes: { nonce_key: 'CSRF_NONCE', nonce: 'secret-nonce-value' } }] };
10
+ const resp = (status, setCookie = [], json = csrfBody) => ({
11
+ status,
12
+ json: jest.fn().mockResolvedValue(json),
13
+ text: jest.fn().mockResolvedValue(status >= 300 ? 'error text' : JSON.stringify(json)),
14
+ headers: { getSetCookie: () => setCookie, get: () => null },
15
+ });
16
+ const createConfig = (overrides) => ({
17
+ apiHost: 'https://flexplm.example.com',
18
+ urlContext: '/FlexPLM',
19
+ vibeEventEndpoint: '/api/events',
20
+ csrfEndpoint: '/csrf',
21
+ plmEnviornment: 'test',
22
+ userName: () => 'user',
23
+ password: () => 'super-secret-password',
24
+ itemPreDevelopmentLifecycleStages: [],
25
+ payloadDefaultAsArray: true,
26
+ useDistinctRestEndPointForImages: false,
27
+ ...overrides,
28
+ });
29
+ // The session cache is module level, so each test uses its own user to start cold.
30
+ let userCounter = 0;
31
+ const sessionConfig = () => {
32
+ const user = 'telemetry-user-' + (++userCounter);
33
+ return createConfig({ userName: () => user, flexplmConnect: { sessionReuse: { enabled: true } } });
34
+ };
35
+ const fetchMock = () => global.fetch;
36
+ const payload = { eventType: 'PERSIST', objectClass: 'LCSProduct', data: {} };
37
+ const allRecordedValues = (spans) => spans.flatMap(span => [
38
+ ...Object.values(span.attributes).map(String),
39
+ ...span.events.flatMap(event => [event.name, ...Object.values(event.attributes || {}).map(String)]),
40
+ ]);
41
+ describe('FlexPLMConnect telemetry', () => {
42
+ let exporter;
43
+ const globalFetch = global.fetch;
44
+ beforeAll(() => {
45
+ exporter = (0, telemetry_test_utils_1.registerInMemoryTracing)();
46
+ });
47
+ beforeEach(() => {
48
+ exporter.reset();
49
+ global.fetch = jest.fn();
50
+ });
51
+ afterEach(() => {
52
+ jest.restoreAllMocks();
53
+ });
54
+ afterAll(() => {
55
+ global.fetch = globalFetch;
56
+ });
57
+ it('should record a send_to_flexplm span with http.response.status_code 200', async () => {
58
+ fetchMock()
59
+ .mockResolvedValueOnce(resp(200))
60
+ .mockResolvedValueOnce(resp(200, [], { ok: true }));
61
+ await new flexplm_connect_1.FlexPLMConnect(createConfig()).sendToFlexPLM(payload);
62
+ const send = (0, telemetry_test_utils_1.findSpan)(exporter, 'send_to_flexplm');
63
+ expect(send.attributes).toEqual(expect.objectContaining({
64
+ [telemetry_attributes_1.ATTR_FLEXPLM_REQUEST_KIND]: 'send',
65
+ [telemetry_attributes_1.ATTR_HTTP_REQUEST_METHOD]: 'POST',
66
+ [telemetry_attributes_1.ATTR_URL_PATH]: '/FlexPLM/servlet/rest/api/events',
67
+ [telemetry_attributes_1.ATTR_FLEXPLM_PAYLOAD_COUNT]: 1,
68
+ [telemetry_attributes_1.ATTR_FLEXPLM_REQUEST_RETRIED]: false,
69
+ [telemetry_attributes_1.ATTR_HTTP_RESPONSE_STATUS_CODE]: 200,
70
+ }));
71
+ expect(send.status.code).not.toBe(api_1.SpanStatusCode.ERROR);
72
+ const csrf = (0, telemetry_test_utils_1.findSpan)(exporter, 'fetch_flexplm_csrf');
73
+ expect(csrf.attributes).toEqual(expect.objectContaining({
74
+ [telemetry_attributes_1.ATTR_FLEXPLM_REQUEST_KIND]: 'csrf',
75
+ [telemetry_attributes_1.ATTR_HTTP_REQUEST_METHOD]: 'GET',
76
+ [telemetry_attributes_1.ATTR_URL_PATH]: '/FlexPLM/csrf',
77
+ [telemetry_attributes_1.ATTR_HTTP_RESPONSE_STATUS_CODE]: 200,
78
+ }));
79
+ expect((0, telemetry_test_utils_1.isChildOf)(csrf, send)).toBe(true);
80
+ });
81
+ it('should set retried true when the cached session is rejected', async () => {
82
+ fetchMock()
83
+ .mockResolvedValueOnce(resp(200, ['JSESSIONID=first; Path=/']))
84
+ .mockResolvedValueOnce(resp(403))
85
+ .mockResolvedValueOnce(resp(200, ['JSESSIONID=second; Path=/']))
86
+ .mockResolvedValueOnce(resp(200, [], { ok: true }));
87
+ await new flexplm_connect_1.FlexPLMConnect(sessionConfig()).sendToFlexPLM(payload);
88
+ const send = (0, telemetry_test_utils_1.findSpan)(exporter, 'send_to_flexplm');
89
+ expect(send.attributes[telemetry_attributes_1.ATTR_FLEXPLM_REQUEST_RETRIED]).toBe(true);
90
+ expect(send.attributes[telemetry_attributes_1.ATTR_HTTP_RESPONSE_STATUS_CODE]).toBe(200);
91
+ expect(send.status.code).not.toBe(api_1.SpanStatusCode.ERROR);
92
+ });
93
+ it('should record a rejected cached session on the csrf call as an event, not an error', async () => {
94
+ const config = sessionConfig();
95
+ // Warm the cache with a cookie.
96
+ fetchMock()
97
+ .mockResolvedValueOnce(resp(200, ['JSESSIONID=cached; Path=/']))
98
+ .mockResolvedValueOnce(resp(200, [], { ok: true }));
99
+ await new flexplm_connect_1.FlexPLMConnect(config).sendToFlexPLM(payload);
100
+ exporter.reset();
101
+ fetchMock()
102
+ .mockResolvedValueOnce(resp(401))
103
+ .mockResolvedValueOnce(resp(200, ['JSESSIONID=fresh; Path=/']))
104
+ .mockResolvedValueOnce(resp(200, [], { ok: true }));
105
+ await new flexplm_connect_1.FlexPLMConnect(config).sendToFlexPLM(payload);
106
+ const [rejected, fresh] = (0, telemetry_test_utils_1.findSpans)(exporter, 'fetch_flexplm_csrf');
107
+ expect(rejected.events.map(event => event.name)).toEqual(['flexplm_session_rejected']);
108
+ expect(rejected.status.code).not.toBe(api_1.SpanStatusCode.ERROR);
109
+ expect(rejected.attributes[telemetry_attributes_1.ATTR_HTTP_RESPONSE_STATUS_CODE]).toBe(401);
110
+ expect(fresh.events).toEqual([]);
111
+ expect(fresh.attributes[telemetry_attributes_1.ATTR_HTTP_RESPONSE_STATUS_CODE]).toBe(200);
112
+ expect((0, telemetry_test_utils_1.findSpan)(exporter, 'send_to_flexplm').status.code).not.toBe(api_1.SpanStatusCode.ERROR);
113
+ });
114
+ it('should set the span status to ERROR when FlexPLM returns 500', async () => {
115
+ const errorLog = jest.spyOn(telemetry_1.logger, 'error').mockImplementation(() => undefined);
116
+ fetchMock()
117
+ .mockResolvedValueOnce(resp(200))
118
+ .mockResolvedValueOnce(resp(500));
119
+ await expect(new flexplm_connect_1.FlexPLMConnect(createConfig()).sendToFlexPLM(payload))
120
+ .rejects.toThrow('Error sending data to FlexPLM:status: 500');
121
+ const send = (0, telemetry_test_utils_1.findSpan)(exporter, 'send_to_flexplm');
122
+ expect(send.status.code).toBe(api_1.SpanStatusCode.ERROR);
123
+ expect(send.attributes[telemetry_attributes_1.ATTR_HTTP_RESPONSE_STATUS_CODE]).toBe(500);
124
+ expect(send.events.map(event => event.name)).toContain('exception');
125
+ expect(errorLog).toHaveBeenCalledWith({ flexplm: { status: 500, url_path: '/FlexPLM/servlet/rest/api/events', response_body: 'error text' } }, 'Error sending data to FlexPLM:status: 500');
126
+ });
127
+ it('should truncate the logged response body', async () => {
128
+ const errorLog = jest.spyOn(telemetry_1.logger, 'error').mockImplementation(() => undefined);
129
+ const failed = resp(500);
130
+ failed.text.mockResolvedValue('x'.repeat(5000));
131
+ fetchMock()
132
+ .mockResolvedValueOnce(resp(200))
133
+ .mockResolvedValueOnce(failed);
134
+ await expect(new flexplm_connect_1.FlexPLMConnect(createConfig()).sendToFlexPLM(payload)).rejects.toThrow();
135
+ const logged = errorLog.mock.calls[0][0].flexplm.response_body;
136
+ expect(logged.length).toBeLessThan(2100);
137
+ expect(logged.endsWith('...(truncated)')).toBe(true);
138
+ });
139
+ it('should record only the path of a getRequest, without the host or query string', async () => {
140
+ fetchMock().mockResolvedValueOnce(resp(200, [], { ok: true }));
141
+ await new flexplm_connect_1.FlexPLMConnect(createConfig()).getRequest({ urlPath: '/servlet/rest/rfa/vibeiq/image?path=%2Fsecret%2Ffile.png' });
142
+ const get = (0, telemetry_test_utils_1.findSpan)(exporter, 'get_from_flexplm');
143
+ expect(get.attributes).toEqual(expect.objectContaining({
144
+ [telemetry_attributes_1.ATTR_FLEXPLM_REQUEST_KIND]: 'get',
145
+ [telemetry_attributes_1.ATTR_URL_PATH]: '/FlexPLM/servlet/rest/rfa/vibeiq/image',
146
+ [telemetry_attributes_1.ATTR_HTTP_RESPONSE_STATUS_CODE]: 200,
147
+ [telemetry_attributes_1.ATTR_FLEXPLM_REQUEST_RETRIED]: false,
148
+ }));
149
+ });
150
+ it('should record the session source: disabled, then new, then cached', async () => {
151
+ fetchMock().mockResolvedValueOnce(resp(200)).mockResolvedValueOnce(resp(200, [], { ok: true }));
152
+ await new flexplm_connect_1.FlexPLMConnect(createConfig()).sendToFlexPLM(payload);
153
+ expect((0, telemetry_test_utils_1.findSpan)(exporter, 'send_to_flexplm').attributes[telemetry_attributes_1.ATTR_FLEXPLM_SESSION_SOURCE]).toBe('disabled');
154
+ const config = sessionConfig();
155
+ for (let i = 0; i < 2; i++) {
156
+ fetchMock().mockResolvedValueOnce(resp(200, ['JSESSIONID=reused; Path=/'])).mockResolvedValueOnce(resp(200, [], { ok: true }));
157
+ }
158
+ exporter.reset();
159
+ await new flexplm_connect_1.FlexPLMConnect(config).sendToFlexPLM(payload);
160
+ await new flexplm_connect_1.FlexPLMConnect(config).sendToFlexPLM(payload);
161
+ const [first, second] = (0, telemetry_test_utils_1.findSpans)(exporter, 'send_to_flexplm');
162
+ expect(first.attributes[telemetry_attributes_1.ATTR_FLEXPLM_SESSION_SOURCE]).toBe('new');
163
+ expect(second.attributes[telemetry_attributes_1.ATTR_FLEXPLM_SESSION_SOURCE]).toBe('cached');
164
+ expect(first.attributes[telemetry_attributes_1.ATTR_FLEXPLM_SESSION_WAITED]).toBeUndefined();
165
+ });
166
+ it('should record session.source new after a rejected cached session is replaced', async () => {
167
+ const config = sessionConfig();
168
+ fetchMock().mockResolvedValueOnce(resp(200, ['JSESSIONID=cached; Path=/'])).mockResolvedValueOnce(resp(200, [], { ok: true }));
169
+ await new flexplm_connect_1.FlexPLMConnect(config).sendToFlexPLM(payload);
170
+ exporter.reset();
171
+ fetchMock()
172
+ .mockResolvedValueOnce(resp(401))
173
+ .mockResolvedValueOnce(resp(200, ['JSESSIONID=fresh; Path=/']))
174
+ .mockResolvedValueOnce(resp(200, [], { ok: true }));
175
+ await new flexplm_connect_1.FlexPLMConnect(config).sendToFlexPLM(payload);
176
+ expect((0, telemetry_test_utils_1.findSpan)(exporter, 'send_to_flexplm').attributes[telemetry_attributes_1.ATTR_FLEXPLM_SESSION_SOURCE]).toBe('new');
177
+ });
178
+ it('should record session.waited when a request waits for another request\'s session acquisition', async () => {
179
+ const config = sessionConfig();
180
+ let release;
181
+ const gate = new Promise(r => { release = r; });
182
+ fetchMock().mockImplementation(async (_url, opts) => {
183
+ if (opts.method === 'GET' && !opts.headers.Cookie) {
184
+ await gate;
185
+ return resp(200, ['JSESSIONID=shared; Path=/']);
186
+ }
187
+ return opts.method === 'GET' ? resp(200) : resp(200, [], { ok: true });
188
+ });
189
+ const all = Promise.all([1, 2].map(() => new flexplm_connect_1.FlexPLMConnect(config).sendToFlexPLM(payload)));
190
+ await new Promise(r => setImmediate(r));
191
+ release();
192
+ await all;
193
+ const spans = (0, telemetry_test_utils_1.findSpans)(exporter, 'send_to_flexplm');
194
+ expect(spans.map(span => span.attributes[telemetry_attributes_1.ATTR_FLEXPLM_SESSION_WAITED]).sort()).toEqual([true, undefined]);
195
+ expect(spans.map(span => span.attributes[telemetry_attributes_1.ATTR_FLEXPLM_SESSION_SOURCE]).sort()).toEqual(['cached', 'new']);
196
+ });
197
+ it('should not record Authorization, Cookie or nonce values on any span', async () => {
198
+ fetchMock()
199
+ .mockResolvedValueOnce(resp(200, ['JSESSIONID=cookie-value-1; Path=/']))
200
+ .mockResolvedValueOnce(resp(403))
201
+ .mockResolvedValueOnce(resp(200, ['JSESSIONID=cookie-value-2; Path=/']))
202
+ .mockResolvedValueOnce(resp(200, [], { ok: true }));
203
+ await new flexplm_connect_1.FlexPLMConnect(sessionConfig()).sendToFlexPLM(payload);
204
+ const spans = exporter.getFinishedSpans();
205
+ expect(spans.length).toBeGreaterThan(0);
206
+ const recorded = allRecordedValues(spans).join('\n');
207
+ const authorization = Buffer.from('telemetry-user-' + userCounter + ':super-secret-password').toString('base64');
208
+ for (const secret of ['super-secret-password', authorization, 'cookie-value-1', 'cookie-value-2', 'secret-nonce-value', 'CSRF_NONCE', 'flexplm.example.com']) {
209
+ expect(recorded).not.toContain(secret);
210
+ }
211
+ });
212
+ });