@azure/monitor-opentelemetry-exporter 1.0.0-beta.22 → 1.0.0-beta.24

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.
package/dist/index.js CHANGED
@@ -60,7 +60,7 @@ const TIME_SINCE_ENQUEUED = "timeSinceEnqueued";
60
60
  * AzureMonitorTraceExporter version.
61
61
  * @internal
62
62
  */
63
- const packageVersion = "1.0.0-beta.22";
63
+ const packageVersion = "1.0.0-beta.24";
64
64
  var DependencyTypes;
65
65
  (function (DependencyTypes) {
66
66
  DependencyTypes["InProc"] = "InProc";
@@ -655,12 +655,19 @@ class FileSystemPersist {
655
655
  }
656
656
  }
657
657
  push(value) {
658
+ var _a;
658
659
  if (this._enabled) {
659
660
  api.diag.debug("Pushing value to persistent storage", value.toString());
660
661
  return this._storeToDisk(JSON.stringify(value));
661
662
  }
663
+ // Only return a false promise if the SDK isn't set to disable offline storage
664
+ if (!((_a = this._options) === null || _a === void 0 ? void 0 : _a.disableOfflineStorage)) {
665
+ return new Promise((resolve) => {
666
+ resolve(false);
667
+ });
668
+ }
662
669
  return new Promise((resolve) => {
663
- resolve(false);
670
+ resolve(true);
664
671
  });
665
672
  }
666
673
  async shift() {
@@ -1814,7 +1821,7 @@ class ApplicationInsightsClient extends coreClient__namespace.ServiceClient {
1814
1821
  const defaults = {
1815
1822
  requestContentType: "application/json; charset=utf-8",
1816
1823
  };
1817
- const packageDetails = `azsdk-js-monitor-opentelemetry-exporter/1.0.0-beta.22`;
1824
+ const packageDetails = `azsdk-js-monitor-opentelemetry-exporter/1.0.0-beta.24`;
1818
1825
  const userAgentPrefix = options.userAgentOptions && options.userAgentOptions.userAgentPrefix
1819
1826
  ? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}`
1820
1827
  : `${packageDetails}`;
@@ -2038,6 +2045,43 @@ class StatsbeatMetrics {
2038
2045
 
2039
2046
  // Copyright (c) Microsoft Corporation.
2040
2047
  // Licensed under the MIT license.
2048
+ /**
2049
+ * Performance Counter OpenTelemetry compliant names.
2050
+ * @internal
2051
+ */
2052
+ var OTelPerformanceCounterNames;
2053
+ (function (OTelPerformanceCounterNames) {
2054
+ OTelPerformanceCounterNames["PRIVATE_BYTES"] = "Private_Bytes";
2055
+ OTelPerformanceCounterNames["AVAILABLE_BYTES"] = "Available_Bytes";
2056
+ OTelPerformanceCounterNames["PROCESSOR_TIME"] = "Processor_Time";
2057
+ OTelPerformanceCounterNames["PROCESS_TIME"] = "Process_Time";
2058
+ OTelPerformanceCounterNames["REQUEST_RATE"] = "Request_Rate";
2059
+ OTelPerformanceCounterNames["REQUEST_DURATION"] = "Request_Execution_Time";
2060
+ })(OTelPerformanceCounterNames || (OTelPerformanceCounterNames = {}));
2061
+ /**
2062
+ * Breeze Performance Counter names.
2063
+ * @internal
2064
+ */
2065
+ var BreezePerformanceCounterNames;
2066
+ (function (BreezePerformanceCounterNames) {
2067
+ BreezePerformanceCounterNames["PRIVATE_BYTES"] = "\\Process(??APP_WIN32_PROC??)\\Private Bytes";
2068
+ BreezePerformanceCounterNames["AVAILABLE_BYTES"] = "\\Memory\\Available Bytes";
2069
+ BreezePerformanceCounterNames["PROCESSOR_TIME"] = "\\Processor(_Total)\\% Processor Time";
2070
+ BreezePerformanceCounterNames["PROCESS_TIME"] = "\\Process(??APP_WIN32_PROC??)\\% Processor Time";
2071
+ BreezePerformanceCounterNames["REQUEST_RATE"] = "\\ASP.NET Applications(??APP_W3SVC_PROC??)\\Requests/Sec";
2072
+ BreezePerformanceCounterNames["REQUEST_DURATION"] = "\\ASP.NET Applications(??APP_W3SVC_PROC??)\\Request Execution Time";
2073
+ })(BreezePerformanceCounterNames || (BreezePerformanceCounterNames = {}));
2074
+
2075
+ // Copyright (c) Microsoft Corporation.
2076
+ // Licensed under the MIT license.
2077
+ const breezePerformanceCountersMap = new Map([
2078
+ [OTelPerformanceCounterNames.PRIVATE_BYTES, BreezePerformanceCounterNames.PRIVATE_BYTES],
2079
+ [OTelPerformanceCounterNames.AVAILABLE_BYTES, BreezePerformanceCounterNames.AVAILABLE_BYTES],
2080
+ [OTelPerformanceCounterNames.PROCESSOR_TIME, BreezePerformanceCounterNames.PROCESSOR_TIME],
2081
+ [OTelPerformanceCounterNames.PROCESS_TIME, BreezePerformanceCounterNames.PROCESS_TIME],
2082
+ [OTelPerformanceCounterNames.REQUEST_RATE, BreezePerformanceCounterNames.REQUEST_RATE],
2083
+ [OTelPerformanceCounterNames.REQUEST_DURATION, BreezePerformanceCounterNames.REQUEST_DURATION],
2084
+ ]);
2041
2085
  function createPropertiesFromMetricAttributes(attributes) {
2042
2086
  const properties = {};
2043
2087
  if (attributes) {
@@ -2072,8 +2116,12 @@ function resourceMetricsToEnvelope(metrics, ikey, isStatsbeat) {
2072
2116
  properties: {},
2073
2117
  };
2074
2118
  baseData.properties = createPropertiesFromMetricAttributes(dataPoint.attributes);
2119
+ let perfCounterName;
2120
+ if (breezePerformanceCountersMap.has(metric.descriptor.name)) {
2121
+ perfCounterName = breezePerformanceCountersMap.get(metric.descriptor.name);
2122
+ }
2075
2123
  const metricDataPoint = {
2076
- name: metric.descriptor.name,
2124
+ name: perfCounterName ? perfCounterName : metric.descriptor.name,
2077
2125
  value: 0,
2078
2126
  dataPointType: "Aggregation",
2079
2127
  };
@@ -2419,6 +2467,7 @@ class LongIntervalStatsbeatMetrics extends StatsbeatMetrics {
2419
2467
  this.connectionString = super.getConnectionString(options.endpointUrl);
2420
2468
  const exporterConfig = {
2421
2469
  connectionString: this.connectionString,
2470
+ disableOfflineStorage: options.disableOfflineStorage,
2422
2471
  };
2423
2472
  this.setFeatures();
2424
2473
  this.longIntervalStatsbeatMeterProvider = new sdkMetrics.MeterProvider();
@@ -2560,16 +2609,19 @@ class BaseSender {
2560
2609
  this.statsbeatFailureCount = 0;
2561
2610
  this.batchSendRetryIntervalMs = DEFAULT_BATCH_SEND_RETRY_INTERVAL_MS;
2562
2611
  this.numConsecutiveRedirects = 0;
2612
+ this.disableOfflineStorage = options.exporterOptions.disableOfflineStorage || false;
2563
2613
  this.persister = new FileSystemPersist(options.instrumentationKey, options.exporterOptions);
2564
2614
  if (options.trackStatsbeat) {
2565
2615
  // Initialize statsbeatMetrics
2566
2616
  this.networkStatsbeatMetrics = new NetworkStatsbeatMetrics({
2567
2617
  instrumentationKey: options.instrumentationKey,
2568
2618
  endpointUrl: options.endpointUrl,
2619
+ disableOfflineStorage: this.disableOfflineStorage,
2569
2620
  });
2570
2621
  this.longIntervalStatsbeatMetrics = getInstance$1({
2571
2622
  instrumentationKey: options.instrumentationKey,
2572
2623
  endpointUrl: options.endpointUrl,
2624
+ disableOfflineStorage: this.disableOfflineStorage,
2573
2625
  });
2574
2626
  }
2575
2627
  this.retryTimer = null;
@@ -3340,7 +3392,8 @@ function createDependencyData(span) {
3340
3392
  function createRequestData(span) {
3341
3393
  const requestData = {
3342
3394
  id: `${span.spanContext().spanId}`,
3343
- success: span.status.code !== api.SpanStatusCode.ERROR,
3395
+ success: span.status.code !== api.SpanStatusCode.ERROR &&
3396
+ (Number(span.attributes[semanticConventions.SEMATTRS_HTTP_STATUS_CODE]) || 0) < 400,
3344
3397
  responseCode: "0",
3345
3398
  duration: msToTimeSpan(core.hrTimeToMilliseconds(span.duration)),
3346
3399
  version: 2,
@@ -3440,40 +3493,46 @@ function spanEventsToEnvelopes(span, ikey) {
3440
3493
  tags[KnownContextTagKeys.AiOperationParentId] = spanId;
3441
3494
  }
3442
3495
  // Only generate exception telemetry for incoming requests
3443
- if (event.name === "exception" && span.kind === api.SpanKind.SERVER) {
3444
- name = "Microsoft.ApplicationInsights.Exception";
3445
- baseType = "ExceptionData";
3446
- let typeName = "";
3447
- let message = "Exception";
3448
- let stack = "";
3449
- let hasFullStack = false;
3450
- if (event.attributes) {
3451
- typeName = String(event.attributes[semanticConventions.SEMATTRS_EXCEPTION_TYPE]);
3452
- stack = String(event.attributes[semanticConventions.SEMATTRS_EXCEPTION_STACKTRACE]);
3453
- if (stack) {
3454
- hasFullStack = true;
3455
- }
3456
- const exceptionMsg = event.attributes[semanticConventions.SEMATTRS_EXCEPTION_MESSAGE];
3457
- if (exceptionMsg) {
3458
- message = String(exceptionMsg);
3459
- }
3460
- const escaped = event.attributes[semanticConventions.SEMATTRS_EXCEPTION_ESCAPED];
3461
- if (escaped !== undefined) {
3462
- properties[semanticConventions.SEMATTRS_EXCEPTION_ESCAPED] = String(escaped);
3496
+ if (event.name === "exception") {
3497
+ if (span.kind === api.SpanKind.SERVER) {
3498
+ name = "Microsoft.ApplicationInsights.Exception";
3499
+ baseType = "ExceptionData";
3500
+ let typeName = "";
3501
+ let message = "Exception";
3502
+ let stack = "";
3503
+ let hasFullStack = false;
3504
+ if (event.attributes) {
3505
+ typeName = String(event.attributes[semanticConventions.SEMATTRS_EXCEPTION_TYPE]);
3506
+ stack = String(event.attributes[semanticConventions.SEMATTRS_EXCEPTION_STACKTRACE]);
3507
+ if (stack) {
3508
+ hasFullStack = true;
3509
+ }
3510
+ const exceptionMsg = event.attributes[semanticConventions.SEMATTRS_EXCEPTION_MESSAGE];
3511
+ if (exceptionMsg) {
3512
+ message = String(exceptionMsg);
3513
+ }
3514
+ const escaped = event.attributes[semanticConventions.SEMATTRS_EXCEPTION_ESCAPED];
3515
+ if (escaped !== undefined) {
3516
+ properties[semanticConventions.SEMATTRS_EXCEPTION_ESCAPED] = String(escaped);
3517
+ }
3463
3518
  }
3519
+ const exceptionDetails = {
3520
+ typeName: typeName,
3521
+ message: message,
3522
+ stack: stack,
3523
+ hasFullStack: hasFullStack,
3524
+ };
3525
+ const exceptionData = {
3526
+ exceptions: [exceptionDetails],
3527
+ version: 2,
3528
+ properties: properties,
3529
+ };
3530
+ baseData = exceptionData;
3531
+ }
3532
+ else {
3533
+ // Drop non-server exception span events
3534
+ return;
3464
3535
  }
3465
- const exceptionDetails = {
3466
- typeName: typeName,
3467
- message: message,
3468
- stack: stack,
3469
- hasFullStack: hasFullStack,
3470
- };
3471
- const exceptionData = {
3472
- exceptions: [exceptionDetails],
3473
- version: 2,
3474
- properties: properties,
3475
- };
3476
- baseData = exceptionData;
3477
3536
  }
3478
3537
  else {
3479
3538
  name = "Microsoft.ApplicationInsights.Message";
@@ -3652,7 +3711,7 @@ function logToEnvelope(log, ikey) {
3652
3711
  const sampleRate = 100;
3653
3712
  const instrumentationKey = ikey;
3654
3713
  const tags = createTagsFromLog(log);
3655
- const [properties, measurements] = createPropertiesFromLog(log);
3714
+ let [properties, measurements] = createPropertiesFromLog(log);
3656
3715
  let name;
3657
3716
  let baseType;
3658
3717
  let baseData;
@@ -3693,6 +3752,7 @@ function logToEnvelope(log, ikey) {
3693
3752
  baseType = String(log.attributes[ApplicationInsightsBaseType]);
3694
3753
  name = getLegacyApplicationInsightsName(log);
3695
3754
  baseData = getLegacyApplicationInsightsBaseData(log);
3755
+ measurements = getLegacyApplicationInsightsMeasurements(log);
3696
3756
  if (!baseData) {
3697
3757
  // Failed to parse log
3698
3758
  return;
@@ -3781,6 +3841,14 @@ function getLegacyApplicationInsightsName(log) {
3781
3841
  }
3782
3842
  return name;
3783
3843
  }
3844
+ function getLegacyApplicationInsightsMeasurements(log) {
3845
+ var _a;
3846
+ let measurements = {};
3847
+ if ((_a = log.body) === null || _a === void 0 ? void 0 : _a.measurements) {
3848
+ measurements = Object.assign({}, log.body.measurements);
3849
+ }
3850
+ return measurements;
3851
+ }
3784
3852
  function getLegacyApplicationInsightsBaseData(log) {
3785
3853
  let baseData = {
3786
3854
  version: 2,
@@ -23,6 +23,7 @@ class LongIntervalStatsbeatMetrics extends StatsbeatMetrics {
23
23
  this.connectionString = super.getConnectionString(options.endpointUrl);
24
24
  const exporterConfig = {
25
25
  connectionString: this.connectionString,
26
+ disableOfflineStorage: options.disableOfflineStorage,
26
27
  };
27
28
  this.setFeatures();
28
29
  this.longIntervalStatsbeatMeterProvider = new MeterProvider();
@@ -1 +1 @@
1
- {"version":3,"file":"longIntervalStatsbeatMetrics.js","sourceRoot":"","sources":["../../../../src/export/statsbeat/longI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AAU,mCACL,IAAI,CAAC,gBAAgB,KACxB,OAAO,EAAE,IAAI,CAAC,OAAO,EACrB,IAAI,EAAE,oBAAoB,CAAC,OAAO,GACnC,CAAC;YACF,gBAAgB,CAAC,OAAO,CAAC,IAAI,CAAC,qBAAqB,EAAE,CAAC,oBAAO,UAAU,EAAG,CAAC;QAC7E,CAAC;IACH,CAAC;IAEO,WAAW;QACjB,IAAI,iBAAiB,GAAG,OAAO,CAAC,GAAG,CAAC,gCAAgC,CAAC;QACrE,IAAI,iBAAiB,EAAE,CAAC;YACtB,IAAI,CAAC;gBACH,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,iBAAiB,CAAC,CAAC,OAAO,CAAC;gBACrD,IAAI,CAAC,eAAe,GAAG,IAAI,CAAC,KAAK,CAAC,iBAAiB,CAAC,CAAC,eAAe,CAAC;YACvE,CAAC;YAAC,OAAO,KAAU,EAAE,CAAC;gBACpB,IAAI,CAAC,KAAK,CACR,2EAA2E,KAAK,GAAG,CACpF,CAAC;YACJ,CAAC;QACH,CAAC;IACH,CAAC;IAEO,cAAc,CAAC,gBAAkC;QACvD,MAAM,UAAU,mCAAQ,IAAI,CAAC,gBAAgB,GAAK,IAAI,CAAC,gBAAgB,CAAE,CAAC;QAC1E,gBAAgB,CAAC,OAAO,CAAC,CAAC,EAAE,UAAU,CAAC,CAAC;IAC1C,CAAC;IAEM,QAAQ;QACb,OAAO,IAAI,CAAC,kCAAkC,CAAC,QAAQ,EAAE,CAAC;IAC5D,CAAC;CACF;AAED;;;GAGG;AACH,MAAM,UAAU,WAAW,CAAC,OAAyB;IACnD,IAAI,CAAC,QAAQ,EAAE,CAAC;QACd,QAAQ,GAAG,IAAI,4BAA4B,CAAC,OAAO,CAAC,CAAC;IACvD,CAAC;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n diag,\n BatchObservableResult,\n ObservableGauge,\n ObservableResult,\n Meter,\n} from \"@opentelemetry/api\";\nimport { ExportResult, ExportResultCode } from \"@opentelemetry/core\";\nimport {\n MeterProvider,\n PeriodicExportingMetricReader,\n PeriodicExportingMetricReaderOptions,\n} from \"@opentelemetry/sdk-metrics\";\nimport { AzureMonitorExporterOptions } from \"../../index\";\nimport * as ai from \"../../utils/constants/applicationinsights\";\nimport { StatsbeatMetrics } from \"./statsbeatMetrics\";\nimport {\n StatsbeatCounter,\n STATSBEAT_LANGUAGE,\n CommonStatsbeatProperties,\n AttachStatsbeatProperties,\n StatsbeatFeatureType,\n StatsbeatOptions,\n} from \"./types\";\nimport { AzureMonitorStatsbeatExporter } from \"./statsbeatExporter\";\n\nlet instance: LongIntervalStatsbeatMetrics | null = null;\n\n/**\n * Long Interval Statsbeat Metrics\n * @internal\n */\nclass LongIntervalStatsbeatMetrics extends StatsbeatMetrics {\n private statsCollectionLongInterval: number = 86400000; // 1 day\n // Custom dimensions\n private cikey: string;\n private runtimeVersion: string;\n private language: string;\n private version: string;\n private attach: string = \"Manual\";\n\n private commonProperties: CommonStatsbeatProperties;\n private attachProperties: AttachStatsbeatProperties;\n\n private feature: number = 0;\n private instrumentation: number = 0;\n\n private longIntervalStatsbeatMeterProvider: MeterProvider;\n private longIntervalAzureExporter: AzureMonitorStatsbeatExporter;\n private longIntervalMetricReader: PeriodicExportingMetricReader;\n private longIntervalStatsbeatMeter: Meter;\n\n // Network Attributes\n private connectionString: string;\n\n // Observable Gauges\n private featureStatsbeatGauge: ObservableGauge;\n private attachStatsbeatGauge: ObservableGauge;\n\n public isInitialized: boolean = false;\n\n constructor(options: StatsbeatOptions) {\n super();\n this.connectionString = super.getConnectionString(options.endpointUrl);\n const exporterConfig: AzureMonitorExporterOptions = {\n connectionString: this.connectionString,\n };\n\n this.setFeatures();\n\n this.longIntervalStatsbeatMeterProvider = new MeterProvider();\n this.longIntervalAzureExporter = new AzureMonitorStatsbeatExporter(exporterConfig);\n\n // Export Long Interval Statsbeats every day\n const longIntervalMetricReaderOptions: PeriodicExportingMetricReaderOptions = {\n exporter: this.longIntervalAzureExporter,\n exportIntervalMillis:\n Number(process.env.LONG_INTERVAL_EXPORT_MILLIS) || this.statsCollectionLongInterval, // 1 day\n };\n\n this.longIntervalMetricReader = new PeriodicExportingMetricReader(\n longIntervalMetricReaderOptions,\n );\n this.longIntervalStatsbeatMeterProvider.addMetricReader(this.longIntervalMetricReader);\n this.longIntervalStatsbeatMeter = this.longIntervalStatsbeatMeterProvider.getMeter(\n \"Azure Monitor Long Interval Statsbeat\",\n );\n\n // Assign Common Properties\n this.runtimeVersion = process.version;\n this.language = STATSBEAT_LANGUAGE;\n this.version = ai.packageVersion;\n this.cikey = options.instrumentationKey;\n\n this.featureStatsbeatGauge = this.longIntervalStatsbeatMeter.createObservableGauge(\n StatsbeatCounter.FEATURE,\n );\n this.attachStatsbeatGauge = this.longIntervalStatsbeatMeter.createObservableGauge(\n StatsbeatCounter.ATTACH,\n );\n\n this.commonProperties = {\n os: this.os,\n rp: this.resourceProvider,\n cikey: this.cikey,\n runtimeVersion: this.runtimeVersion,\n language: this.language,\n version: this.version,\n attach: this.attach,\n };\n\n this.attachProperties = {\n rpId: this.resourceIdentifier,\n };\n\n this.isInitialized = true;\n this.initialize();\n }\n\n private async initialize() {\n try {\n await this.getResourceProvider();\n\n // Add long interval observable callbacks\n this.attachStatsbeatGauge.addCallback(this.attachCallback.bind(this));\n this.longIntervalStatsbeatMeter.addBatchObservableCallback(\n this.getEnvironmentStatus.bind(this),\n [this.featureStatsbeatGauge],\n );\n\n // Export Feature/Attach Statsbeat once upon app initialization\n this.longIntervalAzureExporter.export(\n (await this.longIntervalMetricReader.collect()).resourceMetrics,\n (result: ExportResult) => {\n if (result.code !== ExportResultCode.SUCCESS) {\n diag.error(`LongIntervalStatsbeat: metrics export failed (error ${result.error})`);\n }\n },\n );\n } catch (error) {\n diag.debug(\"Call to get the resource provider failed.\");\n }\n }\n\n private getEnvironmentStatus(observableResult: BatchObservableResult) {\n this.setFeatures();\n let attributes;\n if (this.instrumentation) {\n attributes = {\n ...this.commonProperties,\n feature: this.instrumentation,\n type: StatsbeatFeatureType.INSTRUMENTATION,\n };\n observableResult.observe(this.featureStatsbeatGauge, 1, { ...attributes });\n }\n\n if (this.feature) {\n attributes = {\n ...this.commonProperties,\n feature: this.feature,\n type: StatsbeatFeatureType.FEATURE,\n };\n observableResult.observe(this.featureStatsbeatGauge, 1, { ...attributes });\n }\n }\n\n private setFeatures() {\n let statsbeatFeatures = process.env.AZURE_MONITOR_STATSBEAT_FEATURES;\n if (statsbeatFeatures) {\n try {\n this.feature = JSON.parse(statsbeatFeatures).feature;\n this.instrumentation = JSON.parse(statsbeatFeatures).instrumentation;\n } catch (error: any) {\n diag.error(\n `LongIntervalStatsbeat: Failed to parse features/instrumentations (error ${error})`,\n );\n }\n }\n }\n\n private attachCallback(observableResult: ObservableResult) {\n const attributes = { ...this.commonProperties, ...this.attachProperties };\n observableResult.observe(1, attributes);\n }\n\n public shutdown(): Promise<void> {\n return this.longIntervalStatsbeatMeterProvider.shutdown();\n }\n}\n\n/**\n * Singleton LongIntervalStatsbeatMetrics instance.\n * @internal\n */\nexport function getInstance(options: StatsbeatOptions): LongIntervalStatsbeatMetrics {\n if (!instance) {\n instance = new LongIntervalStatsbeatMetrics(options);\n }\n return instance;\n}\n"]}
1
+ {"version":3,"file":"longIntervalStatsbeatMetrics.js","sourceRoot":"","sources":["../../../../src/export/statsbeat/longIntervalStatsbeatMetrics.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EACL,IAAI,GAKL,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAgB,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACrE,OAAO,EACL,aAAa,EACb,6BAA6B,GAE9B,MAAM,4BAA4B,CAAC;AAEpC,OAAO,KAAK,EAAE,MAAM,2CAA2C,CAAC;AAChE,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CA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,CAAC,gCAAgC,CAAC;QACrE,IAAI,iBAAiB,EAAE,CAAC;YACtB,IAAI,CAAC;gBACH,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,iBAAiB,CAAC,CAAC,OAAO,CAAC;gBACrD,IAAI,CAAC,eAAe,GAAG,IAAI,CAAC,KAAK,CAAC,iBAAiB,CAAC,CAAC,eAAe,CAAC;YACvE,CAAC;YAAC,OAAO,KAAU,EAAE,CAAC;gBACpB,IAAI,CAAC,KAAK,CACR,2EAA2E,KAAK,GAAG,CACpF,CAAC;YACJ,CAAC;QACH,CAAC;IACH,CAAC;IAEO,cAAc,CAAC,gBAAkC;QACvD,MAAM,UAAU,mCAAQ,IAAI,CAAC,gBAAgB,GAAK,IAAI,CAAC,gBAAgB,CAAE,CAAC;QAC1E,gBAAgB,CAAC,OAAO,CAAC,CAAC,EAAE,UAAU,CAAC,CAAC;IAC1C,CAAC;IAEM,QAAQ;QACb,OAAO,IAAI,CAAC,kCAAkC,CAAC,QAAQ,EAAE,CAAC;IAC5D,CAAC;CACF;AAED;;;GAGG;AACH,MAAM,UAAU,WAAW,CAAC,OAAyB;IACnD,IAAI,CAAC,QAAQ,EAAE,CAAC;QACd,QAAQ,GAAG,IAAI,4BAA4B,CAAC,OAAO,CAAC,CAAC;IACvD,CAAC;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n diag,\n BatchObservableResult,\n ObservableGauge,\n ObservableResult,\n Meter,\n} from \"@opentelemetry/api\";\nimport { ExportResult, ExportResultCode } from \"@opentelemetry/core\";\nimport {\n MeterProvider,\n PeriodicExportingMetricReader,\n PeriodicExportingMetricReaderOptions,\n} from \"@opentelemetry/sdk-metrics\";\nimport { AzureMonitorExporterOptions } from \"../../index\";\nimport * as ai from \"../../utils/constants/applicationinsights\";\nimport { StatsbeatMetrics } from \"./statsbeatMetrics\";\nimport {\n StatsbeatCounter,\n STATSBEAT_LANGUAGE,\n CommonStatsbeatProperties,\n AttachStatsbeatProperties,\n StatsbeatFeatureType,\n StatsbeatOptions,\n} from \"./types\";\nimport { AzureMonitorStatsbeatExporter } from \"./statsbeatExporter\";\n\nlet instance: LongIntervalStatsbeatMetrics | null = null;\n\n/**\n * Long Interval Statsbeat Metrics\n * @internal\n */\nclass LongIntervalStatsbeatMetrics extends StatsbeatMetrics {\n private statsCollectionLongInterval: number = 86400000; // 1 day\n // Custom dimensions\n private cikey: string;\n private runtimeVersion: string;\n private language: string;\n private version: string;\n private attach: string = \"Manual\";\n\n private commonProperties: CommonStatsbeatProperties;\n private attachProperties: AttachStatsbeatProperties;\n\n private feature: number = 0;\n private instrumentation: number = 0;\n\n private longIntervalStatsbeatMeterProvider: MeterProvider;\n private longIntervalAzureExporter: AzureMonitorStatsbeatExporter;\n private longIntervalMetricReader: PeriodicExportingMetricReader;\n private longIntervalStatsbeatMeter: Meter;\n\n // Network Attributes\n private connectionString: string;\n\n // Observable Gauges\n private featureStatsbeatGauge: ObservableGauge;\n private attachStatsbeatGauge: ObservableGauge;\n\n public isInitialized: boolean = false;\n\n constructor(options: StatsbeatOptions) {\n super();\n this.connectionString = super.getConnectionString(options.endpointUrl);\n const exporterConfig: AzureMonitorExporterOptions = {\n connectionString: this.connectionString,\n disableOfflineStorage: options.disableOfflineStorage,\n };\n\n this.setFeatures();\n\n this.longIntervalStatsbeatMeterProvider = new MeterProvider();\n this.longIntervalAzureExporter = new AzureMonitorStatsbeatExporter(exporterConfig);\n\n // Export Long Interval Statsbeats every day\n const longIntervalMetricReaderOptions: PeriodicExportingMetricReaderOptions = {\n exporter: this.longIntervalAzureExporter,\n exportIntervalMillis:\n Number(process.env.LONG_INTERVAL_EXPORT_MILLIS) || this.statsCollectionLongInterval, // 1 day\n };\n\n this.longIntervalMetricReader = new PeriodicExportingMetricReader(\n longIntervalMetricReaderOptions,\n );\n this.longIntervalStatsbeatMeterProvider.addMetricReader(this.longIntervalMetricReader);\n this.longIntervalStatsbeatMeter = this.longIntervalStatsbeatMeterProvider.getMeter(\n \"Azure Monitor Long Interval Statsbeat\",\n );\n\n // Assign Common Properties\n this.runtimeVersion = process.version;\n this.language = STATSBEAT_LANGUAGE;\n this.version = ai.packageVersion;\n this.cikey = options.instrumentationKey;\n\n this.featureStatsbeatGauge = this.longIntervalStatsbeatMeter.createObservableGauge(\n StatsbeatCounter.FEATURE,\n );\n this.attachStatsbeatGauge = this.longIntervalStatsbeatMeter.createObservableGauge(\n StatsbeatCounter.ATTACH,\n );\n\n this.commonProperties = {\n os: this.os,\n rp: this.resourceProvider,\n cikey: this.cikey,\n runtimeVersion: this.runtimeVersion,\n language: this.language,\n version: this.version,\n attach: this.attach,\n };\n\n this.attachProperties = {\n rpId: this.resourceIdentifier,\n };\n\n this.isInitialized = true;\n this.initialize();\n }\n\n private async initialize() {\n try {\n await this.getResourceProvider();\n\n // Add long interval observable callbacks\n this.attachStatsbeatGauge.addCallback(this.attachCallback.bind(this));\n this.longIntervalStatsbeatMeter.addBatchObservableCallback(\n this.getEnvironmentStatus.bind(this),\n [this.featureStatsbeatGauge],\n );\n\n // Export Feature/Attach Statsbeat once upon app initialization\n this.longIntervalAzureExporter.export(\n (await this.longIntervalMetricReader.collect()).resourceMetrics,\n (result: ExportResult) => {\n if (result.code !== ExportResultCode.SUCCESS) {\n diag.error(`LongIntervalStatsbeat: metrics export failed (error ${result.error})`);\n }\n },\n );\n } catch (error) {\n diag.debug(\"Call to get the resource provider failed.\");\n }\n }\n\n private getEnvironmentStatus(observableResult: BatchObservableResult) {\n this.setFeatures();\n let attributes;\n if (this.instrumentation) {\n attributes = {\n ...this.commonProperties,\n feature: this.instrumentation,\n type: StatsbeatFeatureType.INSTRUMENTATION,\n };\n observableResult.observe(this.featureStatsbeatGauge, 1, { ...attributes });\n }\n\n if (this.feature) {\n attributes = {\n ...this.commonProperties,\n feature: this.feature,\n type: StatsbeatFeatureType.FEATURE,\n };\n observableResult.observe(this.featureStatsbeatGauge, 1, { ...attributes });\n }\n }\n\n private setFeatures() {\n let statsbeatFeatures = process.env.AZURE_MONITOR_STATSBEAT_FEATURES;\n if (statsbeatFeatures) {\n try {\n this.feature = JSON.parse(statsbeatFeatures).feature;\n this.instrumentation = JSON.parse(statsbeatFeatures).instrumentation;\n } catch (error: any) {\n diag.error(\n `LongIntervalStatsbeat: Failed to parse features/instrumentations (error ${error})`,\n );\n }\n }\n }\n\n private attachCallback(observableResult: ObservableResult) {\n const attributes = { ...this.commonProperties, ...this.attachProperties };\n observableResult.observe(1, attributes);\n }\n\n public shutdown(): Promise<void> {\n return this.longIntervalStatsbeatMeterProvider.shutdown();\n }\n}\n\n/**\n * Singleton LongIntervalStatsbeatMetrics instance.\n * @internal\n */\nexport function getInstance(options: StatsbeatOptions): LongIntervalStatsbeatMetrics {\n if (!instance) {\n instance = new LongIntervalStatsbeatMetrics(options);\n }\n return instance;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../src/export/statsbeat/types.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,MAAM,OAAO,gBAAgB;IA6B3B,YAAY,QAAgB,EAAE,IAAY;QACxC,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,iBAAiB,GAAG,CAAC,CAAC;QAC3B,IAAI,CAAC,0BAA0B,GAAG,CAAC,CAAC;QACpC,IAAI,CAAC,uBAAuB,GAAG,EAAE,CAAC;QAClC,IAAI,CAAC,UAAU,GAAG,EAAE,CAAC;QACrB,IAAI,CAAC,cAAc,GAAG,EAAE,CAAC;QACzB,IAAI,CAAC,aAAa,GAAG,EAAE,CAAC;QACxB,IAAI,CAAC,4BAA4B,GAAG,CAAC,CAAC;QACtC,IAAI,CAAC,gCAAgC,GAAG,CAAC,CAAC;QAC1C,IAAI,CAAC,QAAQ,GAAG,CAAC,IAAI,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B,KAApB,oBAAoB,QAG/B","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nexport class NetworkStatsbeat {\n public time: number | undefined;\n\n public lastTime: number;\n\n public endpoint: string;\n\n public host: string;\n\n public totalRequestCount: number;\n\n public lastRequestCount: number;\n\n public totalSuccesfulRequestCount: number;\n\n public totalFailedRequestCount: { statusCode: number; count: number }[];\n\n public retryCount: { statusCode: number; count: number }[];\n\n public exceptionCount: { exceptionType: string; count: number }[];\n\n public throttleCount: { statusCode: number; count: number }[];\n\n public intervalRequestExecutionTime: number;\n\n public lastIntervalRequestExecutionTime: number;\n\n public averageRequestExecutionTime: number;\n\n constructor(endpoint: string, host: string) {\n this.endpoint = endpoint;\n this.host = host;\n this.totalRequestCount = 0;\n this.totalSuccesfulRequestCount = 0;\n this.totalFailedRequestCount = [];\n this.retryCount = [];\n this.exceptionCount = [];\n this.throttleCount = [];\n this.intervalRequestExecutionTime = 0;\n this.lastIntervalRequestExecutionTime = 0;\n this.lastTime = +new Date();\n this.lastRequestCount = 0;\n this.averageRequestExecutionTime = 0;\n }\n}\n\nexport const STATSBEAT_LANGUAGE = \"node\";\n\nexport const MAX_STATSBEAT_FAILURES = 3;\n\nexport const StatsbeatResourceProvider = {\n appsvc: \"appsvc\",\n aks: \"aks\",\n functions: \"functions\",\n vm: \"vm\",\n unknown: \"unknown\",\n};\n\nexport enum StatsbeatCounter {\n SUCCESS_COUNT = \"Request_Success_Count\",\n FAILURE_COUNT = \"Request_Failure_Count\",\n RETRY_COUNT = \"Retry_Count\",\n THROTTLE_COUNT = \"Throttle_Count\",\n EXCEPTION_COUNT = \"Exception_Count\",\n AVERAGE_DURATION = \"Request_Duration\",\n ATTACH = \"Attach\",\n FEATURE = \"Feature\",\n}\n\nexport const AIMS_URI = \"http://169.254.169.254/metadata/instance/compute\";\nexport const AIMS_API_VERSION = \"api-version=2017-12-01\";\nexport const AIMS_FORMAT = \"format=json\";\nexport const NON_EU_CONNECTION_STRING =\n \"InstrumentationKey=c4a29126-a7cb-47e5-b348-11414998b11e;IngestionEndpoint=https://westus-0.in.applicationinsights.azure.com\";\nexport const EU_CONNECTION_STRING =\n \"InstrumentationKey=7dc56bab-3c0c-4e9f-9ebb-d1acadee8d0f;IngestionEndpoint=https://westeurope-5.in.applicationinsights.azure.com\";\nexport const EU_ENDPOINTS = [\n \"westeurope\",\n \"northeurope\",\n \"francecentral\",\n \"francesouth\",\n \"germanywestcentral\",\n \"norwayeast\",\n \"norwaywest\",\n \"swedencentral\",\n \"switzerlandnorth\",\n \"switzerlandwest\",\n \"uksouth\",\n \"ukwest\",\n];\n\nexport interface CommonStatsbeatProperties {\n os: string;\n rp: string;\n cikey: string;\n runtimeVersion: string;\n language: string;\n version: string;\n attach: string;\n}\n\nexport interface AttachStatsbeatProperties {\n rpId: string;\n}\n\nexport interface NetworkStatsbeatProperties {\n endpoint: string;\n host: string;\n}\n\nexport interface StatsbeatOptions {\n instrumentationKey: string;\n endpointUrl: string;\n networkCollectionInterval?: number;\n longCollectionInterval?: number;\n}\n\nexport interface VirtualMachineInfo {\n isVM?: boolean;\n id?: string;\n subscriptionId?: string;\n osType?: string;\n}\n\nexport enum StatsbeatFeatureType {\n FEATURE = 0,\n INSTRUMENTATION = 1,\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../src/export/statsbeat/types.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,MAAM,OAAO,gBAAgB;IA6B3B,YAAY,QAAgB,EAAE,IAAY;QACxC,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,iBAAiB,GAAG,CAAC,CAAC;QAC3B,IAAI,CAAC,0BAA0B,GAAG,CAAC,CAAC;QACpC,IAAI,CAAC,uBAAuB,GAAG,EAAE,CAAC;QAClC,IAAI,CAAC,UAAU,GAAG,EAAE,CAAC;QACrB,IAAI,C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;IACZ,YAAY;IACZ,eAAe;IACf,kBAAkB;IAClB,iBAAiB;IACjB,SAAS;IACT,QAAQ;CACT,CAAC;AAoCF,MAAM,CAAN,IAAY,oBAGX;AAHD,WAAY,oBAAoB;IAC9B,qEAAW,CAAA;IACX,qFAAmB,CAAA;AACrB,CAAC,EAHW,oBAAoB,KAApB,oBAAoB,QAG/B","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nexport class NetworkStatsbeat {\n public time: number | undefined;\n\n public lastTime: number;\n\n public endpoint: string;\n\n public host: string;\n\n public totalRequestCount: number;\n\n public lastRequestCount: number;\n\n public totalSuccesfulRequestCount: number;\n\n public totalFailedRequestCount: { statusCode: number; count: number }[];\n\n public retryCount: { statusCode: number; count: number }[];\n\n public exceptionCount: { exceptionType: string; count: number }[];\n\n public throttleCount: { statusCode: number; count: number }[];\n\n public intervalRequestExecutionTime: number;\n\n public lastIntervalRequestExecutionTime: number;\n\n public averageRequestExecutionTime: number;\n\n constructor(endpoint: string, host: string) {\n this.endpoint = endpoint;\n this.host = host;\n this.totalRequestCount = 0;\n this.totalSuccesfulRequestCount = 0;\n this.totalFailedRequestCount = [];\n this.retryCount = [];\n this.exceptionCount = [];\n this.throttleCount = [];\n this.intervalRequestExecutionTime = 0;\n this.lastIntervalRequestExecutionTime = 0;\n this.lastTime = +new Date();\n this.lastRequestCount = 0;\n this.averageRequestExecutionTime = 0;\n }\n}\n\nexport const STATSBEAT_LANGUAGE = \"node\";\n\nexport const MAX_STATSBEAT_FAILURES = 3;\n\nexport const StatsbeatResourceProvider = {\n appsvc: \"appsvc\",\n aks: \"aks\",\n functions: \"functions\",\n vm: \"vm\",\n unknown: \"unknown\",\n};\n\nexport enum StatsbeatCounter {\n SUCCESS_COUNT = \"Request_Success_Count\",\n FAILURE_COUNT = \"Request_Failure_Count\",\n RETRY_COUNT = \"Retry_Count\",\n THROTTLE_COUNT = \"Throttle_Count\",\n EXCEPTION_COUNT = \"Exception_Count\",\n AVERAGE_DURATION = \"Request_Duration\",\n ATTACH = \"Attach\",\n FEATURE = \"Feature\",\n}\n\nexport const AIMS_URI = \"http://169.254.169.254/metadata/instance/compute\";\nexport const AIMS_API_VERSION = \"api-version=2017-12-01\";\nexport const AIMS_FORMAT = \"format=json\";\nexport const NON_EU_CONNECTION_STRING =\n \"InstrumentationKey=c4a29126-a7cb-47e5-b348-11414998b11e;IngestionEndpoint=https://westus-0.in.applicationinsights.azure.com\";\nexport const EU_CONNECTION_STRING =\n \"InstrumentationKey=7dc56bab-3c0c-4e9f-9ebb-d1acadee8d0f;IngestionEndpoint=https://westeurope-5.in.applicationinsights.azure.com\";\nexport const EU_ENDPOINTS = [\n \"westeurope\",\n \"northeurope\",\n \"francecentral\",\n \"francesouth\",\n \"germanywestcentral\",\n \"norwayeast\",\n \"norwaywest\",\n \"swedencentral\",\n \"switzerlandnorth\",\n \"switzerlandwest\",\n \"uksouth\",\n \"ukwest\",\n];\n\nexport interface CommonStatsbeatProperties {\n os: string;\n rp: string;\n cikey: string;\n runtimeVersion: string;\n language: string;\n version: string;\n attach: string;\n}\n\nexport interface AttachStatsbeatProperties {\n rpId: string;\n}\n\nexport interface NetworkStatsbeatProperties {\n endpoint: string;\n host: string;\n}\n\nexport interface StatsbeatOptions {\n instrumentationKey: string;\n endpointUrl: string;\n networkCollectionInterval?: number;\n longCollectionInterval?: number;\n disableOfflineStorage?: boolean;\n}\n\nexport interface VirtualMachineInfo {\n isVM?: boolean;\n id?: string;\n subscriptionId?: string;\n osType?: string;\n}\n\nexport enum StatsbeatFeatureType {\n FEATURE = 0,\n INSTRUMENTATION = 1,\n}\n"]}
@@ -22,7 +22,7 @@ export class ApplicationInsightsClient extends coreClient.ServiceClient {
22
22
  const defaults = {
23
23
  requestContentType: "application/json; charset=utf-8",
24
24
  };
25
- const packageDetails = `azsdk-js-monitor-opentelemetry-exporter/1.0.0-beta.22`;
25
+ const packageDetails = `azsdk-js-monitor-opentelemetry-exporter/1.0.0-beta.24`;
26
26
  const userAgentPrefix = options.userAgentOptions && options.userAgentOptions.userAgentPrefix
27
27
  ? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}`
28
28
  : `${packageDetails}`;
@@ -1 +1 @@
1
- {"version":3,"file":"applicationInsightsClient.js","sourceRoot":"","sources":["../../../src/generated/applicationInsightsClient.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,UAAU,MAAM,oBAAoB,CAAC;AACjD,OAAO,KAAK,UAAU,MAAM,qBAAqB,CAAC;AAClD,OAAO,KAAK,OAAO,MAAM,kBAAkB,CAAC;AAQ5C,MAAM,OAAO,yBAA0B,SAAQ,UAAU,CAAC,aAAa;IAGrE;;;OAGG;IACH,YAAY,OAAiD;;QAC3D,0CAA0C;QAC1C,IAAI,CAAC,OAAO,EAAE,CAAC;YACb,OAAO,GAAG,EAAE,CAAC;QACf,CAAC;QACD,MAAM,QAAQ,GAA4C;YACxD,kBAAkB,EAAE,iCAAiC;SACtD,CAAC;QAEF,MAAM,cAAc,GAAG,uDAAuD,CAAC;QAC/E,MAAM,eAAe,GACnB,OAAO,CAAC,gBAAgB,IAAI,OAAO,CAAC,gBAAgB,CAAC,eAAe;YAClE,CAAC,CAAC,GAAG,OAAO,CAAC,gBAAgB,CAAC,eAAe,IAAI,cAAc,EAAE;YACjE,CAAC,CAAC,GAAG,cAAc,EAAE,CAAC;QAE1B,MAAM,mBAAmB,iDACpB,QAAQ,GACR,OAAO,KACV,gBAAgB,EAAE;gBAChB,eAAe;aAChB,EACD,QAAQ,EAAE,MAAA,MAAA,OAAO,CAAC,QAAQ,mCAAI,OAAO,CAAC,OAAO,mCAAI,aAAa,GAC/D,CAAC;QACF,KAAK,CAAC,mBAAmB,CAAC,CAAC;QAE3B,0CAA0C;QAC1C,IAAI,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,IAAI,sCAAsC,CAAC;IACrE,CAAC;IAED;;;;OAIG;IACH,KAAK,CACH,IAAqB,EACrB,OAA6B;QAE7B,OAAO,IAAI,CAAC,oBAAoB,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,EAAE,kBAAkB,CAAC,CAAC;IAC1E,CAAC;CACF;AACD,2BAA2B;AAC3B,MAAM,UAAU,GAAG,UAAU,CAAC,gBAAgB,CAAC,OAAO,EAAE,WAAW,CAAC,KAAK,CAAC,CAAC;AAE3E,MAAM,kBAAkB,GAA6B;IACnD,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE,MAAM;IAClB,SAAS,EAAE;QACT,GAAG,EAAE;YACH,UAAU,EAAE,OAAO,CAAC,aAAa;SAClC;QACD,GAAG,EAAE;YACH,UAAU,EAAE,OAAO,CAAC,aAAa;SAClC;QACD,GAAG,EAAE;YACH,UAAU,EAAE,OAAO,CAAC,aAAa;YACjC,OAAO,EAAE,IAAI;SACd;QACD,GAAG,EAAE;YACH,UAAU,EAAE,OAAO,CAAC,aAAa;YACjC,OAAO,EAAE,IAAI;SACd;QACD,GAAG,EAAE;YACH,UAAU,EAAE,OAAO,CAAC,aAAa;YACjC,OAAO,EAAE,IAAI;SACd;QACD,GAAG,EAAE;YACH,UAAU,EAAE,OAAO,CAAC,aAAa;YACjC,OAAO,EAAE,IAAI;SACd;QACD,GAAG,EAAE;YACH,UAAU,EAAE,OAAO,CAAC,aAAa;YACjC,OAAO,EAAE,IAAI;SACd;KACF;IACD,WAAW,EAAE,UAAU,CAAC,IAAI;IAC5B,aAAa,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC;IAChC,gBAAgB,EAAE,CAAC,UAAU,CAAC,WAAW,EAAE,UAAU,CAAC,MAAM,CAAC;IAC7D,SAAS,EAAE,MAAM;IACjB,UAAU;CACX,CAAC","sourcesContent":["/*\n * Copyright (c) Microsoft Corporation.\n * Licensed under the MIT License.\n *\n * Code generated by Microsoft (R) AutoRest Code Generator.\n * Changes may cause incorrect behavior and will be lost if the code is regenerated.\n */\n\nimport * as coreClient from \"@azure/core-client\";\nimport * as Parameters from \"./models/parameters\";\nimport * as Mappers from \"./models/mappers\";\nimport {\n ApplicationInsightsClientOptionalParams,\n TelemetryItem,\n TrackOptionalParams,\n TrackOperationResponse,\n} from \"./models\";\n\nexport class ApplicationInsightsClient extends coreClient.ServiceClient {\n host: string;\n\n /**\n * Initializes a new instance of the ApplicationInsightsClient class.\n * @param options The parameter options\n */\n constructor(options?: ApplicationInsightsClientOptionalParams) {\n // Initializing default values for options\n if (!options) {\n options = {};\n }\n const defaults: ApplicationInsightsClientOptionalParams = {\n requestContentType: \"application/json; charset=utf-8\",\n };\n\n const packageDetails = `azsdk-js-monitor-opentelemetry-exporter/1.0.0-beta.22`;\n const userAgentPrefix =\n options.userAgentOptions && options.userAgentOptions.userAgentPrefix\n ? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}`\n : `${packageDetails}`;\n\n const optionsWithDefaults = {\n ...defaults,\n ...options,\n userAgentOptions: {\n userAgentPrefix,\n },\n endpoint: options.endpoint ?? options.baseUri ?? \"{Host}/v2.1\",\n };\n super(optionsWithDefaults);\n\n // Assigning values to Constant parameters\n this.host = options.host || \"https://dc.services.visualstudio.com\";\n }\n\n /**\n * This operation sends a sequence of telemetry events that will be monitored by Azure Monitor.\n * @param body The list of telemetry events to track.\n * @param options The options parameters.\n */\n track(\n body: TelemetryItem[],\n options?: TrackOptionalParams,\n ): Promise<TrackOperationResponse> {\n return this.sendOperationRequest({ body, options }, trackOperationSpec);\n }\n}\n// Operation Specifications\nconst serializer = coreClient.createSerializer(Mappers, /* isXml */ false);\n\nconst trackOperationSpec: coreClient.OperationSpec = {\n path: \"/track\",\n httpMethod: \"POST\",\n responses: {\n 200: {\n bodyMapper: Mappers.TrackResponse,\n },\n 206: {\n bodyMapper: Mappers.TrackResponse,\n },\n 400: {\n bodyMapper: Mappers.TrackResponse,\n isError: true,\n },\n 402: {\n bodyMapper: Mappers.TrackResponse,\n isError: true,\n },\n 429: {\n bodyMapper: Mappers.TrackResponse,\n isError: true,\n },\n 500: {\n bodyMapper: Mappers.TrackResponse,\n isError: true,\n },\n 503: {\n bodyMapper: Mappers.TrackResponse,\n isError: true,\n },\n },\n requestBody: Parameters.body,\n urlParameters: [Parameters.host],\n headerParameters: [Parameters.contentType, Parameters.accept],\n mediaType: \"json\",\n serializer,\n};\n"]}
1
+ {"version":3,"file":"applicationInsightsClient.js","sourceRoot":"","sources":["../../../src/generated/applicationInsightsClient.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,UAAU,MAAM,oBAAoB,CAAC;AACjD,OAAO,KAAK,UAAU,MAAM,qBAAqB,CAAC;AAClD,OAAO,KAAK,OAAO,MAAM,kBAAkB,CAAC;AAQ5C,MAAM,OAAO,yBAA0B,SAAQ,UAAU,CAAC,aAAa;IAGrE;;;OAGG;IACH,YAAY,OAAiD;;QAC3D,0CAA0C;QAC1C,IAAI,CAAC,OAAO,EAAE,CAAC;YACb,OAAO,GAAG,EAAE,CAAC;QACf,CAAC;QACD,MAAM,QAAQ,GAA4C;YACxD,kBAAkB,EAAE,iCAAiC;SACtD,CAAC;QAEF,MAAM,cAAc,GAAG,uDAAuD,CAAC;QAC/E,MAAM,eAAe,GACnB,OAAO,CAAC,gBAAgB,IAAI,OAAO,CAAC,gBAAgB,CAAC,eAAe;YAClE,CAAC,CAAC,GAAG,OAAO,CAAC,gBAAgB,CAAC,eAAe,IAAI,cAAc,EAAE;YACjE,CAAC,CAAC,GAAG,cAAc,EAAE,CAAC;QAE1B,MAAM,mBAAmB,iDACpB,QAAQ,GACR,OAAO,KACV,gBAAgB,EAAE;gBAChB,eAAe;aAChB,EACD,QAAQ,EAAE,MAAA,MAAA,OAAO,CAAC,QAAQ,mCAAI,OAAO,CAAC,OAAO,mCAAI,aAAa,GAC/D,CAAC;QACF,KAAK,CAAC,mBAAmB,CAAC,CAAC;QAE3B,0CAA0C;QAC1C,IAAI,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,IAAI,sCAAsC,CAAC;IACrE,CAAC;IAED;;;;OAIG;IACH,KAAK,CACH,IAAqB,EACrB,OAA6B;QAE7B,OAAO,IAAI,CAAC,oBAAoB,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,EAAE,kBAAkB,CAAC,CAAC;IAC1E,CAAC;CACF;AACD,2BAA2B;AAC3B,MAAM,UAAU,GAAG,UAAU,CAAC,gBAAgB,CAAC,OAAO,EAAE,WAAW,CAAC,KAAK,CAAC,CAAC;AAE3E,MAAM,kBAAkB,GAA6B;IACnD,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE,MAAM;IAClB,SAAS,EAAE;QACT,GAAG,EAAE;YACH,UAAU,EAAE,OAAO,CAAC,aAAa;SAClC;QACD,GAAG,EAAE;YACH,UAAU,EAAE,OAAO,CAAC,aAAa;SAClC;QACD,GAAG,EAAE;YACH,UAAU,EAAE,OAAO,CAAC,aAAa;YACjC,OAAO,EAAE,IAAI;SACd;QACD,GAAG,EAAE;YACH,UAAU,EAAE,OAAO,CAAC,aAAa;YACjC,OAAO,EAAE,IAAI;SACd;QACD,GAAG,EAAE;YACH,UAAU,EAAE,OAAO,CAAC,aAAa;YACjC,OAAO,EAAE,IAAI;SACd;QACD,GAAG,EAAE;YACH,UAAU,EAAE,OAAO,CAAC,aAAa;YACjC,OAAO,EAAE,IAAI;SACd;QACD,GAAG,EAAE;YACH,UAAU,EAAE,OAAO,CAAC,aAAa;YACjC,OAAO,EAAE,IAAI;SACd;KACF;IACD,WAAW,EAAE,UAAU,CAAC,IAAI;IAC5B,aAAa,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC;IAChC,gBAAgB,EAAE,CAAC,UAAU,CAAC,WAAW,EAAE,UAAU,CAAC,MAAM,CAAC;IAC7D,SAAS,EAAE,MAAM;IACjB,UAAU;CACX,CAAC","sourcesContent":["/*\n * Copyright (c) Microsoft Corporation.\n * Licensed under the MIT License.\n *\n * Code generated by Microsoft (R) AutoRest Code Generator.\n * Changes may cause incorrect behavior and will be lost if the code is regenerated.\n */\n\nimport * as coreClient from \"@azure/core-client\";\nimport * as Parameters from \"./models/parameters\";\nimport * as Mappers from \"./models/mappers\";\nimport {\n ApplicationInsightsClientOptionalParams,\n TelemetryItem,\n TrackOptionalParams,\n TrackOperationResponse,\n} from \"./models\";\n\nexport class ApplicationInsightsClient extends coreClient.ServiceClient {\n host: string;\n\n /**\n * Initializes a new instance of the ApplicationInsightsClient class.\n * @param options The parameter options\n */\n constructor(options?: ApplicationInsightsClientOptionalParams) {\n // Initializing default values for options\n if (!options) {\n options = {};\n }\n const defaults: ApplicationInsightsClientOptionalParams = {\n requestContentType: \"application/json; charset=utf-8\",\n };\n\n const packageDetails = `azsdk-js-monitor-opentelemetry-exporter/1.0.0-beta.24`;\n const userAgentPrefix =\n options.userAgentOptions && options.userAgentOptions.userAgentPrefix\n ? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}`\n : `${packageDetails}`;\n\n const optionsWithDefaults = {\n ...defaults,\n ...options,\n userAgentOptions: {\n userAgentPrefix,\n },\n endpoint: options.endpoint ?? options.baseUri ?? \"{Host}/v2.1\",\n };\n super(optionsWithDefaults);\n\n // Assigning values to Constant parameters\n this.host = options.host || \"https://dc.services.visualstudio.com\";\n }\n\n /**\n * This operation sends a sequence of telemetry events that will be monitored by Azure Monitor.\n * @param body The list of telemetry events to track.\n * @param options The options parameters.\n */\n track(\n body: TelemetryItem[],\n options?: TrackOptionalParams,\n ): Promise<TrackOperationResponse> {\n return this.sendOperationRequest({ body, options }, trackOperationSpec);\n }\n}\n// Operation Specifications\nconst serializer = coreClient.createSerializer(Mappers, /* isXml */ false);\n\nconst trackOperationSpec: coreClient.OperationSpec = {\n path: \"/track\",\n httpMethod: \"POST\",\n responses: {\n 200: {\n bodyMapper: Mappers.TrackResponse,\n },\n 206: {\n bodyMapper: Mappers.TrackResponse,\n },\n 400: {\n bodyMapper: Mappers.TrackResponse,\n isError: true,\n },\n 402: {\n bodyMapper: Mappers.TrackResponse,\n isError: true,\n },\n 429: {\n bodyMapper: Mappers.TrackResponse,\n isError: true,\n },\n 500: {\n bodyMapper: Mappers.TrackResponse,\n isError: true,\n },\n 503: {\n bodyMapper: Mappers.TrackResponse,\n isError: true,\n },\n },\n requestBody: Parameters.body,\n urlParameters: [Parameters.host],\n headerParameters: [Parameters.contentType, Parameters.accept],\n mediaType: \"json\",\n serializer,\n};\n"]}
@@ -17,16 +17,19 @@ export class BaseSender {
17
17
  this.statsbeatFailureCount = 0;
18
18
  this.batchSendRetryIntervalMs = DEFAULT_BATCH_SEND_RETRY_INTERVAL_MS;
19
19
  this.numConsecutiveRedirects = 0;
20
+ this.disableOfflineStorage = options.exporterOptions.disableOfflineStorage || false;
20
21
  this.persister = new FileSystemPersist(options.instrumentationKey, options.exporterOptions);
21
22
  if (options.trackStatsbeat) {
22
23
  // Initialize statsbeatMetrics
23
24
  this.networkStatsbeatMetrics = new NetworkStatsbeatMetrics({
24
25
  instrumentationKey: options.instrumentationKey,
25
26
  endpointUrl: options.endpointUrl,
27
+ disableOfflineStorage: this.disableOfflineStorage,
26
28
  });
27
29
  this.longIntervalStatsbeatMetrics = getInstance({
28
30
  instrumentationKey: options.instrumentationKey,
29
31
  endpointUrl: options.endpointUrl,
32
+ disableOfflineStorage: this.disableOfflineStorage,
30
33
  });
31
34
  }
32
35
  this.retryTimer = null;
@@ -1 +1 @@
1
- {"version":3,"file":"baseSender.js","sourceRoot":"","sources":["../../../../src/platform/nodejs/baseSender.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAClC,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAG1C,OAAO,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAC9C,OAAO,EAAgB,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACrE,OAAO,EAAE,uBAAuB,EAAE,MAAM,gDAAgD,CAAC;AACzF,OAAO,EAAE,WAAW,EAAE,MAAM,qDAAqD,CAAC;AAElF,OAAO,EAAE,sBAAsB,EAAE,MAAM,8BAA8B,CAAC;AACtE,O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,CAAC;IACf,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\nimport { diag } from \"@opentelemetry/api\";\nimport { PersistentStorage, SenderResult } from \"../../types\";\nimport { AzureMonitorExporterOptions } from \"../../config\";\nimport { FileSystemPersist } from \"./persist\";\nimport { ExportResult, ExportResultCode } from \"@opentelemetry/core\";\nimport { NetworkStatsbeatMetrics } from \"../../export/statsbeat/networkStatsbeatMetrics\";\nimport { getInstance } from \"../../export/statsbeat/longIntervalStatsbeatMetrics\";\nimport { RestError } from \"@azure/core-rest-pipeline\";\nimport { MAX_STATSBEAT_FAILURES } from \"../../export/statsbeat/types\";\nimport { BreezeResponse, isRetriable } from \"../../utils/breezeUtils\";\nimport { TelemetryItem as Envelope } from \"../../generated\";\n\nconst DEFAULT_BATCH_SEND_RETRY_INTERVAL_MS = 60_000;\n\n/**\n * Base sender class\n * @internal\n */\nexport abstract class BaseSender {\n private readonly persister: PersistentStorage;\n private numConsecutiveRedirects: number;\n private retryTimer: NodeJS.Timeout | null;\n private networkStatsbeatMetrics: NetworkStatsbeatMetrics | undefined;\n private longIntervalStatsbeatMetrics;\n private statsbeatFailureCount: number = 0;\n private batchSendRetryIntervalMs: number = DEFAULT_BATCH_SEND_RETRY_INTERVAL_MS;\n private isStatsbeatSender: boolean;\n\n constructor(options: {\n endpointUrl: string;\n instrumentationKey: string;\n trackStatsbeat: boolean;\n exporterOptions: AzureMonitorExporterOptions;\n aadAudience?: string;\n isStatsbeatSender?: boolean;\n }) {\n this.numConsecutiveRedirects = 0;\n this.persister = new FileSystemPersist(options.instrumentationKey, options.exporterOptions);\n if (options.trackStatsbeat) {\n // Initialize statsbeatMetrics\n this.networkStatsbeatMetrics = new NetworkStatsbeatMetrics({\n instrumentationKey: options.instrumentationKey,\n endpointUrl: options.endpointUrl,\n });\n this.longIntervalStatsbeatMetrics = getInstance({\n instrumentationKey: options.instrumentationKey,\n endpointUrl: options.endpointUrl,\n });\n }\n this.retryTimer = null;\n this.isStatsbeatSender = options.isStatsbeatSender || false;\n }\n\n abstract send(payload: unknown[]): Promise<SenderResult>;\n abstract shutdown(): Promise<void>;\n abstract handlePermanentRedirect(location: string | undefined): void;\n\n /**\n * Export envelopes\n */\n public async exportEnvelopes(envelopes: Envelope[]): Promise<ExportResult> {\n diag.info(`Exporting ${envelopes.length} envelope(s)`);\n\n if (envelopes.length < 1) {\n return { code: ExportResultCode.SUCCESS };\n }\n\n try {\n const startTime = new Date().getTime();\n const { result, statusCode } = await this.send(envelopes);\n const endTime = new Date().getTime();\n const duration = endTime - startTime;\n this.numConsecutiveRedirects = 0;\n\n if (statusCode === 200) {\n // Success -- @todo: start retry timer\n if (!this.retryTimer) {\n this.retryTimer = setTimeout(() => {\n this.retryTimer = null;\n this.sendFirstPersistedFile();\n }, this.batchSendRetryIntervalMs);\n this.retryTimer.unref();\n }\n // If we are not exportings statsbeat and statsbeat is not disabled -- count success\n this.networkStatsbeatMetrics?.countSuccess(duration);\n return { code: ExportResultCode.SUCCESS };\n } else if (statusCode && isRetriable(statusCode)) {\n // Failed -- persist failed data\n if (statusCode === 429 || statusCode === 439) {\n this.networkStatsbeatMetrics?.countThrottle(statusCode);\n }\n if (result) {\n diag.info(result);\n const breezeResponse = JSON.parse(result) as BreezeResponse;\n const filteredEnvelopes: Envelope[] = [];\n if (breezeResponse.errors) {\n breezeResponse.errors.forEach((error) => {\n if (error.statusCode && isRetriable(error.statusCode)) {\n filteredEnvelopes.push(envelopes[error.index]);\n }\n });\n }\n if (filteredEnvelopes.length > 0) {\n this.networkStatsbeatMetrics?.countRetry(statusCode);\n // calls resultCallback(ExportResult) based on result of persister.push\n return await this.persist(filteredEnvelopes);\n }\n // Failed -- not retriable\n this.networkStatsbeatMetrics?.countFailure(duration, statusCode);\n return {\n code: ExportResultCode.FAILED,\n };\n } else {\n // calls resultCallback(ExportResult) based on result of persister.push\n this.networkStatsbeatMetrics?.countRetry(statusCode);\n return await this.persist(envelopes);\n }\n } else {\n // Failed -- not retriable\n if (this.networkStatsbeatMetrics) {\n if (statusCode) {\n this.networkStatsbeatMetrics.countFailure(duration, statusCode);\n }\n } else {\n this.incrementStatsbeatFailure();\n }\n return {\n code: ExportResultCode.FAILED,\n };\n }\n } catch (error: any) {\n const restError = error as RestError;\n if (\n restError.statusCode &&\n (restError.statusCode === 307 || // Temporary redirect\n restError.statusCode === 308)\n ) {\n // Permanent redirect\n this.numConsecutiveRedirects++;\n // To prevent circular redirects\n if (this.numConsecutiveRedirects < 10) {\n if (restError.response && restError.response.headers) {\n const location = restError.response.headers.get(\"location\");\n if (location) {\n // Update sender URL\n this.handlePermanentRedirect(location);\n // Send to redirect endpoint as HTTPs library doesn't handle redirect automatically\n return this.exportEnvelopes(envelopes);\n }\n }\n } else {\n const redirectError = new Error(\"Circular redirect\");\n this.networkStatsbeatMetrics?.countException(redirectError);\n return { code: ExportResultCode.FAILED, error: redirectError };\n }\n } else if (restError.statusCode && isRetriable(restError.statusCode)) {\n this.networkStatsbeatMetrics?.countRetry(restError.statusCode);\n return this.persist(envelopes);\n } else if (\n restError.statusCode === 400 &&\n restError.message.includes(\"Invalid instrumentation key\")\n ) {\n const invalidInstrumentationKeyError = new Error(\"Invalid instrumentation key\");\n this.shutdownStatsbeat();\n return { code: ExportResultCode.FAILED, error: invalidInstrumentationKeyError };\n }\n if (this.isNetworkError(restError)) {\n if (restError.statusCode) {\n this.networkStatsbeatMetrics?.countRetry(restError.statusCode);\n }\n if (!this.isStatsbeatSender) {\n diag.error(\n \"Retrying due to transient client side error. Error message:\",\n restError.message,\n );\n }\n return this.persist(envelopes);\n }\n this.networkStatsbeatMetrics?.countException(restError);\n if (!this.isStatsbeatSender) {\n diag.error(\n \"Envelopes could not be exported and are not retriable. Error message:\",\n restError.message,\n );\n }\n return { code: ExportResultCode.FAILED, error: restError };\n }\n }\n\n /**\n * Persist envelopes to disk\n */\n private async persist(envelopes: unknown[]): Promise<ExportResult> {\n try {\n const success = await this.persister.push(envelopes);\n return success\n ? { code: ExportResultCode.SUCCESS }\n : {\n code: ExportResultCode.FAILED,\n error: new Error(\"Failed to persist envelope in disk.\"),\n };\n } catch (ex: any) {\n return { code: ExportResultCode.FAILED, error: ex };\n }\n }\n\n /**\n * Disable collection of statsbeat metrics after max failures\n */\n private incrementStatsbeatFailure() {\n this.statsbeatFailureCount++;\n if (this.statsbeatFailureCount > MAX_STATSBEAT_FAILURES) {\n this.shutdownStatsbeat();\n }\n }\n\n /**\n * Shutdown statsbeat metrics\n */\n private shutdownStatsbeat() {\n this.networkStatsbeatMetrics?.shutdown();\n this.longIntervalStatsbeatMetrics?.shutdown();\n this.networkStatsbeatMetrics = undefined;\n this.statsbeatFailureCount = 0;\n }\n\n private async sendFirstPersistedFile(): Promise<void> {\n try {\n const envelopes = (await this.persister.shift()) as Envelope[] | null;\n if (envelopes) {\n await this.send(envelopes);\n }\n } catch (err: any) {\n diag.warn(`Failed to fetch persisted file`, err);\n }\n }\n\n private isNetworkError(error: RestError): boolean {\n if (error && error.code && error.code === \"REQUEST_SEND_ERROR\") {\n return true;\n }\n return false;\n }\n}\n"]}
1
+ {"version":3,"file":"baseSender.js","sourceRoot":"","sources":["../../../../src/platform/nodejs/baseSender.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAClC,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAG1C,OAAO,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAC9C,OAAO,EAAgB,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACrE,OAAO,EAAE,uBAAuB,EAAE,MAAM,gDAAgD,CAAC;AACzF,OAAO,EAAE,WAAW,EAAE,MAAM,qDAAqD,CAAC;AAElF,OAAO,EAAE,sBAAsB,EAAE,MAAM,8BAA8B,CAAC;AACtE,OAAO,EAAkB,WAAW,EAAE,MAAM,yBAAyB,CAAC;AAGtE,MAAM,oCAAoC,GAAG,KAAM,CAAC;AAEpD;;;GAGG;AACH,MAAM,OAAg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YAC/D,OAAO,IAAI,CAAC;QACd,CAAC;QACD,OAAO,KAAK,CAAC;IACf,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\nimport { diag } from \"@opentelemetry/api\";\nimport { PersistentStorage, SenderResult } from \"../../types\";\nimport { AzureMonitorExporterOptions } from \"../../config\";\nimport { FileSystemPersist } from \"./persist\";\nimport { ExportResult, ExportResultCode } from \"@opentelemetry/core\";\nimport { NetworkStatsbeatMetrics } from \"../../export/statsbeat/networkStatsbeatMetrics\";\nimport { getInstance } from \"../../export/statsbeat/longIntervalStatsbeatMetrics\";\nimport { RestError } from \"@azure/core-rest-pipeline\";\nimport { MAX_STATSBEAT_FAILURES } from \"../../export/statsbeat/types\";\nimport { BreezeResponse, isRetriable } from \"../../utils/breezeUtils\";\nimport { TelemetryItem as Envelope } from \"../../generated\";\n\nconst DEFAULT_BATCH_SEND_RETRY_INTERVAL_MS = 60_000;\n\n/**\n * Base sender class\n * @internal\n */\nexport abstract class BaseSender {\n private readonly persister: PersistentStorage;\n private numConsecutiveRedirects: number;\n private retryTimer: NodeJS.Timeout | null;\n private networkStatsbeatMetrics: NetworkStatsbeatMetrics | undefined;\n private longIntervalStatsbeatMetrics;\n private statsbeatFailureCount: number = 0;\n private batchSendRetryIntervalMs: number = DEFAULT_BATCH_SEND_RETRY_INTERVAL_MS;\n private isStatsbeatSender: boolean;\n private disableOfflineStorage: boolean;\n\n constructor(options: {\n endpointUrl: string;\n instrumentationKey: string;\n trackStatsbeat: boolean;\n exporterOptions: AzureMonitorExporterOptions;\n aadAudience?: string;\n isStatsbeatSender?: boolean;\n }) {\n this.numConsecutiveRedirects = 0;\n this.disableOfflineStorage = options.exporterOptions.disableOfflineStorage || false;\n this.persister = new FileSystemPersist(options.instrumentationKey, options.exporterOptions);\n if (options.trackStatsbeat) {\n // Initialize statsbeatMetrics\n this.networkStatsbeatMetrics = new NetworkStatsbeatMetrics({\n instrumentationKey: options.instrumentationKey,\n endpointUrl: options.endpointUrl,\n disableOfflineStorage: this.disableOfflineStorage,\n });\n this.longIntervalStatsbeatMetrics = getInstance({\n instrumentationKey: options.instrumentationKey,\n endpointUrl: options.endpointUrl,\n disableOfflineStorage: this.disableOfflineStorage,\n });\n }\n this.retryTimer = null;\n this.isStatsbeatSender = options.isStatsbeatSender || false;\n }\n\n abstract send(payload: unknown[]): Promise<SenderResult>;\n abstract shutdown(): Promise<void>;\n abstract handlePermanentRedirect(location: string | undefined): void;\n\n /**\n * Export envelopes\n */\n public async exportEnvelopes(envelopes: Envelope[]): Promise<ExportResult> {\n diag.info(`Exporting ${envelopes.length} envelope(s)`);\n\n if (envelopes.length < 1) {\n return { code: ExportResultCode.SUCCESS };\n }\n\n try {\n const startTime = new Date().getTime();\n const { result, statusCode } = await this.send(envelopes);\n const endTime = new Date().getTime();\n const duration = endTime - startTime;\n this.numConsecutiveRedirects = 0;\n\n if (statusCode === 200) {\n // Success -- @todo: start retry timer\n if (!this.retryTimer) {\n this.retryTimer = setTimeout(() => {\n this.retryTimer = null;\n this.sendFirstPersistedFile();\n }, this.batchSendRetryIntervalMs);\n this.retryTimer.unref();\n }\n // If we are not exportings statsbeat and statsbeat is not disabled -- count success\n this.networkStatsbeatMetrics?.countSuccess(duration);\n return { code: ExportResultCode.SUCCESS };\n } else if (statusCode && isRetriable(statusCode)) {\n // Failed -- persist failed data\n if (statusCode === 429 || statusCode === 439) {\n this.networkStatsbeatMetrics?.countThrottle(statusCode);\n }\n if (result) {\n diag.info(result);\n const breezeResponse = JSON.parse(result) as BreezeResponse;\n const filteredEnvelopes: Envelope[] = [];\n if (breezeResponse.errors) {\n breezeResponse.errors.forEach((error) => {\n if (error.statusCode && isRetriable(error.statusCode)) {\n filteredEnvelopes.push(envelopes[error.index]);\n }\n });\n }\n if (filteredEnvelopes.length > 0) {\n this.networkStatsbeatMetrics?.countRetry(statusCode);\n // calls resultCallback(ExportResult) based on result of persister.push\n return await this.persist(filteredEnvelopes);\n }\n // Failed -- not retriable\n this.networkStatsbeatMetrics?.countFailure(duration, statusCode);\n return {\n code: ExportResultCode.FAILED,\n };\n } else {\n // calls resultCallback(ExportResult) based on result of persister.push\n this.networkStatsbeatMetrics?.countRetry(statusCode);\n return await this.persist(envelopes);\n }\n } else {\n // Failed -- not retriable\n if (this.networkStatsbeatMetrics) {\n if (statusCode) {\n this.networkStatsbeatMetrics.countFailure(duration, statusCode);\n }\n } else {\n this.incrementStatsbeatFailure();\n }\n return {\n code: ExportResultCode.FAILED,\n };\n }\n } catch (error: any) {\n const restError = error as RestError;\n if (\n restError.statusCode &&\n (restError.statusCode === 307 || // Temporary redirect\n restError.statusCode === 308)\n ) {\n // Permanent redirect\n this.numConsecutiveRedirects++;\n // To prevent circular redirects\n if (this.numConsecutiveRedirects < 10) {\n if (restError.response && restError.response.headers) {\n const location = restError.response.headers.get(\"location\");\n if (location) {\n // Update sender URL\n this.handlePermanentRedirect(location);\n // Send to redirect endpoint as HTTPs library doesn't handle redirect automatically\n return this.exportEnvelopes(envelopes);\n }\n }\n } else {\n const redirectError = new Error(\"Circular redirect\");\n this.networkStatsbeatMetrics?.countException(redirectError);\n return { code: ExportResultCode.FAILED, error: redirectError };\n }\n } else if (restError.statusCode && isRetriable(restError.statusCode)) {\n this.networkStatsbeatMetrics?.countRetry(restError.statusCode);\n return this.persist(envelopes);\n } else if (\n restError.statusCode === 400 &&\n restError.message.includes(\"Invalid instrumentation key\")\n ) {\n const invalidInstrumentationKeyError = new Error(\"Invalid instrumentation key\");\n this.shutdownStatsbeat();\n return { code: ExportResultCode.FAILED, error: invalidInstrumentationKeyError };\n }\n if (this.isNetworkError(restError)) {\n if (restError.statusCode) {\n this.networkStatsbeatMetrics?.countRetry(restError.statusCode);\n }\n if (!this.isStatsbeatSender) {\n diag.error(\n \"Retrying due to transient client side error. Error message:\",\n restError.message,\n );\n }\n return this.persist(envelopes);\n }\n this.networkStatsbeatMetrics?.countException(restError);\n if (!this.isStatsbeatSender) {\n diag.error(\n \"Envelopes could not be exported and are not retriable. Error message:\",\n restError.message,\n );\n }\n return { code: ExportResultCode.FAILED, error: restError };\n }\n }\n\n /**\n * Persist envelopes to disk\n */\n private async persist(envelopes: unknown[]): Promise<ExportResult> {\n try {\n const success = await this.persister.push(envelopes);\n return success\n ? { code: ExportResultCode.SUCCESS }\n : {\n code: ExportResultCode.FAILED,\n error: new Error(\"Failed to persist envelope in disk.\"),\n };\n } catch (ex: any) {\n return { code: ExportResultCode.FAILED, error: ex };\n }\n }\n\n /**\n * Disable collection of statsbeat metrics after max failures\n */\n private incrementStatsbeatFailure() {\n this.statsbeatFailureCount++;\n if (this.statsbeatFailureCount > MAX_STATSBEAT_FAILURES) {\n this.shutdownStatsbeat();\n }\n }\n\n /**\n * Shutdown statsbeat metrics\n */\n private shutdownStatsbeat() {\n this.networkStatsbeatMetrics?.shutdown();\n this.longIntervalStatsbeatMetrics?.shutdown();\n this.networkStatsbeatMetrics = undefined;\n this.statsbeatFailureCount = 0;\n }\n\n private async sendFirstPersistedFile(): Promise<void> {\n try {\n const envelopes = (await this.persister.shift()) as Envelope[] | null;\n if (envelopes) {\n await this.send(envelopes);\n }\n } catch (err: any) {\n diag.warn(`Failed to fetch persisted file`, err);\n }\n }\n\n private isNetworkError(error: RestError): boolean {\n if (error && error.code && error.code === \"REQUEST_SEND_ERROR\") {\n return true;\n }\n return false;\n }\n}\n"]}
@@ -52,12 +52,19 @@ export class FileSystemPersist {
52
52
  }
53
53
  }
54
54
  push(value) {
55
+ var _a;
55
56
  if (this._enabled) {
56
57
  diag.debug("Pushing value to persistent storage", value.toString());
57
58
  return this._storeToDisk(JSON.stringify(value));
58
59
  }
60
+ // Only return a false promise if the SDK isn't set to disable offline storage
61
+ if (!((_a = this._options) === null || _a === void 0 ? void 0 : _a.disableOfflineStorage)) {
62
+ return new Promise((resolve) => {
63
+ resolve(false);
64
+ });
65
+ }
59
66
  return new Promise((resolve) => {
60
- resolve(false);
67
+ resolve(true);
61
68
  });
62
69
  }
63
70
  async shift() {
@@ -1 +1 @@
1
- {"version":3,"file":"fileSystemPersist.js","sourceRoot":"","sources":["../../../../../src/platform/nodejs/persist/fileSystemPersist.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAC7B,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAE1C,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,EAAE,gBAAgB,EAAE,uBAAuB,EAAE,MAAM,qBAAqB,CAAC;AAChF,OAAO,EAAE,SAAS,EAAE,MAAM,MAAM,CAAC;AAGjC,MAAM,SAAS,GAAG,SAAS,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC;AACrC,MAAM,YAAY,GAAG,SAAS,CAAC,EAAE,CAAC,OAAO,CAAC,CAAC;AAC3C,MAAM,aAAa,GAAG,SAAS,CAAC,EAAE,CAAC,QAAQ,CAAC,CAAC;AAC7C,MAAM,WAAW,GAAG,SAAS,CAAC,EAAE,CAAC,MAAM,CAAC,CAAC;AACzC,MAAM,cAAc,GAAG,SAAS,CAAC,EAAE,CAAC,SAAS,CAAC,CAAC;AAE/C;;;GAGG;AACH,MAAM,OAAO,iBAAiB;IAa5B,YACE,kBAA0B,EAClB,QAAsC;;QAAtC,aAAQ,GAAR,QAAQ,CAA8B;QAXhD,yBAAoB,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC,CAAC,SAAS;QACzD,mBAAc,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC,CAAC,SAAS;QAC1C,mBAAc,GAAW,QAAU,CAAC,CAAC,QAAQ;QAGrC,mBAAc,GAAW,EAAE,CAAC;QAC5B,sBAAiB,GAA0B,IAAI,CAAC;QAOtD,IAAI,CA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C;gBACf,CAAC;qBAAM,CAAC;oBACN,KAAK,CAAC,OAAO,CAAC,KAAK,EAAE,IAAI,EAAE,EAAE;wBAC3B,mBAAmB;wBACnB,MAAM,gBAAgB,GAAS,IAAI,IAAI,CACrC,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,iBAAiB,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,CAAC,CAC3D,CAAC;wBACF,MAAM,OAAO,GAAG,IAAI,IAAI,CAAC,CAAC,IAAI,IAAI,EAAE,GAAG,IAAI,CAAC,oBAAoB,CAAC,GAAG,gBAAgB,CAAC;wBACrF,IAAI,OAAO,EAAE,CAAC;4BACZ,MAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,cAAc,EAAE,IAAI,CAAC,CAAC;4BACtD,MAAM,WAAW,CAAC,QAAQ,CAAC,CAAC;wBAC9B,CAAC;oBACH,CAAC,CAAC,CAAC;oBACH,OAAO,IAAI,CAAC;gBACd,CAAC;YACH,CAAC;YACD,OAAO,KAAK,CAAC;QACf,CAAC;QAAC,OAAO,KAAU,EAAE,CAAC;YACpB,IAAI,CAAC,IAAI,CAAC,yDAAyD,EAAE,KAAK,CAAC,CAAC;YAC5E,OAAO,KAAK,CAAC;QACf,CAAC;IACH,CAAC;;AAtLM,gCAAc,GAAG,oBAAoB,AAAvB,CAAwB;AACtC,iCAAe,GAAG,UAAU,AAAb,CAAc","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport * as fs from \"fs\";\nimport * as os from \"os\";\nimport * as path from \"path\";\nimport { diag } from \"@opentelemetry/api\";\nimport { PersistentStorage } from \"../../../types\";\nimport { FileAccessControl } from \"./fileAccessControl\";\nimport { confirmDirExists, getShallowDirectorySize } from \"./fileSystemHelpers\";\nimport { promisify } from \"util\";\nimport { AzureMonitorExporterOptions } from \"../../../config\";\n\nconst statAsync = promisify(fs.stat);\nconst readdirAsync = promisify(fs.readdir);\nconst readFileAsync = promisify(fs.readFile);\nconst unlinkAsync = promisify(fs.unlink);\nconst writeFileAsync = promisify(fs.writeFile);\n\n/**\n * File system persist class.\n * @internal\n */\nexport class FileSystemPersist implements PersistentStorage {\n static TEMPDIR_PREFIX = \"ot-azure-exporter-\";\n static FILENAME_SUFFIX = \".ai.json\";\n\n fileRetemptionPeriod = 2 * 24 * 60 * 60 * 1000; // 2 days\n cleanupTimeOut = 60 * 60 * 1000; // 1 hour\n maxBytesOnDisk: number = 50_000_000; // ~50MB\n\n private _enabled: boolean;\n private _tempDirectory: string = \"\";\n private _fileCleanupTimer: NodeJS.Timeout | null = null;\n private _instrumentationKey: string;\n\n constructor(\n instrumentationKey: string,\n private _options?: AzureMonitorExporterOptions,\n ) {\n this._instrumentationKey = instrumentationKey;\n if (this._options?.disableOfflineStorage) {\n this._enabled = false;\n return;\n }\n this._enabled = true;\n FileAccessControl.checkFileProtection();\n\n if (!FileAccessControl.OS_PROVIDES_FILE_PROTECTION) {\n this._enabled = false;\n diag.error(\n \"Sufficient file protection capabilities were not detected. Files will not be persisted\",\n );\n }\n\n if (!this._instrumentationKey) {\n this._enabled = false;\n diag.error(\n `No instrumentation key was provided to FileSystemPersister. Files will not be persisted`,\n );\n }\n if (this._enabled) {\n this._tempDirectory = path.join(\n this._options?.storageDirectory || os.tmpdir(),\n \"Microsoft\",\n \"AzureMonitor\",\n FileSystemPersist.TEMPDIR_PREFIX + this._instrumentationKey,\n );\n\n // Starts file cleanup task\n if (!this._fileCleanupTimer) {\n this._fileCleanupTimer = setTimeout(() => {\n this._fileCleanupTask();\n }, this.cleanupTimeOut);\n this._fileCleanupTimer.unref();\n }\n }\n }\n\n push(value: unknown[]): Promise<boolean> {\n if (this._enabled) {\n diag.debug(\"Pushing value to persistent storage\", value.toString());\n return this._storeToDisk(JSON.stringify(value));\n }\n return new Promise((resolve) => {\n resolve(false);\n });\n }\n\n async shift(): Promise<unknown> {\n if (this._enabled) {\n diag.debug(\"Searching for filesystem persisted files\");\n try {\n const buffer = await this._getFirstFileOnDisk();\n if (buffer) {\n return JSON.parse(buffer.toString(\"utf8\"));\n }\n } catch (e: any) {\n diag.debug(\"Failed to read persisted file\", e);\n }\n return null;\n }\n return new Promise((resolve) => {\n resolve(null);\n });\n }\n\n /**\n * Check for temp telemetry files\n * reads the first file if exist, deletes it and tries to send its load\n */\n private async _getFirstFileOnDisk(): Promise<Buffer | null> {\n try {\n const stats = await statAsync(this._tempDirectory);\n if (stats.isDirectory()) {\n const origFiles = await readdirAsync(this._tempDirectory);\n const files = origFiles.filter((f) =>\n path.basename(f).includes(FileSystemPersist.FILENAME_SUFFIX),\n );\n if (files.length === 0) {\n return null;\n } else {\n const firstFile = files[0];\n const filePath = path.join(this._tempDirectory, firstFile);\n const payload = await readFileAsync(filePath);\n // delete the file first to prevent double sending\n await unlinkAsync(filePath);\n return payload;\n }\n }\n return null;\n } catch (e: any) {\n if (e.code === \"ENOENT\") {\n // File does not exist -- return null instead of throwing\n return null;\n } else {\n throw e;\n }\n }\n }\n\n private async _storeToDisk(payload: string): Promise<boolean> {\n try {\n await confirmDirExists(this._tempDirectory);\n } catch (error: any) {\n diag.warn(`Error while checking/creating directory: `, error && error.message);\n return false;\n }\n\n try {\n const size = await getShallowDirectorySize(this._tempDirectory);\n if (size > this.maxBytesOnDisk) {\n diag.warn(\n `Not saving data due to max size limit being met. Directory size in bytes is: ${size}`,\n );\n return false;\n }\n } catch (error: any) {\n diag.warn(`Error while checking size of persistence directory: `, error && error.message);\n return false;\n }\n\n const fileName = `${new Date().getTime()}${FileSystemPersist.FILENAME_SUFFIX}`;\n const fileFullPath = path.join(this._tempDirectory, fileName);\n\n // Mode 600 is w/r for creator and no read access for others\n diag.info(`saving data to disk at: ${fileFullPath}`);\n try {\n await writeFileAsync(fileFullPath, payload, { mode: 0o600 });\n } catch (writeError: any) {\n diag.warn(`Error writing file to persistent file storage`, writeError);\n return false;\n }\n return true;\n }\n\n private async _fileCleanupTask(): Promise<boolean> {\n try {\n const stats = await statAsync(this._tempDirectory);\n if (stats.isDirectory()) {\n const origFiles = await readdirAsync(this._tempDirectory);\n const files = origFiles.filter((f) =>\n path.basename(f).includes(FileSystemPersist.FILENAME_SUFFIX),\n );\n if (files.length === 0) {\n return false;\n } else {\n files.forEach(async (file) => {\n // Check expiration\n const fileCreationDate: Date = new Date(\n parseInt(file.split(FileSystemPersist.FILENAME_SUFFIX)[0]),\n );\n const expired = new Date(+new Date() - this.fileRetemptionPeriod) > fileCreationDate;\n if (expired) {\n const filePath = path.join(this._tempDirectory, file);\n await unlinkAsync(filePath);\n }\n });\n return true;\n }\n }\n return false;\n } catch (error: any) {\n diag.info(`Failed cleanup of persistent file storage expired files`, error);\n return false;\n }\n }\n}\n"]}
1
+ {"version":3,"file":"fileSystemPersist.js","sourceRoot":"","sources":["../../../../../src/platform/nodejs/persist/fileSystemPersist.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAC7B,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAE1C,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,EAAE,gBAAgB,EAAE,uBAAuB,EAAE,MAAM,qBAAqB,CAAC;AAChF,OAAO,EAAE,SAAS,EAAE,MAAM,MAAM,CAAC;AAGjC,MAAM,SAAS,GAAG,SAAS,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC;AACrC,MAAM,YAAY,GAAG,SAAS,CAAC,EAAE,CAAC,OAAO,CAAC,CAAC;AAC3C,MAAM,aAAa,GAAG,SAAS,CAAC,EAAE,CAAC,QAAQ,CAAC,CAAC;AAC7C,MAAM,WAAW,GAAG,SAAS,CAAC,EAAE,CAAC,MAAM,CAAC,CAAC;AACzC,MAAM,cAAc,GAAG,SAAS,CAAC,EAAE,C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H,OAAO,IAAI,CAAC;gBACd,CAAC;YACH,CAAC;YACD,OAAO,KAAK,CAAC;QACf,CAAC;QAAC,OAAO,KAAU,EAAE,CAAC;YACpB,IAAI,CAAC,IAAI,CAAC,yDAAyD,EAAE,KAAK,CAAC,CAAC;YAC5E,OAAO,KAAK,CAAC;QACf,CAAC;IACH,CAAC;;AA5LM,gCAAc,GAAG,oBAAoB,AAAvB,CAAwB;AACtC,iCAAe,GAAG,UAAU,AAAb,CAAc","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport * as fs from \"fs\";\nimport * as os from \"os\";\nimport * as path from \"path\";\nimport { diag } from \"@opentelemetry/api\";\nimport { PersistentStorage } from \"../../../types\";\nimport { FileAccessControl } from \"./fileAccessControl\";\nimport { confirmDirExists, getShallowDirectorySize } from \"./fileSystemHelpers\";\nimport { promisify } from \"util\";\nimport { AzureMonitorExporterOptions } from \"../../../config\";\n\nconst statAsync = promisify(fs.stat);\nconst readdirAsync = promisify(fs.readdir);\nconst readFileAsync = promisify(fs.readFile);\nconst unlinkAsync = promisify(fs.unlink);\nconst writeFileAsync = promisify(fs.writeFile);\n\n/**\n * File system persist class.\n * @internal\n */\nexport class FileSystemPersist implements PersistentStorage {\n static TEMPDIR_PREFIX = \"ot-azure-exporter-\";\n static FILENAME_SUFFIX = \".ai.json\";\n\n fileRetemptionPeriod = 2 * 24 * 60 * 60 * 1000; // 2 days\n cleanupTimeOut = 60 * 60 * 1000; // 1 hour\n maxBytesOnDisk: number = 50_000_000; // ~50MB\n\n private _enabled: boolean;\n private _tempDirectory: string = \"\";\n private _fileCleanupTimer: NodeJS.Timeout | null = null;\n private _instrumentationKey: string;\n\n constructor(\n instrumentationKey: string,\n private _options?: AzureMonitorExporterOptions,\n ) {\n this._instrumentationKey = instrumentationKey;\n if (this._options?.disableOfflineStorage) {\n this._enabled = false;\n return;\n }\n this._enabled = true;\n FileAccessControl.checkFileProtection();\n\n if (!FileAccessControl.OS_PROVIDES_FILE_PROTECTION) {\n this._enabled = false;\n diag.error(\n \"Sufficient file protection capabilities were not detected. Files will not be persisted\",\n );\n }\n\n if (!this._instrumentationKey) {\n this._enabled = false;\n diag.error(\n `No instrumentation key was provided to FileSystemPersister. Files will not be persisted`,\n );\n }\n if (this._enabled) {\n this._tempDirectory = path.join(\n this._options?.storageDirectory || os.tmpdir(),\n \"Microsoft\",\n \"AzureMonitor\",\n FileSystemPersist.TEMPDIR_PREFIX + this._instrumentationKey,\n );\n\n // Starts file cleanup task\n if (!this._fileCleanupTimer) {\n this._fileCleanupTimer = setTimeout(() => {\n this._fileCleanupTask();\n }, this.cleanupTimeOut);\n this._fileCleanupTimer.unref();\n }\n }\n }\n\n push(value: unknown[]): Promise<boolean> {\n if (this._enabled) {\n diag.debug(\"Pushing value to persistent storage\", value.toString());\n return this._storeToDisk(JSON.stringify(value));\n }\n // Only return a false promise if the SDK isn't set to disable offline storage\n if (!this._options?.disableOfflineStorage) {\n return new Promise((resolve) => {\n resolve(false);\n });\n }\n return new Promise((resolve) => {\n resolve(true);\n });\n }\n\n async shift(): Promise<unknown> {\n if (this._enabled) {\n diag.debug(\"Searching for filesystem persisted files\");\n try {\n const buffer = await this._getFirstFileOnDisk();\n if (buffer) {\n return JSON.parse(buffer.toString(\"utf8\"));\n }\n } catch (e: any) {\n diag.debug(\"Failed to read persisted file\", e);\n }\n return null;\n }\n return new Promise((resolve) => {\n resolve(null);\n });\n }\n\n /**\n * Check for temp telemetry files\n * reads the first file if exist, deletes it and tries to send its load\n */\n private async _getFirstFileOnDisk(): Promise<Buffer | null> {\n try {\n const stats = await statAsync(this._tempDirectory);\n if (stats.isDirectory()) {\n const origFiles = await readdirAsync(this._tempDirectory);\n const files = origFiles.filter((f) =>\n path.basename(f).includes(FileSystemPersist.FILENAME_SUFFIX),\n );\n if (files.length === 0) {\n return null;\n } else {\n const firstFile = files[0];\n const filePath = path.join(this._tempDirectory, firstFile);\n const payload = await readFileAsync(filePath);\n // delete the file first to prevent double sending\n await unlinkAsync(filePath);\n return payload;\n }\n }\n return null;\n } catch (e: any) {\n if (e.code === \"ENOENT\") {\n // File does not exist -- return null instead of throwing\n return null;\n } else {\n throw e;\n }\n }\n }\n\n private async _storeToDisk(payload: string): Promise<boolean> {\n try {\n await confirmDirExists(this._tempDirectory);\n } catch (error: any) {\n diag.warn(`Error while checking/creating directory: `, error && error.message);\n return false;\n }\n\n try {\n const size = await getShallowDirectorySize(this._tempDirectory);\n if (size > this.maxBytesOnDisk) {\n diag.warn(\n `Not saving data due to max size limit being met. Directory size in bytes is: ${size}`,\n );\n return false;\n }\n } catch (error: any) {\n diag.warn(`Error while checking size of persistence directory: `, error && error.message);\n return false;\n }\n\n const fileName = `${new Date().getTime()}${FileSystemPersist.FILENAME_SUFFIX}`;\n const fileFullPath = path.join(this._tempDirectory, fileName);\n\n // Mode 600 is w/r for creator and no read access for others\n diag.info(`saving data to disk at: ${fileFullPath}`);\n try {\n await writeFileAsync(fileFullPath, payload, { mode: 0o600 });\n } catch (writeError: any) {\n diag.warn(`Error writing file to persistent file storage`, writeError);\n return false;\n }\n return true;\n }\n\n private async _fileCleanupTask(): Promise<boolean> {\n try {\n const stats = await statAsync(this._tempDirectory);\n if (stats.isDirectory()) {\n const origFiles = await readdirAsync(this._tempDirectory);\n const files = origFiles.filter((f) =>\n path.basename(f).includes(FileSystemPersist.FILENAME_SUFFIX),\n );\n if (files.length === 0) {\n return false;\n } else {\n files.forEach(async (file) => {\n // Check expiration\n const fileCreationDate: Date = new Date(\n parseInt(file.split(FileSystemPersist.FILENAME_SUFFIX)[0]),\n );\n const expired = new Date(+new Date() - this.fileRetemptionPeriod) > fileCreationDate;\n if (expired) {\n const filePath = path.join(this._tempDirectory, file);\n await unlinkAsync(filePath);\n }\n });\n return true;\n }\n }\n return false;\n } catch (error: any) {\n diag.info(`Failed cleanup of persistent file storage expired files`, error);\n return false;\n }\n }\n}\n"]}
@@ -1,4 +1,29 @@
1
1
  // Copyright (c) Microsoft Corporation.
2
2
  // Licensed under the MIT license.
3
- export {};
3
+ /**
4
+ * Performance Counter OpenTelemetry compliant names.
5
+ * @internal
6
+ */
7
+ export var OTelPerformanceCounterNames;
8
+ (function (OTelPerformanceCounterNames) {
9
+ OTelPerformanceCounterNames["PRIVATE_BYTES"] = "Private_Bytes";
10
+ OTelPerformanceCounterNames["AVAILABLE_BYTES"] = "Available_Bytes";
11
+ OTelPerformanceCounterNames["PROCESSOR_TIME"] = "Processor_Time";
12
+ OTelPerformanceCounterNames["PROCESS_TIME"] = "Process_Time";
13
+ OTelPerformanceCounterNames["REQUEST_RATE"] = "Request_Rate";
14
+ OTelPerformanceCounterNames["REQUEST_DURATION"] = "Request_Execution_Time";
15
+ })(OTelPerformanceCounterNames || (OTelPerformanceCounterNames = {}));
16
+ /**
17
+ * Breeze Performance Counter names.
18
+ * @internal
19
+ */
20
+ export var BreezePerformanceCounterNames;
21
+ (function (BreezePerformanceCounterNames) {
22
+ BreezePerformanceCounterNames["PRIVATE_BYTES"] = "\\Process(??APP_WIN32_PROC??)\\Private Bytes";
23
+ BreezePerformanceCounterNames["AVAILABLE_BYTES"] = "\\Memory\\Available Bytes";
24
+ BreezePerformanceCounterNames["PROCESSOR_TIME"] = "\\Processor(_Total)\\% Processor Time";
25
+ BreezePerformanceCounterNames["PROCESS_TIME"] = "\\Process(??APP_WIN32_PROC??)\\% Processor Time";
26
+ BreezePerformanceCounterNames["REQUEST_RATE"] = "\\ASP.NET Applications(??APP_W3SVC_PROC??)\\Requests/Sec";
27
+ BreezePerformanceCounterNames["REQUEST_DURATION"] = "\\ASP.NET Applications(??APP_W3SVC_PROC??)\\Request Execution Time";
28
+ })(BreezePerformanceCounterNames || (BreezePerformanceCounterNames = {}));
4
29
  //# sourceMappingURL=types.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { ContextTagKeys } from \"./generated\";\n\n/**\n * Azure Monitor envelope tags.\n * @internal\n */\nexport type Tags = { [key in ContextTagKeys]: string };\n/**\n * Azure Monitor envelope property type.\n * @internal\n */\nexport type PropertyType = string | number | boolean | object | Array<PropertyType>;\n/**\n * Azure Monitor envelope properties.\n * @internal\n */\nexport type Properties = { [key: string]: Properties | PropertyType };\n/**\n * Azure Monitor envelope links.\n * @internal\n */\nexport interface MSLink {\n operation_Id: string;\n id: string;\n}\n/**\n * Azure Monitor envelope measurements.\n * @internal\n */\nexport type Measurements = { [key: string]: number };\n/**\n * Exporter sender result.\n * @internal\n */\nexport type SenderResult = { statusCode: number | undefined; result: string };\n\n/**\n * Exporter persistent storage.\n * @internal\n */\nexport interface PersistentStorage {\n shift(): Promise<unknown>;\n push(value: unknown[]): Promise<boolean>;\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AA+ClC;;;GAGG;AACH,MAAM,CAAN,IAAY,2BAOX;AAPD,WAAY,2BAA2B;IACrC,8DAA+B,CAAA;IAC/B,kEAAmC,CAAA;IACnC,gEAAiC,CAAA;IACjC,4DAA6B,CAAA;IAC7B,4DAA6B,CAAA;IAC7B,0EAA2C,CAAA;AAC7C,CAAC,EAPW,2BAA2B,KAA3B,2BAA2B,QAOtC;AAED;;;GAGG;AACH,MAAM,CAAN,IAAY,6BAOX;AAPD,WAAY,6BAA6B;IACvC,+FAA8D,CAAA;IAC9D,8EAA6C,CAAA;IAC7C,yFAAwD,CAAA;IACxD,iGAAgE,CAAA;IAChE,0GAAyE,CAAA;IACzE,wHAAuF,CAAA;AACzF,CAAC,EAPW,6BAA6B,KAA7B,6BAA6B,QAOxC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { ContextTagKeys } from \"./generated\";\n\n/**\n * Azure Monitor envelope tags.\n * @internal\n */\nexport type Tags = { [key in ContextTagKeys]: string };\n/**\n * Azure Monitor envelope property type.\n * @internal\n */\nexport type PropertyType = string | number | boolean | object | Array<PropertyType>;\n/**\n * Azure Monitor envelope properties.\n * @internal\n */\nexport type Properties = { [key: string]: Properties | PropertyType };\n/**\n * Azure Monitor envelope links.\n * @internal\n */\nexport interface MSLink {\n operation_Id: string;\n id: string;\n}\n/**\n * Azure Monitor envelope measurements.\n * @internal\n */\nexport type Measurements = { [key: string]: number };\n/**\n * Exporter sender result.\n * @internal\n */\nexport type SenderResult = { statusCode: number | undefined; result: string };\n\n/**\n * Exporter persistent storage.\n * @internal\n */\nexport interface PersistentStorage {\n shift(): Promise<unknown>;\n push(value: unknown[]): Promise<boolean>;\n}\n\n/**\n * Performance Counter OpenTelemetry compliant names.\n * @internal\n */\nexport enum OTelPerformanceCounterNames {\n PRIVATE_BYTES = \"Private_Bytes\",\n AVAILABLE_BYTES = \"Available_Bytes\",\n PROCESSOR_TIME = \"Processor_Time\",\n PROCESS_TIME = \"Process_Time\",\n REQUEST_RATE = \"Request_Rate\",\n REQUEST_DURATION = \"Request_Execution_Time\",\n}\n\n/**\n * Breeze Performance Counter names.\n * @internal\n */\nexport enum BreezePerformanceCounterNames {\n PRIVATE_BYTES = \"\\\\Process(??APP_WIN32_PROC??)\\\\Private Bytes\",\n AVAILABLE_BYTES = \"\\\\Memory\\\\Available Bytes\",\n PROCESSOR_TIME = \"\\\\Processor(_Total)\\\\% Processor Time\",\n PROCESS_TIME = \"\\\\Process(??APP_WIN32_PROC??)\\\\% Processor Time\",\n REQUEST_RATE = \"\\\\ASP.NET Applications(??APP_W3SVC_PROC??)\\\\Requests/Sec\",\n REQUEST_DURATION = \"\\\\ASP.NET Applications(??APP_W3SVC_PROC??)\\\\Request Execution Time\",\n}\n"]}
@@ -19,7 +19,7 @@ export const TIME_SINCE_ENQUEUED = "timeSinceEnqueued";
19
19
  * AzureMonitorTraceExporter version.
20
20
  * @internal
21
21
  */
22
- export const packageVersion = "1.0.0-beta.22";
22
+ export const packageVersion = "1.0.0-beta.24";
23
23
  export var DependencyTypes;
24
24
  (function (DependencyTypes) {
25
25
  DependencyTypes["InProc"] = "InProc";
@@ -1 +1 @@
1
- {"version":3,"file":"applicationinsights.js","sourceRoot":"","sources":["../../../../src/utils/constants/applicationinsights.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,iCAAiC;AAEjC;;;GAGG;AACH,MAAM,CAAC,MAAM,QAAQ,GAAG,WAAW,CAAC;AACpC;;;GAGG;AACH,MAAM,CAAC,MAAM,aAAa,GAAG,cAAc,CAAC;AAC5C;;;GAGG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG,mBAAmB,CAAC;AACvD;;;GAGG;AACH,MAAM,CAAC,MAAM,cAAc,GAAG,eAAe,CAAC;AAE9C,MAAM,CAAN,IAAY,eAOX;AAPD,WAAY,eAAe;IACzB,oCAAiB,CAAA;IACjB,iDAA8B,CAAA;IAC9B,8BAAW,CAAA;IACX,gCAAa,CAAA;IACb,gCAAa,CAAA;IACb,sCAAmB,CAAA;AACrB,CAAC,EAPW,eAAe,KAAf,eAAe,QAO1B;AAED,MAAM,CAAC,MAAM,sBAAsB,GAAG,gBAAgB,CAAC;AACvD,MAAM,CAAC,MAAM,2BAA2B,GAAG,cAAc,CAAC;AAE1D,MAAM,CAAC,MAAM,8BAA8B,GAAG,uCAAuC,CAAC;AACtF,MAAM,CAAC,MAAM,gCAAgC,GAAG,yCAAyC,CAAC;AAC1F,MAAM,CAAC,MAAM,+BAA+B,GAAG,wCAAwC,CAAC;AACxF,MAAM,CAAC,MAAM,mCAAmC,GAAG,4CAA4C,CAAC;AAChG,MAAM,CAAC,MAAM,4BAA4B,GAAG,qCAAqC,CAAC;AAElF,MAAM,CAAC,MAAM,kCAAkC,GAAG,aAAa,CAAC;AAChE,MAAM,CAAC,MAAM,oCAAoC,GAAG,eAAe,CAAC;AACpE,MAAM,CAAC,MAAM,mCAAmC,GAAG,cAAc,CAAC;AAClE,MAAM,CAAC,MAAM,uCAAuC,GAAG,kBAAkB,CAAC;AAC1E,MAAM,CAAC,MAAM,gCAAgC,GAAG,WAAW,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license\n\n/**\n * AI MS Links.\n * @internal\n */\nexport const MS_LINKS = \"_MS.links\";\n/**\n * AI enqueued time attribute.\n * @internal\n */\nexport const ENQUEUED_TIME = \"enqueuedTime\";\n/**\n * AI time since enqueued attribute.\n * @internal\n */\nexport const TIME_SINCE_ENQUEUED = \"timeSinceEnqueued\";\n/**\n * AzureMonitorTraceExporter version.\n * @internal\n */\nexport const packageVersion = \"1.0.0-beta.22\";\n\nexport enum DependencyTypes {\n InProc = \"InProc\",\n QueueMessage = \"Queue Message\",\n Sql = \"SQL\",\n Http = \"Http\",\n Grpc = \"GRPC\",\n Wcf = \"WCF Service\",\n}\n\nexport const AzureMonitorSampleRate = \"_MS.sampleRate\";\nexport const ApplicationInsightsBaseType = \"_MS.baseType\";\n\nexport const ApplicationInsightsMessageName = \"Microsoft.ApplicationInsights.Message\";\nexport const ApplicationInsightsExceptionName = \"Microsoft.ApplicationInsights.Exception\";\nexport const ApplicationInsightsPageViewName = \"Microsoft.ApplicationInsights.PageView\";\nexport const ApplicationInsightsAvailabilityName = \"Microsoft.ApplicationInsights.Availability\";\nexport const ApplicationInsightsEventName = \"Microsoft.ApplicationInsights.Event\";\n\nexport const ApplicationInsightsMessageBaseType = \"MessageData\";\nexport const ApplicationInsightsExceptionBaseType = \"ExceptionData\";\nexport const ApplicationInsightsPageViewBaseType = \"PageViewData\";\nexport const ApplicationInsightsAvailabilityBaseType = \"AvailabilityData\";\nexport const ApplicationInsightsEventBaseType = \"EventData\";\n"]}
1
+ {"version":3,"file":"applicationinsights.js","sourceRoot":"","sources":["../../../../src/utils/constants/applicationinsights.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,iCAAiC;AAEjC;;;GAGG;AACH,MAAM,CAAC,MAAM,QAAQ,GAAG,WAAW,CAAC;AACpC;;;GAGG;AACH,MAAM,CAAC,MAAM,aAAa,GAAG,cAAc,CAAC;AAC5C;;;GAGG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG,mBAAmB,CAAC;AACvD;;;GAGG;AACH,MAAM,CAAC,MAAM,cAAc,GAAG,eAAe,CAAC;AAE9C,MAAM,CAAN,IAAY,eAOX;AAPD,WAAY,eAAe;IACzB,oCAAiB,CAAA;IACjB,iDAA8B,CAAA;IAC9B,8BAAW,CAAA;IACX,gCAAa,CAAA;IACb,gCAAa,CAAA;IACb,sCAAmB,CAAA;AACrB,CAAC,EAPW,eAAe,KAAf,eAAe,QAO1B;AAED,MAAM,CAAC,MAAM,sBAAsB,GAAG,gBAAgB,CAAC;AACvD,MAAM,CAAC,MAAM,2BAA2B,GAAG,cAAc,CAAC;AAE1D,MAAM,CAAC,MAAM,8BAA8B,GAAG,uCAAuC,CAAC;AACtF,MAAM,CAAC,MAAM,gCAAgC,GAAG,yCAAyC,CAAC;AAC1F,MAAM,CAAC,MAAM,+BAA+B,GAAG,wCAAwC,CAAC;AACxF,MAAM,CAAC,MAAM,mCAAmC,GAAG,4CAA4C,CAAC;AAChG,MAAM,CAAC,MAAM,4BAA4B,GAAG,qCAAqC,CAAC;AAElF,MAAM,CAAC,MAAM,kCAAkC,GAAG,aAAa,CAAC;AAChE,MAAM,CAAC,MAAM,oCAAoC,GAAG,eAAe,CAAC;AACpE,MAAM,CAAC,MAAM,mCAAmC,GAAG,cAAc,CAAC;AAClE,MAAM,CAAC,MAAM,uCAAuC,GAAG,kBAAkB,CAAC;AAC1E,MAAM,CAAC,MAAM,gCAAgC,GAAG,WAAW,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license\n\n/**\n * AI MS Links.\n * @internal\n */\nexport const MS_LINKS = \"_MS.links\";\n/**\n * AI enqueued time attribute.\n * @internal\n */\nexport const ENQUEUED_TIME = \"enqueuedTime\";\n/**\n * AI time since enqueued attribute.\n * @internal\n */\nexport const TIME_SINCE_ENQUEUED = \"timeSinceEnqueued\";\n/**\n * AzureMonitorTraceExporter version.\n * @internal\n */\nexport const packageVersion = \"1.0.0-beta.24\";\n\nexport enum DependencyTypes {\n InProc = \"InProc\",\n QueueMessage = \"Queue Message\",\n Sql = \"SQL\",\n Http = \"Http\",\n Grpc = \"GRPC\",\n Wcf = \"WCF Service\",\n}\n\nexport const AzureMonitorSampleRate = \"_MS.sampleRate\";\nexport const ApplicationInsightsBaseType = \"_MS.baseType\";\n\nexport const ApplicationInsightsMessageName = \"Microsoft.ApplicationInsights.Message\";\nexport const ApplicationInsightsExceptionName = \"Microsoft.ApplicationInsights.Exception\";\nexport const ApplicationInsightsPageViewName = \"Microsoft.ApplicationInsights.PageView\";\nexport const ApplicationInsightsAvailabilityName = \"Microsoft.ApplicationInsights.Availability\";\nexport const ApplicationInsightsEventName = \"Microsoft.ApplicationInsights.Event\";\n\nexport const ApplicationInsightsMessageBaseType = \"MessageData\";\nexport const ApplicationInsightsExceptionBaseType = \"ExceptionData\";\nexport const ApplicationInsightsPageViewBaseType = \"PageViewData\";\nexport const ApplicationInsightsAvailabilityBaseType = \"AvailabilityData\";\nexport const ApplicationInsightsEventBaseType = \"EventData\";\n"]}
@@ -14,7 +14,7 @@ export function logToEnvelope(log, ikey) {
14
14
  const sampleRate = 100;
15
15
  const instrumentationKey = ikey;
16
16
  const tags = createTagsFromLog(log);
17
- const [properties, measurements] = createPropertiesFromLog(log);
17
+ let [properties, measurements] = createPropertiesFromLog(log);
18
18
  let name;
19
19
  let baseType;
20
20
  let baseData;
@@ -55,6 +55,7 @@ export function logToEnvelope(log, ikey) {
55
55
  baseType = String(log.attributes[ApplicationInsightsBaseType]);
56
56
  name = getLegacyApplicationInsightsName(log);
57
57
  baseData = getLegacyApplicationInsightsBaseData(log);
58
+ measurements = getLegacyApplicationInsightsMeasurements(log);
58
59
  if (!baseData) {
59
60
  // Failed to parse log
60
61
  return;
@@ -143,6 +144,14 @@ function getLegacyApplicationInsightsName(log) {
143
144
  }
144
145
  return name;
145
146
  }
147
+ function getLegacyApplicationInsightsMeasurements(log) {
148
+ var _a;
149
+ let measurements = {};
150
+ if ((_a = log.body) === null || _a === void 0 ? void 0 : _a.measurements) {
151
+ measurements = Object.assign({}, log.body.measurements);
152
+ }
153
+ return measurements;
154
+ }
146
155
  function getLegacyApplicationInsightsBaseData(log) {
147
156
  let baseData = {
148
157
  version: 2,
@@ -1 +1 @@
1
- {"version":3,"file":"logUtils.js","sourceRoot":"","sources":["../../../src/utils/logUtils.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAGL,mBAAmB,EACnB,kBAAkB,GAOnB,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,sBAAsB,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AAEhE,OAAO,EACL,0BAA0B,EAC1B,6BAA6B,EAC7B,uBAAuB,GACxB,MAAM,qCAAqC,CAAC;AAE7C,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAC1C,OAAO,EACL,uCAAuC,EACvC,mCAAmC,EACnC,2BAA2B,EAC3B,gCAAgC,EAChC,4BAA4B,EAC5B,oCAAoC,EACpC,gCAAgC,EAChC,kCAAkC,EAClC,8BAA8B,EAC9B,mCAAmC,EACnC,+BAA+B,GAChC,MAAM,iCAAiC,CAAC;AAEzC;;;GAGG;AACH,MAAM,UAAU,aAAa,CAAC,GAAsB,EAAE,IAAY;IAChE,MAAM,IAAI,GAAG,YAAY,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IACtC,MAAM,UAAU,GAAG,GAAG,CAAC;IACvB,MAAM,kBAAkB,GAAG,IAAI,CAAC;IAChC,MAAM,IAAI,GAAG,iBAAiB,CAAC,GAAG,CAAC,CAAC;IACpC,MAAM,CAAC,UAAU,EAAE,YAAY,CAAC,GAAG,uBAAuB,CAAC,GAAG,CAAC,CAAC;IAChE,IAAI,IAAY,CAAC;IAC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AO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n AvailabilityData,\n TelemetryItem as Envelope,\n KnownContextTagKeys,\n KnownSeverityLevel,\n MessageData,\n MonitorDomain,\n PageViewData,\n TelemetryEventData,\n TelemetryExceptionData,\n TelemetryExceptionDetails,\n} from \"../generated\";\nimport { createTagsFromResource, hrTimeToDate } from \"./common\";\nimport { ReadableLogRecord } from \"@opentelemetry/sdk-logs\";\nimport {\n SEMATTRS_EXCEPTION_MESSAGE,\n SEMATTRS_EXCEPTION_STACKTRACE,\n SEMATTRS_EXCEPTION_TYPE,\n} from \"@opentelemetry/semantic-conventions\";\nimport { Measurements, Properties, Tags } from \"../types\";\nimport { diag } from \"@opentelemetry/api\";\nimport {\n ApplicationInsightsAvailabilityBaseType,\n ApplicationInsightsAvailabilityName,\n ApplicationInsightsBaseType,\n ApplicationInsightsEventBaseType,\n ApplicationInsightsEventName,\n ApplicationInsightsExceptionBaseType,\n ApplicationInsightsExceptionName,\n ApplicationInsightsMessageBaseType,\n ApplicationInsightsMessageName,\n ApplicationInsightsPageViewBaseType,\n ApplicationInsightsPageViewName,\n} from \"./constants/applicationinsights\";\n\n/**\n * Log to Azure envelope parsing.\n * @internal\n */\nexport function logToEnvelope(log: ReadableLogRecord, ikey: string): Envelope | undefined {\n const time = hrTimeToDate(log.hrTime);\n const sampleRate = 100;\n const instrumentationKey = ikey;\n const tags = createTagsFromLog(log);\n const [properties, measurements] = createPropertiesFromLog(log);\n let name: string;\n let baseType: string;\n let baseData: MonitorDomain;\n\n if (!log.attributes[ApplicationInsightsBaseType]) {\n // Get Exception attributes if available\n const exceptionType = log.attributes[SEMATTRS_EXCEPTION_TYPE];\n if (exceptionType) {\n const exceptionMessage = log.attributes[SEMATTRS_EXCEPTION_MESSAGE];\n const exceptionStacktrace = log.attributes[SEMATTRS_EXCEPTION_STACKTRACE];\n name = ApplicationInsightsExceptionName;\n baseType = ApplicationInsightsExceptionBaseType;\n const exceptionDetails: TelemetryExceptionDetails = {\n typeName: String(exceptionType),\n message: String(exceptionMessage),\n hasFullStack: exceptionStacktrace ? true : false,\n stack: String(exceptionStacktrace),\n };\n const exceptionData: TelemetryExceptionData = {\n exceptions: [exceptionDetails],\n severityLevel: String(getSeverity(log.severityNumber)),\n version: 2,\n };\n baseData = exceptionData;\n } else {\n name = ApplicationInsightsMessageName;\n baseType = ApplicationInsightsMessageBaseType;\n const messageData: MessageData = {\n message: String(log.body),\n severityLevel: String(getSeverity(log.severityNumber)),\n version: 2,\n };\n baseData = messageData;\n }\n } else {\n // If Legacy Application Insights Log\n baseType = String(log.attributes[ApplicationInsightsBaseType]);\n name = getLegacyApplicationInsightsName(log);\n baseData = getLegacyApplicationInsightsBaseData(log);\n if (!baseData) {\n // Failed to parse log\n return;\n }\n }\n return {\n name,\n sampleRate,\n time,\n instrumentationKey,\n tags,\n version: 1,\n data: {\n baseType,\n baseData: {\n ...baseData,\n properties,\n measurements,\n },\n },\n };\n}\n\nfunction createTagsFromLog(log: ReadableLogRecord): Tags {\n const tags: Tags = createTagsFromResource(log.resource);\n if (log.spanContext?.traceId) {\n tags[KnownContextTagKeys.AiOperationId] = log.spanContext.traceId;\n }\n if (log.spanContext?.spanId) {\n tags[KnownContextTagKeys.AiOperationParentId] = log.spanContext.spanId;\n }\n return tags;\n}\n\nfunction createPropertiesFromLog(log: ReadableLogRecord): [Properties, Measurements] {\n const measurements: Measurements = {};\n const properties: { [propertyName: string]: string } = {};\n if (log.attributes) {\n for (const key of Object.keys(log.attributes)) {\n // Avoid duplication ignoring fields already mapped.\n if (\n !(\n key.startsWith(\"_MS.\") ||\n key === SEMATTRS_EXCEPTION_TYPE ||\n key === SEMATTRS_EXCEPTION_MESSAGE ||\n key === SEMATTRS_EXCEPTION_STACKTRACE\n )\n ) {\n properties[key] = log.attributes[key] as string;\n }\n }\n }\n return [properties, measurements];\n}\n\n// https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/logs/data-model.md#field-severitynumber\nfunction getSeverity(severityNumber: number | undefined): KnownSeverityLevel | undefined {\n if (severityNumber) {\n if (severityNumber > 0 && severityNumber < 9) {\n return KnownSeverityLevel.Verbose;\n } else if (severityNumber >= 9 && severityNumber < 13) {\n return KnownSeverityLevel.Information;\n } else if (severityNumber >= 13 && severityNumber < 17) {\n return KnownSeverityLevel.Warning;\n } else if (severityNumber >= 17 && severityNumber < 21) {\n return KnownSeverityLevel.Error;\n } else if (severityNumber >= 21 && severityNumber < 25) {\n return KnownSeverityLevel.Critical;\n }\n }\n return;\n}\n\nfunction getLegacyApplicationInsightsName(log: ReadableLogRecord): string {\n let name = \"\";\n switch (log.attributes[ApplicationInsightsBaseType]) {\n case ApplicationInsightsAvailabilityBaseType:\n name = ApplicationInsightsAvailabilityName;\n break;\n case ApplicationInsightsExceptionBaseType:\n name = ApplicationInsightsExceptionName;\n break;\n case ApplicationInsightsMessageBaseType:\n name = ApplicationInsightsMessageName;\n break;\n case ApplicationInsightsPageViewBaseType:\n name = ApplicationInsightsPageViewName;\n break;\n case ApplicationInsightsEventBaseType:\n name = ApplicationInsightsEventName;\n break;\n }\n return name;\n}\n\nfunction getLegacyApplicationInsightsBaseData(log: ReadableLogRecord): MonitorDomain {\n let baseData: MonitorDomain = {\n version: 2,\n };\n if (log.body) {\n try {\n switch (log.attributes[ApplicationInsightsBaseType]) {\n case ApplicationInsightsAvailabilityBaseType:\n baseData = log.body as AvailabilityData;\n break;\n case ApplicationInsightsExceptionBaseType:\n baseData = log.body as TelemetryExceptionData;\n break;\n case ApplicationInsightsMessageBaseType:\n baseData = log.body as MessageData;\n break;\n case ApplicationInsightsPageViewBaseType:\n baseData = log.body as PageViewData;\n break;\n case ApplicationInsightsEventBaseType:\n baseData = log.body as TelemetryEventData;\n break;\n }\n if (typeof baseData?.message === \"object\") {\n baseData.message = JSON.stringify(baseData.message);\n }\n } catch (err) {\n diag.error(\"AzureMonitorLogExporter failed to parse Application Insights Telemetry\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QACvF,CAAC;IACH,CAAC;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n AvailabilityData,\n TelemetryItem as Envelope,\n KnownContextTagKeys,\n KnownSeverityLevel,\n MessageData,\n MonitorDomain,\n PageViewData,\n TelemetryEventData,\n TelemetryExceptionData,\n TelemetryExceptionDetails,\n} from \"../generated\";\nimport { createTagsFromResource, hrTimeToDate } from \"./common\";\nimport { ReadableLogRecord } from \"@opentelemetry/sdk-logs\";\nimport {\n SEMATTRS_EXCEPTION_MESSAGE,\n SEMATTRS_EXCEPTION_STACKTRACE,\n SEMATTRS_EXCEPTION_TYPE,\n} from \"@opentelemetry/semantic-conventions\";\nimport { Measurements, Properties, Tags } from \"../types\";\nimport { diag } from \"@opentelemetry/api\";\nimport {\n ApplicationInsightsAvailabilityBaseType,\n ApplicationInsightsAvailabilityName,\n ApplicationInsightsBaseType,\n ApplicationInsightsEventBaseType,\n ApplicationInsightsEventName,\n ApplicationInsightsExceptionBaseType,\n ApplicationInsightsExceptionName,\n ApplicationInsightsMessageBaseType,\n ApplicationInsightsMessageName,\n ApplicationInsightsPageViewBaseType,\n ApplicationInsightsPageViewName,\n} from \"./constants/applicationinsights\";\n\n/**\n * Log to Azure envelope parsing.\n * @internal\n */\nexport function logToEnvelope(log: ReadableLogRecord, ikey: string): Envelope | undefined {\n const time = hrTimeToDate(log.hrTime);\n const sampleRate = 100;\n const instrumentationKey = ikey;\n const tags = createTagsFromLog(log);\n let [properties, measurements] = createPropertiesFromLog(log);\n let name: string;\n let baseType: string;\n let baseData: MonitorDomain;\n\n if (!log.attributes[ApplicationInsightsBaseType]) {\n // Get Exception attributes if available\n const exceptionType = log.attributes[SEMATTRS_EXCEPTION_TYPE];\n if (exceptionType) {\n const exceptionMessage = log.attributes[SEMATTRS_EXCEPTION_MESSAGE];\n const exceptionStacktrace = log.attributes[SEMATTRS_EXCEPTION_STACKTRACE];\n name = ApplicationInsightsExceptionName;\n baseType = ApplicationInsightsExceptionBaseType;\n const exceptionDetails: TelemetryExceptionDetails = {\n typeName: String(exceptionType),\n message: String(exceptionMessage),\n hasFullStack: exceptionStacktrace ? true : false,\n stack: String(exceptionStacktrace),\n };\n const exceptionData: TelemetryExceptionData = {\n exceptions: [exceptionDetails],\n severityLevel: String(getSeverity(log.severityNumber)),\n version: 2,\n };\n baseData = exceptionData;\n } else {\n name = ApplicationInsightsMessageName;\n baseType = ApplicationInsightsMessageBaseType;\n const messageData: MessageData = {\n message: String(log.body),\n severityLevel: String(getSeverity(log.severityNumber)),\n version: 2,\n };\n baseData = messageData;\n }\n } else {\n // If Legacy Application Insights Log\n baseType = String(log.attributes[ApplicationInsightsBaseType]);\n name = getLegacyApplicationInsightsName(log);\n baseData = getLegacyApplicationInsightsBaseData(log);\n measurements = getLegacyApplicationInsightsMeasurements(log);\n if (!baseData) {\n // Failed to parse log\n return;\n }\n }\n return {\n name,\n sampleRate,\n time,\n instrumentationKey,\n tags,\n version: 1,\n data: {\n baseType,\n baseData: {\n ...baseData,\n properties,\n measurements,\n },\n },\n };\n}\n\nfunction createTagsFromLog(log: ReadableLogRecord): Tags {\n const tags: Tags = createTagsFromResource(log.resource);\n if (log.spanContext?.traceId) {\n tags[KnownContextTagKeys.AiOperationId] = log.spanContext.traceId;\n }\n if (log.spanContext?.spanId) {\n tags[KnownContextTagKeys.AiOperationParentId] = log.spanContext.spanId;\n }\n return tags;\n}\n\nfunction createPropertiesFromLog(log: ReadableLogRecord): [Properties, Measurements] {\n const measurements: Measurements = {};\n const properties: { [propertyName: string]: string } = {};\n if (log.attributes) {\n for (const key of Object.keys(log.attributes)) {\n // Avoid duplication ignoring fields already mapped.\n if (\n !(\n key.startsWith(\"_MS.\") ||\n key === SEMATTRS_EXCEPTION_TYPE ||\n key === SEMATTRS_EXCEPTION_MESSAGE ||\n key === SEMATTRS_EXCEPTION_STACKTRACE\n )\n ) {\n properties[key] = log.attributes[key] as string;\n }\n }\n }\n return [properties, measurements];\n}\n\n// https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/logs/data-model.md#field-severitynumber\nfunction getSeverity(severityNumber: number | undefined): KnownSeverityLevel | undefined {\n if (severityNumber) {\n if (severityNumber > 0 && severityNumber < 9) {\n return KnownSeverityLevel.Verbose;\n } else if (severityNumber >= 9 && severityNumber < 13) {\n return KnownSeverityLevel.Information;\n } else if (severityNumber >= 13 && severityNumber < 17) {\n return KnownSeverityLevel.Warning;\n } else if (severityNumber >= 17 && severityNumber < 21) {\n return KnownSeverityLevel.Error;\n } else if (severityNumber >= 21 && severityNumber < 25) {\n return KnownSeverityLevel.Critical;\n }\n }\n return;\n}\n\nfunction getLegacyApplicationInsightsName(log: ReadableLogRecord): string {\n let name = \"\";\n switch (log.attributes[ApplicationInsightsBaseType]) {\n case ApplicationInsightsAvailabilityBaseType:\n name = ApplicationInsightsAvailabilityName;\n break;\n case ApplicationInsightsExceptionBaseType:\n name = ApplicationInsightsExceptionName;\n break;\n case ApplicationInsightsMessageBaseType:\n name = ApplicationInsightsMessageName;\n break;\n case ApplicationInsightsPageViewBaseType:\n name = ApplicationInsightsPageViewName;\n break;\n case ApplicationInsightsEventBaseType:\n name = ApplicationInsightsEventName;\n break;\n }\n return name;\n}\n\nfunction getLegacyApplicationInsightsMeasurements(log: ReadableLogRecord): Measurements {\n let measurements: Measurements = {};\n if ((log.body as MonitorDomain)?.measurements) {\n measurements = { ...(log.body as MonitorDomain).measurements };\n }\n return measurements;\n}\n\nfunction getLegacyApplicationInsightsBaseData(log: ReadableLogRecord): MonitorDomain {\n let baseData: MonitorDomain = {\n version: 2,\n };\n if (log.body) {\n try {\n switch (log.attributes[ApplicationInsightsBaseType]) {\n case ApplicationInsightsAvailabilityBaseType:\n baseData = log.body as AvailabilityData;\n break;\n case ApplicationInsightsExceptionBaseType:\n baseData = log.body as TelemetryExceptionData;\n break;\n case ApplicationInsightsMessageBaseType:\n baseData = log.body as MessageData;\n break;\n case ApplicationInsightsPageViewBaseType:\n baseData = log.body as PageViewData;\n break;\n case ApplicationInsightsEventBaseType:\n baseData = log.body as TelemetryEventData;\n break;\n }\n if (typeof baseData?.message === \"object\") {\n baseData.message = JSON.stringify(baseData.message);\n }\n } catch (err) {\n diag.error(\"AzureMonitorLogExporter failed to parse Application Insights Telemetry\");\n }\n }\n return baseData;\n}\n"]}
@@ -2,6 +2,15 @@
2
2
  // Licensed under the MIT license.
3
3
  import { DataPointType } from "@opentelemetry/sdk-metrics";
4
4
  import { createTagsFromResource } from "./common";
5
+ import { BreezePerformanceCounterNames, OTelPerformanceCounterNames } from "../types";
6
+ const breezePerformanceCountersMap = new Map([
7
+ [OTelPerformanceCounterNames.PRIVATE_BYTES, BreezePerformanceCounterNames.PRIVATE_BYTES],
8
+ [OTelPerformanceCounterNames.AVAILABLE_BYTES, BreezePerformanceCounterNames.AVAILABLE_BYTES],
9
+ [OTelPerformanceCounterNames.PROCESSOR_TIME, BreezePerformanceCounterNames.PROCESSOR_TIME],
10
+ [OTelPerformanceCounterNames.PROCESS_TIME, BreezePerformanceCounterNames.PROCESS_TIME],
11
+ [OTelPerformanceCounterNames.REQUEST_RATE, BreezePerformanceCounterNames.REQUEST_RATE],
12
+ [OTelPerformanceCounterNames.REQUEST_DURATION, BreezePerformanceCounterNames.REQUEST_DURATION],
13
+ ]);
5
14
  function createPropertiesFromMetricAttributes(attributes) {
6
15
  const properties = {};
7
16
  if (attributes) {
@@ -36,8 +45,12 @@ export function resourceMetricsToEnvelope(metrics, ikey, isStatsbeat) {
36
45
  properties: {},
37
46
  };
38
47
  baseData.properties = createPropertiesFromMetricAttributes(dataPoint.attributes);
48
+ let perfCounterName;
49
+ if (breezePerformanceCountersMap.has(metric.descriptor.name)) {
50
+ perfCounterName = breezePerformanceCountersMap.get(metric.descriptor.name);
51
+ }
39
52
  const metricDataPoint = {
40
- name: metric.descriptor.name,
53
+ name: perfCounterName ? perfCounterName : metric.descriptor.name,
41
54
  value: 0,
42
55
  dataPointType: "Aggregation",
43
56
  };
@@ -1 +1 @@
1
- {"version":3,"file":"metricUtils.js","sourceRoot":"","sources":["../../../src/utils/metricUtils.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,aAAa,EAA8B,MAAM,4BAA4B,CAAC;AAEvF,OAAO,EAAE,sBAAsB,EAAE,MAAM,UAAU,CAAC;AAElD,SAAS,oCAAoC,CAAC,UAAuB;IAGnE,MAAM,UAAU,GAAuC,EAAE,CAAC;IAC1D,IAAI,UAAU,EAAE,CAAC;QACf,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,EAAE,CAAC;YAC1C,UAAU,CAAC,GAAG,CAAC,GAAG,UAAU,CAAC,GAAG,CAAW,CAAC;QAC9C,CAAC;IACH,CAAC;IACD,OAAO,UAAU,CAAC;AACpB,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,yBAAyB,CACvC,OAAwB,EACxB,IAAY,EACZ,WAAqB;IAErB,MAAM,SAAS,GAAe,EAAE,CAAC;IACjC,MAAM,IAAI,GAAG,IAAI,IAAI,EAAE,CAAC;IACxB,MAAM,kBAAkB,GAAG,IAAI,CAAC;IAChC,MAAM,IAAI,GAAG,sBAAsB,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;IACtD,IAAI,YAAoB,CAAC;IAEzB,IAAI,WAAW,EAAE,CAAC;QAChB,YAAY,GAAG,yCAAyC,CAAC;IAC3D,CAAC;SAAM,CAAC;QACN,YAAY,GAAG,sCAAsC,CAAC;IACxD,CAAC;IAED,OAAO,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC,WAAW,EAAE,EAAE;QAC3C,WAAW,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,EAAE;YACrC,MAAM,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,SAAS,EAAE,EAAE;gBACtC,MAAM,QAAQ,GAAgB;oBAC5B,OAAO,EAAE,EA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,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;IAEH,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { Attributes } from \"@opentelemetry/api\";\nimport { DataPointType, Histogram, ResourceMetrics } from \"@opentelemetry/sdk-metrics\";\nimport { TelemetryItem as Envelope, MetricsData, MetricDataPoint } from \"../generated\";\nimport { createTagsFromResource } from \"./common\";\n\nfunction createPropertiesFromMetricAttributes(attributes?: Attributes): {\n [propertyName: string]: string;\n} {\n const properties: { [propertyName: string]: string } = {};\n if (attributes) {\n for (const key of Object.keys(attributes)) {\n properties[key] = attributes[key] as string;\n }\n }\n return properties;\n}\n\n/**\n * Metric to Azure envelope parsing.\n * @internal\n */\nexport function resourceMetricsToEnvelope(\n metrics: ResourceMetrics,\n ikey: string,\n isStatsbeat?: boolean,\n): Envelope[] {\n const envelopes: Envelope[] = [];\n const time = new Date();\n const instrumentationKey = ikey;\n const tags = createTagsFromResource(metrics.resource);\n let envelopeName: string;\n\n if (isStatsbeat) {\n envelopeName = \"Microsoft.ApplicationInsights.Statsbeat\";\n } else {\n envelopeName = \"Microsoft.ApplicationInsights.Metric\";\n }\n\n metrics.scopeMetrics.forEach((scopeMetric) => {\n scopeMetric.metrics.forEach((metric) => {\n metric.dataPoints.forEach((dataPoint) => {\n const baseData: MetricsData = {\n metrics: [],\n version: 2,\n properties: {},\n };\n baseData.properties = createPropertiesFromMetricAttributes(dataPoint.attributes);\n const metricDataPoint: MetricDataPoint = {\n name: metric.descriptor.name,\n value: 0,\n dataPointType: \"Aggregation\",\n };\n if (\n metric.dataPointType === DataPointType.SUM ||\n metric.dataPointType === DataPointType.GAUGE\n ) {\n metricDataPoint.value = dataPoint.value as number;\n metricDataPoint.count = 1;\n } else {\n metricDataPoint.value = (dataPoint.value as Histogram).sum || 0;\n metricDataPoint.count = (dataPoint.value as Histogram).count;\n metricDataPoint.max = (dataPoint.value as Histogram).max;\n metricDataPoint.min = (dataPoint.value as Histogram).min;\n }\n baseData.metrics.push(metricDataPoint);\n const envelope: Envelope = {\n name: envelopeName,\n time: time,\n sampleRate: 100, // Metrics are never sampled\n instrumentationKey: instrumentationKey,\n tags: tags,\n version: 1,\n data: {\n baseType: \"MetricData\",\n baseData: {\n ...baseData,\n },\n },\n };\n envelopes.push(envelope);\n });\n });\n });\n\n return envelopes;\n}\n"]}
1
+ {"version":3,"file":"metricUtils.js","sourceRoot":"","sources":["../../../src/utils/metricUtils.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,aAAa,EAA8B,MAAM,4BAA4B,CAAC;AAEvF,OAAO,EAAE,sBAAsB,EAAE,MAAM,UAAU,CAAC;AAClD,OAAO,EAAE,6BAA6B,EAAE,2BAA2B,EAAE,MAAM,UAAU,CAAC;AAEtF,MAAM,4BAA4B,GAAG,IAAI,GAAG,CAAiB;IAC3D,CAAC,2BAA2B,CAAC,aAAa,EAAE,6BAA6B,CAAC,aAAa,CAAC;IACxF,CAAC,2BAA2B,CAAC,eAAe,EAAE,6BAA6B,CAAC,eAAe,CAAC;IAC5F,CAAC,2BAA2B,CAAC,cAAc,EAAE,6BAA6B,CAAC,cAAc,CAAC;IAC1F,CAAC,2BAA2B,CAAC,YAAY,EAAE,6BAA6B,CAAC,YAAY,CAAC;IACtF,CAAC,2BAA2B,CAAC,YAAY,EAAE,6BAA6B,CAAC,YAAY,CAAC;IACtF,CAAC,2BAA2B,CAAC,gBAAgB,EAAE,6BAA6B,CAAC,gBAAgB,CAAC;CAC/F,CAAC,CAAC;AAEH,SAAS,oCAAoC,CAAC,UAAuB;IAGnE,MAAM,UAAU,GAAuC,EAAE,CAAC;IAC1D,IAAI,UAAU,EAAE,CAAC;QACf,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,EAAE,CAAC;YAC1C,UAAU,CAAC,GAAG,CAA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C,UAAU,CAAC,IAAI;oBAChE,KAAK,EAAE,CAAC;oBACR,aAAa,EAAE,aAAa;iBAC7B,CAAC;gBACF,IACE,MAAM,CAAC,aAAa,KAAK,aAAa,CAAC,GAAG;oBAC1C,MAAM,CAAC,aAAa,KAAK,aAAa,CAAC,KAAK,EAC5C,CAAC;oBACD,eAAe,CAAC,KAAK,GAAG,SAAS,CAAC,KAAe,CAAC;oBAClD,eAAe,CAAC,KAAK,GAAG,CAAC,CAAC;gBAC5B,CAAC;qBAAM,CAAC;oBACN,eAAe,CAAC,KAAK,GAAI,SAAS,CAAC,KAAmB,CAAC,GAAG,IAAI,CAAC,CAAC;oBAChE,eAAe,CAAC,KAAK,GAAI,SAAS,CAAC,KAAmB,CAAC,KAAK,CAAC;oBAC7D,eAAe,CAAC,GAAG,GAAI,SAAS,CAAC,KAAmB,CAAC,GAAG,CAAC;oBACzD,eAAe,CAAC,GAAG,GAAI,SAAS,CAAC,KAAmB,CAAC,GAAG,CAAC;gBAC3D,CAAC;gBACD,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC;gBACvC,MAAM,QAAQ,GAAa;oBACzB,IAAI,EAAE,YAAY;oBAClB,IAAI,EAAE,IAAI;oBACV,UAAU,EAAE,GAAG,EAAE,4BAA4B;oBAC7C,kBAAkB,EAAE,kBAAkB;oBACtC,IAAI,EAAE,IAAI;oBACV,OAAO,EAAE,CAAC;oBACV,IAAI,EAAE;wBACJ,QAAQ,EAAE,YAAY;wBACtB,QAAQ,oBACH,QAAQ,CACZ;qBACF;iBACF,CAAC;gBACF,SAAS,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;YAC3B,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;IAEH,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { Attributes } from \"@opentelemetry/api\";\nimport { DataPointType, Histogram, ResourceMetrics } from \"@opentelemetry/sdk-metrics\";\nimport { TelemetryItem as Envelope, MetricsData, MetricDataPoint } from \"../generated\";\nimport { createTagsFromResource } from \"./common\";\nimport { BreezePerformanceCounterNames, OTelPerformanceCounterNames } from \"../types\";\n\nconst breezePerformanceCountersMap = new Map<string, string>([\n [OTelPerformanceCounterNames.PRIVATE_BYTES, BreezePerformanceCounterNames.PRIVATE_BYTES],\n [OTelPerformanceCounterNames.AVAILABLE_BYTES, BreezePerformanceCounterNames.AVAILABLE_BYTES],\n [OTelPerformanceCounterNames.PROCESSOR_TIME, BreezePerformanceCounterNames.PROCESSOR_TIME],\n [OTelPerformanceCounterNames.PROCESS_TIME, BreezePerformanceCounterNames.PROCESS_TIME],\n [OTelPerformanceCounterNames.REQUEST_RATE, BreezePerformanceCounterNames.REQUEST_RATE],\n [OTelPerformanceCounterNames.REQUEST_DURATION, BreezePerformanceCounterNames.REQUEST_DURATION],\n]);\n\nfunction createPropertiesFromMetricAttributes(attributes?: Attributes): {\n [propertyName: string]: string;\n} {\n const properties: { [propertyName: string]: string } = {};\n if (attributes) {\n for (const key of Object.keys(attributes)) {\n properties[key] = attributes[key] as string;\n }\n }\n return properties;\n}\n\n/**\n * Metric to Azure envelope parsing.\n * @internal\n */\nexport function resourceMetricsToEnvelope(\n metrics: ResourceMetrics,\n ikey: string,\n isStatsbeat?: boolean,\n): Envelope[] {\n const envelopes: Envelope[] = [];\n const time = new Date();\n const instrumentationKey = ikey;\n const tags = createTagsFromResource(metrics.resource);\n let envelopeName: string;\n\n if (isStatsbeat) {\n envelopeName = \"Microsoft.ApplicationInsights.Statsbeat\";\n } else {\n envelopeName = \"Microsoft.ApplicationInsights.Metric\";\n }\n\n metrics.scopeMetrics.forEach((scopeMetric) => {\n scopeMetric.metrics.forEach((metric) => {\n metric.dataPoints.forEach((dataPoint) => {\n const baseData: MetricsData = {\n metrics: [],\n version: 2,\n properties: {},\n };\n baseData.properties = createPropertiesFromMetricAttributes(dataPoint.attributes);\n let perfCounterName;\n if (breezePerformanceCountersMap.has(metric.descriptor.name)) {\n perfCounterName = breezePerformanceCountersMap.get(metric.descriptor.name);\n }\n const metricDataPoint: MetricDataPoint = {\n name: perfCounterName ? perfCounterName : metric.descriptor.name,\n value: 0,\n dataPointType: \"Aggregation\",\n };\n if (\n metric.dataPointType === DataPointType.SUM ||\n metric.dataPointType === DataPointType.GAUGE\n ) {\n metricDataPoint.value = dataPoint.value as number;\n metricDataPoint.count = 1;\n } else {\n metricDataPoint.value = (dataPoint.value as Histogram).sum || 0;\n metricDataPoint.count = (dataPoint.value as Histogram).count;\n metricDataPoint.max = (dataPoint.value as Histogram).max;\n metricDataPoint.min = (dataPoint.value as Histogram).min;\n }\n baseData.metrics.push(metricDataPoint);\n const envelope: Envelope = {\n name: envelopeName,\n time: time,\n sampleRate: 100, // Metrics are never sampled\n instrumentationKey: instrumentationKey,\n tags: tags,\n version: 1,\n data: {\n baseType: \"MetricData\",\n baseData: {\n ...baseData,\n },\n },\n };\n envelopes.push(envelope);\n });\n });\n });\n\n return envelopes;\n}\n"]}
@@ -221,7 +221,8 @@ function createDependencyData(span) {
221
221
  function createRequestData(span) {
222
222
  const requestData = {
223
223
  id: `${span.spanContext().spanId}`,
224
- success: span.status.code !== SpanStatusCode.ERROR,
224
+ success: span.status.code !== SpanStatusCode.ERROR &&
225
+ (Number(span.attributes[SEMATTRS_HTTP_STATUS_CODE]) || 0) < 400,
225
226
  responseCode: "0",
226
227
  duration: msToTimeSpan(hrTimeToMilliseconds(span.duration)),
227
228
  version: 2,
@@ -321,40 +322,46 @@ export function spanEventsToEnvelopes(span, ikey) {
321
322
  tags[KnownContextTagKeys.AiOperationParentId] = spanId;
322
323
  }
323
324
  // Only generate exception telemetry for incoming requests
324
- if (event.name === "exception" && span.kind === SpanKind.SERVER) {
325
- name = "Microsoft.ApplicationInsights.Exception";
326
- baseType = "ExceptionData";
327
- let typeName = "";
328
- let message = "Exception";
329
- let stack = "";
330
- let hasFullStack = false;
331
- if (event.attributes) {
332
- typeName = String(event.attributes[SEMATTRS_EXCEPTION_TYPE]);
333
- stack = String(event.attributes[SEMATTRS_EXCEPTION_STACKTRACE]);
334
- if (stack) {
335
- hasFullStack = true;
336
- }
337
- const exceptionMsg = event.attributes[SEMATTRS_EXCEPTION_MESSAGE];
338
- if (exceptionMsg) {
339
- message = String(exceptionMsg);
340
- }
341
- const escaped = event.attributes[SEMATTRS_EXCEPTION_ESCAPED];
342
- if (escaped !== undefined) {
343
- properties[SEMATTRS_EXCEPTION_ESCAPED] = String(escaped);
325
+ if (event.name === "exception") {
326
+ if (span.kind === SpanKind.SERVER) {
327
+ name = "Microsoft.ApplicationInsights.Exception";
328
+ baseType = "ExceptionData";
329
+ let typeName = "";
330
+ let message = "Exception";
331
+ let stack = "";
332
+ let hasFullStack = false;
333
+ if (event.attributes) {
334
+ typeName = String(event.attributes[SEMATTRS_EXCEPTION_TYPE]);
335
+ stack = String(event.attributes[SEMATTRS_EXCEPTION_STACKTRACE]);
336
+ if (stack) {
337
+ hasFullStack = true;
338
+ }
339
+ const exceptionMsg = event.attributes[SEMATTRS_EXCEPTION_MESSAGE];
340
+ if (exceptionMsg) {
341
+ message = String(exceptionMsg);
342
+ }
343
+ const escaped = event.attributes[SEMATTRS_EXCEPTION_ESCAPED];
344
+ if (escaped !== undefined) {
345
+ properties[SEMATTRS_EXCEPTION_ESCAPED] = String(escaped);
346
+ }
344
347
  }
348
+ const exceptionDetails = {
349
+ typeName: typeName,
350
+ message: message,
351
+ stack: stack,
352
+ hasFullStack: hasFullStack,
353
+ };
354
+ const exceptionData = {
355
+ exceptions: [exceptionDetails],
356
+ version: 2,
357
+ properties: properties,
358
+ };
359
+ baseData = exceptionData;
360
+ }
361
+ else {
362
+ // Drop non-server exception span events
363
+ return;
345
364
  }
346
- const exceptionDetails = {
347
- typeName: typeName,
348
- message: message,
349
- stack: stack,
350
- hasFullStack: hasFullStack,
351
- };
352
- const exceptionData = {
353
- exceptions: [exceptionDetails],
354
- version: 2,
355
- properties: properties,
356
- };
357
- baseData = exceptionData;
358
365
  }
359
366
  else {
360
367
  name = "Microsoft.ApplicationInsights.Message";
@@ -1 +1 @@
1
- {"version":3,"file":"spanUtils.js","sourceRoot":"","sources":["../../../src/utils/spanUtils.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,GAAG,EAAE,MAAM,KAAK,CAAC;AAE1B,OAAO,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AAC3D,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,cAAc,EAAoB,MAAM,oBAAoB,CAAC;AACtF,OAAO,EACL,sBAAsB,EACtB,oBAAoB,EACpB,yBAAyB,EACzB,oBAAoB,EACpB,gBAAgB,EAChB,qBAAqB,EACrB,qBAAqB,EACrB,kBAAkB,EAClB,mBAAmB,EACnB,0BAA0B,EAC1B,0BAA0B,EAC1B,6BAA6B,EAC7B,uBAAuB,EACvB,uBAAuB,EACvB,kBAAkB,EAClB,oBAAoB,EACpB,mBAAmB,EACnB,yBAAyB,EACzB,iBAAiB,EACjB,wBAAwB,EACxB,oBAAoB,EACpB,sBAAsB,EACtB,qBAAqB,EACrB,6BAA6B,EAC7B,mBAAmB,GACpB,MAAM,qCAAqC,CAAC;AAE7C,OAAO,EACL,sBAAsB,EACtB,mBAAmB,EACnB,MAAM,EACN,YAAY,EACZ,OAAO,GACR,MAAM,UAAU,CAAC;AAElB,OAAO,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAC/C,OAAO,EAAE,sBAAsB,EAAE,eAAe,EAAE,QAAQ,EAAE,MAAM,iCAAiC,CAAC;AACpG,OAAO,EAAE,WAAW,EAAE,iBAAiB,EAAE,MAAM,+BAA+B,CAAC;AAC/E,OAAO,EAML,mBAAmB,GAEpB,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAE7C,SAAS,kBAAkB,CAAC,IAAkB;IA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,GAAG,WAAW,CAAC;YACzB,CAAC;YACD,IAAI,UAAU,GAAG,GAAG,CAAC;YACrB,IAAI,IAAI,CAAC,UAAU,CAAC,sBAAsB,CAAC,EAAE,CAAC;gBAC5C,UAAU,GAAG,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,sBAAsB,CAAC,CAAC,CAAC;YAC/D,CAAC;YACD,MAAM,GAAG,GAAa;gBACpB,IAAI,EAAE,IAAI;gBACV,IAAI,EAAE,IAAI;gBACV,kBAAkB,EAAE,IAAI;gBACxB,OAAO,EAAE,CAAC;gBACV,UAAU,EAAE,UAAU;gBACtB,IAAI,EAAE;oBACJ,QAAQ,EAAE,QAAQ;oBAClB,QAAQ,EAAE,QAAQ;iBACnB;gBACD,IAAI,EAAE,IAAI;aACX,CAAC;YACF,SAAS,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QACtB,CAAC,CAAC,CAAC;IACL,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { URL } from \"url\";\nimport { ReadableSpan, TimedEvent } from \"@opentelemetry/sdk-trace-base\";\nimport { hrTimeToMilliseconds } from \"@opentelemetry/core\";\nimport { diag, SpanKind, SpanStatusCode, Link, Attributes } from \"@opentelemetry/api\";\nimport {\n DBSYSTEMVALUES_MONGODB,\n DBSYSTEMVALUES_MYSQL,\n DBSYSTEMVALUES_POSTGRESQL,\n DBSYSTEMVALUES_REDIS,\n SEMATTRS_DB_NAME,\n SEMATTRS_DB_OPERATION,\n SEMATTRS_DB_STATEMENT,\n SEMATTRS_DB_SYSTEM,\n SEMATTRS_ENDUSER_ID,\n SEMATTRS_EXCEPTION_ESCAPED,\n SEMATTRS_EXCEPTION_MESSAGE,\n SEMATTRS_EXCEPTION_STACKTRACE,\n SEMATTRS_EXCEPTION_TYPE,\n SEMATTRS_HTTP_CLIENT_IP,\n SEMATTRS_HTTP_HOST,\n SEMATTRS_HTTP_METHOD,\n SEMATTRS_HTTP_ROUTE,\n SEMATTRS_HTTP_STATUS_CODE,\n SEMATTRS_HTTP_URL,\n SEMATTRS_HTTP_USER_AGENT,\n SEMATTRS_NET_PEER_IP,\n SEMATTRS_NET_PEER_NAME,\n SEMATTRS_PEER_SERVICE,\n SEMATTRS_RPC_GRPC_STATUS_CODE,\n SEMATTRS_RPC_SYSTEM,\n} from \"@opentelemetry/semantic-conventions\";\n\nimport {\n createTagsFromResource,\n getDependencyTarget,\n getUrl,\n hrTimeToDate,\n isSqlDB,\n} from \"./common\";\nimport { Tags, Properties, MSLink, Measurements } from \"../types\";\nimport { parseEventHubSpan } from \"./eventhub\";\nimport { AzureMonitorSampleRate, DependencyTypes, MS_LINKS } from \"./constants/applicationinsights\";\nimport { AzNamespace, MicrosoftEventHub } from \"./constants/span/azAttributes\";\nimport {\n TelemetryExceptionData,\n MessageData,\n RemoteDependencyData,\n RequestData,\n TelemetryItem as Envelope,\n KnownContextTagKeys,\n TelemetryExceptionDetails,\n} from \"../generated\";\nimport { msToTimeSpan } from \"./breezeUtils\";\n\nfunction createTagsFromSpan(span: ReadableSpan): Tags {\n const tags: Tags = createTagsFromResource(span.resource);\n tags[KnownContextTagKeys.AiOperationId] = span.spanContext().traceId;\n if (span.parentSpanId) {\n tags[KnownContextTagKeys.AiOperationParentId] = span.parentSpanId;\n }\n const endUserId = span.attributes[SEMATTRS_ENDUSER_ID];\n if (endUserId) {\n tags[KnownContextTagKeys.AiUserId] = String(endUserId);\n }\n const httpUserAgent = span.attributes[SEMATTRS_HTTP_USER_AGENT];\n if (httpUserAgent) {\n // TODO: Not exposed in Swagger, need to update def\n tags[\"ai.user.userAgent\"] = String(httpUserAgent);\n }\n if (span.kind === SpanKind.SERVER) {\n const httpMethod = span.attributes[SEMATTRS_HTTP_METHOD];\n const httpClientIp = span.attributes[SEMATTRS_HTTP_CLIENT_IP];\n const netPeerIp = span.attributes[SEMATTRS_NET_PEER_IP];\n if (httpMethod) {\n const httpRoute = span.attributes[SEMATTRS_HTTP_ROUTE];\n const httpUrl = span.attributes[SEMATTRS_HTTP_URL];\n tags[KnownContextTagKeys.AiOperationName] = span.name; // Default\n if (httpRoute) {\n tags[KnownContextTagKeys.AiOperationName] = `${httpMethod as string} ${\n httpRoute as string\n }`;\n } else if (httpUrl) {\n try {\n const url = new URL(String(httpUrl));\n tags[KnownContextTagKeys.AiOperationName] = `${httpMethod} ${url.pathname}`;\n } catch (ex: any) {}\n }\n if (httpClientIp) {\n tags[KnownContextTagKeys.AiLocationIp] = String(httpClientIp);\n } else if (netPeerIp) {\n tags[KnownContextTagKeys.AiLocationIp] = String(netPeerIp);\n }\n } else {\n tags[KnownContextTagKeys.AiOperationName] = span.name;\n if (netPeerIp) {\n tags[KnownContextTagKeys.AiLocationIp] = String(netPeerIp);\n }\n }\n }\n // TODO: Operation Name and Location IP TBD for non server spans\n\n return tags;\n}\n\nfunction createPropertiesFromSpanAttributes(attributes?: Attributes): {\n [propertyName: string]: string;\n} {\n const properties: { [propertyName: string]: string } = {};\n if (attributes) {\n for (const key of Object.keys(attributes)) {\n // Avoid duplication ignoring fields already mapped.\n if (\n !(\n key.startsWith(\"_MS.\") ||\n key === SEMATTRS_NET_PEER_IP ||\n key === SEMATTRS_NET_PEER_NAME ||\n key === SEMATTRS_PEER_SERVICE ||\n key === SEMATTRS_HTTP_METHOD ||\n key === SEMATTRS_HTTP_URL ||\n key === SEMATTRS_HTTP_STATUS_CODE ||\n key === SEMATTRS_HTTP_ROUTE ||\n key === SEMATTRS_HTTP_HOST ||\n key === SEMATTRS_HTTP_URL ||\n key === SEMATTRS_DB_SYSTEM ||\n key === SEMATTRS_DB_STATEMENT ||\n key === SEMATTRS_DB_OPERATION ||\n key === SEMATTRS_DB_NAME ||\n key === SEMATTRS_RPC_SYSTEM ||\n key === SEMATTRS_RPC_GRPC_STATUS_CODE ||\n key === SEMATTRS_EXCEPTION_TYPE ||\n key === SEMATTRS_EXCEPTION_MESSAGE ||\n key === SEMATTRS_EXCEPTION_STACKTRACE\n )\n ) {\n properties[key] = attributes[key] as string;\n }\n }\n }\n return properties;\n}\n\nfunction createPropertiesFromSpan(span: ReadableSpan): [Properties, Measurements] {\n const properties: Properties = createPropertiesFromSpanAttributes(span.attributes);\n const measurements: Measurements = {};\n\n const links: MSLink[] = span.links.map((link: Link) => ({\n operation_Id: link.context.traceId,\n id: link.context.spanId,\n }));\n if (links.length > 0) {\n properties[MS_LINKS] = JSON.stringify(links);\n }\n return [properties, measurements];\n}\n\nfunction createDependencyData(span: ReadableSpan): RemoteDependencyData {\n const remoteDependencyData: RemoteDependencyData = {\n name: span.name, // Default\n id: `${span.spanContext().spanId}`,\n success: span.status?.code !== SpanStatusCode.ERROR,\n resultCode: \"0\",\n type: \"Dependency\",\n duration: msToTimeSpan(hrTimeToMilliseconds(span.duration)),\n version: 2,\n };\n if (span.kind === SpanKind.PRODUCER) {\n remoteDependencyData.type = DependencyTypes.QueueMessage;\n }\n if (span.kind === SpanKind.INTERNAL && span.parentSpanId) {\n remoteDependencyData.type = DependencyTypes.InProc;\n }\n\n const httpMethod = span.attributes[SEMATTRS_HTTP_METHOD];\n const dbSystem = span.attributes[SEMATTRS_DB_SYSTEM];\n const rpcSystem = span.attributes[SEMATTRS_RPC_SYSTEM];\n // HTTP Dependency\n if (httpMethod) {\n const httpUrl = span.attributes[SEMATTRS_HTTP_URL];\n if (httpUrl) {\n try {\n const dependencyUrl = new URL(String(httpUrl));\n remoteDependencyData.name = `${httpMethod} ${dependencyUrl.pathname}`;\n } catch (ex: any) {}\n }\n remoteDependencyData.type = DependencyTypes.Http;\n remoteDependencyData.data = getUrl(span.attributes);\n const httpStatusCode = span.attributes[SEMATTRS_HTTP_STATUS_CODE];\n if (httpStatusCode) {\n remoteDependencyData.resultCode = String(httpStatusCode);\n }\n let target = getDependencyTarget(span.attributes);\n if (target) {\n try {\n // Remove default port\n const portRegex = new RegExp(/(https?)(:\\/\\/.*)(:\\d+)(\\S*)/);\n const res = portRegex.exec(target);\n if (res !== null) {\n const protocol = res[1];\n const port = res[3];\n if (\n (protocol === \"https\" && port === \":443\") ||\n (protocol === \"http\" && port === \":80\")\n ) {\n // Drop port\n target = res[1] + res[2] + res[4];\n }\n }\n } catch (ex: any) {}\n remoteDependencyData.target = `${target}`;\n }\n }\n // DB Dependency\n else if (dbSystem) {\n // TODO: Remove special logic when Azure UX supports OpenTelemetry dbSystem\n if (String(dbSystem) === DBSYSTEMVALUES_MYSQL) {\n remoteDependencyData.type = \"mysql\";\n } else if (String(dbSystem) === DBSYSTEMVALUES_POSTGRESQL) {\n remoteDependencyData.type = \"postgresql\";\n } else if (String(dbSystem) === DBSYSTEMVALUES_MONGODB) {\n remoteDependencyData.type = \"mongodb\";\n } else if (String(dbSystem) === DBSYSTEMVALUES_REDIS) {\n remoteDependencyData.type = \"redis\";\n } else if (isSqlDB(String(dbSystem))) {\n remoteDependencyData.type = \"SQL\";\n } else {\n remoteDependencyData.type = String(dbSystem);\n }\n const dbStatement = span.attributes[SEMATTRS_DB_STATEMENT];\n const dbOperation = span.attributes[SEMATTRS_DB_OPERATION];\n if (dbStatement) {\n remoteDependencyData.data = String(dbStatement);\n } else if (dbOperation) {\n remoteDependencyData.data = String(dbOperation);\n }\n const target = getDependencyTarget(span.attributes);\n const dbName = span.attributes[SEMATTRS_DB_NAME];\n if (target) {\n remoteDependencyData.target = dbName ? `${target}|${dbName}` : `${target}`;\n } else {\n remoteDependencyData.target = dbName ? `${dbName}` : `${dbSystem}`;\n }\n }\n // grpc Dependency\n else if (rpcSystem) {\n if (rpcSystem == DependencyTypes.Wcf) {\n remoteDependencyData.type = DependencyTypes.Wcf;\n } else {\n remoteDependencyData.type = DependencyTypes.Grpc;\n }\n const grpcStatusCode = span.attributes[SEMATTRS_RPC_GRPC_STATUS_CODE];\n if (grpcStatusCode) {\n remoteDependencyData.resultCode = String(grpcStatusCode);\n }\n const target = getDependencyTarget(span.attributes);\n if (target) {\n remoteDependencyData.target = `${target}`;\n } else if (rpcSystem) {\n remoteDependencyData.target = String(rpcSystem);\n }\n }\n return remoteDependencyData;\n}\n\nfunction createRequestData(span: ReadableSpan): RequestData {\n const requestData: RequestData = {\n id: `${span.spanContext().spanId}`,\n success: span.status.code !== SpanStatusCode.ERROR,\n responseCode: \"0\",\n duration: msToTimeSpan(hrTimeToMilliseconds(span.duration)),\n version: 2,\n source: undefined,\n };\n const httpMethod = span.attributes[SEMATTRS_HTTP_METHOD];\n const grpcStatusCode = span.attributes[SEMATTRS_RPC_GRPC_STATUS_CODE];\n if (httpMethod) {\n requestData.url = getUrl(span.attributes);\n const httpStatusCode = span.attributes[SEMATTRS_HTTP_STATUS_CODE];\n if (httpStatusCode) {\n requestData.responseCode = String(httpStatusCode);\n }\n } else if (grpcStatusCode) {\n requestData.responseCode = String(grpcStatusCode);\n }\n return requestData;\n}\n\n/**\n * Span to Azure envelope parsing.\n * @internal\n */\nexport function readableSpanToEnvelope(span: ReadableSpan, ikey: string): Envelope {\n let name: string;\n let baseType: \"RemoteDependencyData\" | \"RequestData\";\n let baseData: RemoteDependencyData | RequestData;\n\n const time = hrTimeToDate(span.startTime);\n const instrumentationKey = ikey;\n const tags = createTagsFromSpan(span);\n const [properties, measurements] = createPropertiesFromSpan(span);\n switch (span.kind) {\n case SpanKind.CLIENT:\n case SpanKind.PRODUCER:\n case SpanKind.INTERNAL:\n name = \"Microsoft.ApplicationInsights.RemoteDependency\";\n baseType = \"RemoteDependencyData\";\n baseData = createDependencyData(span);\n break;\n case SpanKind.SERVER:\n case SpanKind.CONSUMER:\n name = \"Microsoft.ApplicationInsights.Request\";\n baseType = \"RequestData\";\n baseData = createRequestData(span);\n baseData.name = tags[KnownContextTagKeys.AiOperationName];\n break;\n default:\n // never\n diag.error(`Unsupported span kind ${span.kind}`);\n throw new Error(`Unsupported span kind ${span.kind}`);\n }\n\n let sampleRate = 100;\n if (span.attributes[AzureMonitorSampleRate]) {\n sampleRate = Number(span.attributes[AzureMonitorSampleRate]);\n }\n\n // Azure SDK\n if (span.attributes[AzNamespace]) {\n if (span.kind === SpanKind.INTERNAL) {\n baseData.type = `${DependencyTypes.InProc} | ${span.attributes[AzNamespace]}`;\n }\n if (span.attributes[AzNamespace] === MicrosoftEventHub) {\n parseEventHubSpan(span, baseData);\n }\n }\n\n return {\n name,\n sampleRate,\n time,\n instrumentationKey,\n tags,\n version: 1,\n data: {\n baseType,\n baseData: {\n ...baseData,\n properties,\n measurements,\n },\n },\n };\n}\n\n/**\n * Span Events to Azure envelopes parsing.\n * @internal\n */\nexport function spanEventsToEnvelopes(span: ReadableSpan, ikey: string): Envelope[] {\n const envelopes: Envelope[] = [];\n if (span.events) {\n span.events.forEach((event: TimedEvent) => {\n let baseType: \"ExceptionData\" | \"MessageData\";\n const time = hrTimeToDate(event.time);\n let name = \"\";\n let baseData: TelemetryExceptionData | MessageData;\n const properties = createPropertiesFromSpanAttributes(event.attributes);\n\n const tags: Tags = createTagsFromResource(span.resource);\n tags[KnownContextTagKeys.AiOperationId] = span.spanContext().traceId;\n const spanId = span.spanContext()?.spanId;\n if (spanId) {\n tags[KnownContextTagKeys.AiOperationParentId] = spanId;\n }\n\n // Only generate exception telemetry for incoming requests\n if (event.name === \"exception\" && span.kind === SpanKind.SERVER) {\n name = \"Microsoft.ApplicationInsights.Exception\";\n baseType = \"ExceptionData\";\n let typeName = \"\";\n let message = \"Exception\";\n let stack = \"\";\n let hasFullStack = false;\n if (event.attributes) {\n typeName = String(event.attributes[SEMATTRS_EXCEPTION_TYPE]);\n stack = String(event.attributes[SEMATTRS_EXCEPTION_STACKTRACE]);\n if (stack) {\n hasFullStack = true;\n }\n const exceptionMsg = event.attributes[SEMATTRS_EXCEPTION_MESSAGE];\n if (exceptionMsg) {\n message = String(exceptionMsg);\n }\n const escaped = event.attributes[SEMATTRS_EXCEPTION_ESCAPED];\n if (escaped !== undefined) {\n properties[SEMATTRS_EXCEPTION_ESCAPED] = String(escaped);\n }\n }\n const exceptionDetails: TelemetryExceptionDetails = {\n typeName: typeName,\n message: message,\n stack: stack,\n hasFullStack: hasFullStack,\n };\n const exceptionData: TelemetryExceptionData = {\n exceptions: [exceptionDetails],\n version: 2,\n properties: properties,\n };\n baseData = exceptionData;\n } else {\n name = \"Microsoft.ApplicationInsights.Message\";\n baseType = \"MessageData\";\n const messageData: MessageData = {\n message: event.name,\n version: 2,\n properties: properties,\n };\n baseData = messageData;\n }\n let sampleRate = 100;\n if (span.attributes[AzureMonitorSampleRate]) {\n sampleRate = Number(span.attributes[AzureMonitorSampleRate]);\n }\n const env: Envelope = {\n name: name,\n time: time,\n instrumentationKey: ikey,\n version: 1,\n sampleRate: sampleRate,\n data: {\n baseType: baseType,\n baseData: baseData,\n },\n tags: tags,\n };\n envelopes.push(env);\n });\n }\n return envelopes;\n}\n"]}
1
+ {"version":3,"file":"spanUtils.js","sourceRoot":"","sources":["../../../src/utils/spanUtils.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,GAAG,EAAE,MAAM,KAAK,CAAC;AAE1B,OAAO,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AAC3D,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,cAAc,EAAoB,MAAM,oBAAoB,CAAC;AACtF,OAAO,EACL,sBAAsB,EACtB,oBAAoB,EACpB,yBAAyB,EACzB,oBAAoB,EACpB,gBAAgB,EAChB,qBAAqB,EACrB,qBAAqB,EACrB,kBAAkB,EAClB,mBAAmB,EACnB,0BAA0B,EAC1B,0BAA0B,EAC1B,6BAA6B,EAC7B,uBAAuB,EACvB,uBAAuB,EACvB,kBAAkB,EAClB,oBAAoB,EACpB,mBAAmB,EACnB,yBAAyB,EACzB,iBAAiB,EACjB,wBAAwB,EACxB,oBAAoB,EACpB,sBAAsB,EACtB,qBAAqB,EACrB,6BAA6B,EAC7B,mBAAmB,GACpB,MAAM,qCAAqC,CAAC;AAE7C,OAAO,EACL,sBAAsB,EACtB,mBAAmB,EACnB,MAAM,EACN,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nimport { ReadableSpan, TimedEvent } from \"@opentelemetry/sdk-trace-base\";\nimport { hrTimeToMilliseconds } from \"@opentelemetry/core\";\nimport { diag, SpanKind, SpanStatusCode, Link, Attributes } from \"@opentelemetry/api\";\nimport {\n DBSYSTEMVALUES_MONGODB,\n DBSYSTEMVALUES_MYSQL,\n DBSYSTEMVALUES_POSTGRESQL,\n DBSYSTEMVALUES_REDIS,\n SEMATTRS_DB_NAME,\n SEMATTRS_DB_OPERATION,\n SEMATTRS_DB_STATEMENT,\n SEMATTRS_DB_SYSTEM,\n SEMATTRS_ENDUSER_ID,\n SEMATTRS_EXCEPTION_ESCAPED,\n SEMATTRS_EXCEPTION_MESSAGE,\n SEMATTRS_EXCEPTION_STACKTRACE,\n SEMATTRS_EXCEPTION_TYPE,\n SEMATTRS_HTTP_CLIENT_IP,\n SEMATTRS_HTTP_HOST,\n SEMATTRS_HTTP_METHOD,\n SEMATTRS_HTTP_ROUTE,\n SEMATTRS_HTTP_STATUS_CODE,\n SEMATTRS_HTTP_URL,\n SEMATTRS_HTTP_USER_AGENT,\n SEMATTRS_NET_PEER_IP,\n SEMATTRS_NET_PEER_NAME,\n SEMATTRS_PEER_SERVICE,\n SEMATTRS_RPC_GRPC_STATUS_CODE,\n SEMATTRS_RPC_SYSTEM,\n} from \"@opentelemetry/semantic-conventions\";\n\nimport {\n createTagsFromResource,\n getDependencyTarget,\n getUrl,\n hrTimeToDate,\n isSqlDB,\n} from \"./common\";\nimport { Tags, Properties, MSLink, Measurements } from \"../types\";\nimport { parseEventHubSpan } from \"./eventhub\";\nimport { AzureMonitorSampleRate, DependencyTypes, MS_LINKS } from \"./constants/applicationinsights\";\nimport { AzNamespace, MicrosoftEventHub } from \"./constants/span/azAttributes\";\nimport {\n TelemetryExceptionData,\n MessageData,\n RemoteDependencyData,\n RequestData,\n TelemetryItem as Envelope,\n KnownContextTagKeys,\n TelemetryExceptionDetails,\n} from \"../generated\";\nimport { msToTimeSpan } from \"./breezeUtils\";\n\nfunction createTagsFromSpan(span: ReadableSpan): Tags {\n const tags: Tags = createTagsFromResource(span.resource);\n tags[KnownContextTagKeys.AiOperationId] = span.spanContext().traceId;\n if (span.parentSpanId) {\n tags[KnownContextTagKeys.AiOperationParentId] = span.parentSpanId;\n }\n const endUserId = span.attributes[SEMATTRS_ENDUSER_ID];\n if (endUserId) {\n tags[KnownContextTagKeys.AiUserId] = String(endUserId);\n }\n const httpUserAgent = span.attributes[SEMATTRS_HTTP_USER_AGENT];\n if (httpUserAgent) {\n // TODO: Not exposed in Swagger, need to update def\n tags[\"ai.user.userAgent\"] = String(httpUserAgent);\n }\n if (span.kind === SpanKind.SERVER) {\n const httpMethod = span.attributes[SEMATTRS_HTTP_METHOD];\n const httpClientIp = span.attributes[SEMATTRS_HTTP_CLIENT_IP];\n const netPeerIp = span.attributes[SEMATTRS_NET_PEER_IP];\n if (httpMethod) {\n const httpRoute = span.attributes[SEMATTRS_HTTP_ROUTE];\n const httpUrl = span.attributes[SEMATTRS_HTTP_URL];\n tags[KnownContextTagKeys.AiOperationName] = span.name; // Default\n if (httpRoute) {\n tags[KnownContextTagKeys.AiOperationName] = `${httpMethod as string} ${\n httpRoute as string\n }`;\n } else if (httpUrl) {\n try {\n const url = new URL(String(httpUrl));\n tags[KnownContextTagKeys.AiOperationName] = `${httpMethod} ${url.pathname}`;\n } catch (ex: any) {}\n }\n if (httpClientIp) {\n tags[KnownContextTagKeys.AiLocationIp] = String(httpClientIp);\n } else if (netPeerIp) {\n tags[KnownContextTagKeys.AiLocationIp] = String(netPeerIp);\n }\n } else {\n tags[KnownContextTagKeys.AiOperationName] = span.name;\n if (netPeerIp) {\n tags[KnownContextTagKeys.AiLocationIp] = String(netPeerIp);\n }\n }\n }\n // TODO: Operation Name and Location IP TBD for non server spans\n\n return tags;\n}\n\nfunction createPropertiesFromSpanAttributes(attributes?: Attributes): {\n [propertyName: string]: string;\n} {\n const properties: { [propertyName: string]: string } = {};\n if (attributes) {\n for (const key of Object.keys(attributes)) {\n // Avoid duplication ignoring fields already mapped.\n if (\n !(\n key.startsWith(\"_MS.\") ||\n key === SEMATTRS_NET_PEER_IP ||\n key === SEMATTRS_NET_PEER_NAME ||\n key === SEMATTRS_PEER_SERVICE ||\n key === SEMATTRS_HTTP_METHOD ||\n key === SEMATTRS_HTTP_URL ||\n key === SEMATTRS_HTTP_STATUS_CODE ||\n key === SEMATTRS_HTTP_ROUTE ||\n key === SEMATTRS_HTTP_HOST ||\n key === SEMATTRS_HTTP_URL ||\n key === SEMATTRS_DB_SYSTEM ||\n key === SEMATTRS_DB_STATEMENT ||\n key === SEMATTRS_DB_OPERATION ||\n key === SEMATTRS_DB_NAME ||\n key === SEMATTRS_RPC_SYSTEM ||\n key === SEMATTRS_RPC_GRPC_STATUS_CODE ||\n key === SEMATTRS_EXCEPTION_TYPE ||\n key === SEMATTRS_EXCEPTION_MESSAGE ||\n key === SEMATTRS_EXCEPTION_STACKTRACE\n )\n ) {\n properties[key] = attributes[key] as string;\n }\n }\n }\n return properties;\n}\n\nfunction createPropertiesFromSpan(span: ReadableSpan): [Properties, Measurements] {\n const properties: Properties = createPropertiesFromSpanAttributes(span.attributes);\n const measurements: Measurements = {};\n\n const links: MSLink[] = span.links.map((link: Link) => ({\n operation_Id: link.context.traceId,\n id: link.context.spanId,\n }));\n if (links.length > 0) {\n properties[MS_LINKS] = JSON.stringify(links);\n }\n return [properties, measurements];\n}\n\nfunction createDependencyData(span: ReadableSpan): RemoteDependencyData {\n const remoteDependencyData: RemoteDependencyData = {\n name: span.name, // Default\n id: `${span.spanContext().spanId}`,\n success: span.status?.code !== SpanStatusCode.ERROR,\n resultCode: \"0\",\n type: \"Dependency\",\n duration: msToTimeSpan(hrTimeToMilliseconds(span.duration)),\n version: 2,\n };\n if (span.kind === SpanKind.PRODUCER) {\n remoteDependencyData.type = DependencyTypes.QueueMessage;\n }\n if (span.kind === SpanKind.INTERNAL && span.parentSpanId) {\n remoteDependencyData.type = DependencyTypes.InProc;\n }\n\n const httpMethod = span.attributes[SEMATTRS_HTTP_METHOD];\n const dbSystem = span.attributes[SEMATTRS_DB_SYSTEM];\n const rpcSystem = span.attributes[SEMATTRS_RPC_SYSTEM];\n // HTTP Dependency\n if (httpMethod) {\n const httpUrl = span.attributes[SEMATTRS_HTTP_URL];\n if (httpUrl) {\n try {\n const dependencyUrl = new URL(String(httpUrl));\n remoteDependencyData.name = `${httpMethod} ${dependencyUrl.pathname}`;\n } catch (ex: any) {}\n }\n remoteDependencyData.type = DependencyTypes.Http;\n remoteDependencyData.data = getUrl(span.attributes);\n const httpStatusCode = span.attributes[SEMATTRS_HTTP_STATUS_CODE];\n if (httpStatusCode) {\n remoteDependencyData.resultCode = String(httpStatusCode);\n }\n let target = getDependencyTarget(span.attributes);\n if (target) {\n try {\n // Remove default port\n const portRegex = new RegExp(/(https?)(:\\/\\/.*)(:\\d+)(\\S*)/);\n const res = portRegex.exec(target);\n if (res !== null) {\n const protocol = res[1];\n const port = res[3];\n if (\n (protocol === \"https\" && port === \":443\") ||\n (protocol === \"http\" && port === \":80\")\n ) {\n // Drop port\n target = res[1] + res[2] + res[4];\n }\n }\n } catch (ex: any) {}\n remoteDependencyData.target = `${target}`;\n }\n }\n // DB Dependency\n else if (dbSystem) {\n // TODO: Remove special logic when Azure UX supports OpenTelemetry dbSystem\n if (String(dbSystem) === DBSYSTEMVALUES_MYSQL) {\n remoteDependencyData.type = \"mysql\";\n } else if (String(dbSystem) === DBSYSTEMVALUES_POSTGRESQL) {\n remoteDependencyData.type = \"postgresql\";\n } else if (String(dbSystem) === DBSYSTEMVALUES_MONGODB) {\n remoteDependencyData.type = \"mongodb\";\n } else if (String(dbSystem) === DBSYSTEMVALUES_REDIS) {\n remoteDependencyData.type = \"redis\";\n } else if (isSqlDB(String(dbSystem))) {\n remoteDependencyData.type = \"SQL\";\n } else {\n remoteDependencyData.type = String(dbSystem);\n }\n const dbStatement = span.attributes[SEMATTRS_DB_STATEMENT];\n const dbOperation = span.attributes[SEMATTRS_DB_OPERATION];\n if (dbStatement) {\n remoteDependencyData.data = String(dbStatement);\n } else if (dbOperation) {\n remoteDependencyData.data = String(dbOperation);\n }\n const target = getDependencyTarget(span.attributes);\n const dbName = span.attributes[SEMATTRS_DB_NAME];\n if (target) {\n remoteDependencyData.target = dbName ? `${target}|${dbName}` : `${target}`;\n } else {\n remoteDependencyData.target = dbName ? `${dbName}` : `${dbSystem}`;\n }\n }\n // grpc Dependency\n else if (rpcSystem) {\n if (rpcSystem == DependencyTypes.Wcf) {\n remoteDependencyData.type = DependencyTypes.Wcf;\n } else {\n remoteDependencyData.type = DependencyTypes.Grpc;\n }\n const grpcStatusCode = span.attributes[SEMATTRS_RPC_GRPC_STATUS_CODE];\n if (grpcStatusCode) {\n remoteDependencyData.resultCode = String(grpcStatusCode);\n }\n const target = getDependencyTarget(span.attributes);\n if (target) {\n remoteDependencyData.target = `${target}`;\n } else if (rpcSystem) {\n remoteDependencyData.target = String(rpcSystem);\n }\n }\n return remoteDependencyData;\n}\n\nfunction createRequestData(span: ReadableSpan): RequestData {\n const requestData: RequestData = {\n id: `${span.spanContext().spanId}`,\n success:\n span.status.code !== SpanStatusCode.ERROR &&\n (Number(span.attributes[SEMATTRS_HTTP_STATUS_CODE]) || 0) < 400,\n responseCode: \"0\",\n duration: msToTimeSpan(hrTimeToMilliseconds(span.duration)),\n version: 2,\n source: undefined,\n };\n const httpMethod = span.attributes[SEMATTRS_HTTP_METHOD];\n const grpcStatusCode = span.attributes[SEMATTRS_RPC_GRPC_STATUS_CODE];\n if (httpMethod) {\n requestData.url = getUrl(span.attributes);\n const httpStatusCode = span.attributes[SEMATTRS_HTTP_STATUS_CODE];\n if (httpStatusCode) {\n requestData.responseCode = String(httpStatusCode);\n }\n } else if (grpcStatusCode) {\n requestData.responseCode = String(grpcStatusCode);\n }\n return requestData;\n}\n\n/**\n * Span to Azure envelope parsing.\n * @internal\n */\nexport function readableSpanToEnvelope(span: ReadableSpan, ikey: string): Envelope {\n let name: string;\n let baseType: \"RemoteDependencyData\" | \"RequestData\";\n let baseData: RemoteDependencyData | RequestData;\n\n const time = hrTimeToDate(span.startTime);\n const instrumentationKey = ikey;\n const tags = createTagsFromSpan(span);\n const [properties, measurements] = createPropertiesFromSpan(span);\n switch (span.kind) {\n case SpanKind.CLIENT:\n case SpanKind.PRODUCER:\n case SpanKind.INTERNAL:\n name = \"Microsoft.ApplicationInsights.RemoteDependency\";\n baseType = \"RemoteDependencyData\";\n baseData = createDependencyData(span);\n break;\n case SpanKind.SERVER:\n case SpanKind.CONSUMER:\n name = \"Microsoft.ApplicationInsights.Request\";\n baseType = \"RequestData\";\n baseData = createRequestData(span);\n baseData.name = tags[KnownContextTagKeys.AiOperationName];\n break;\n default:\n // never\n diag.error(`Unsupported span kind ${span.kind}`);\n throw new Error(`Unsupported span kind ${span.kind}`);\n }\n\n let sampleRate = 100;\n if (span.attributes[AzureMonitorSampleRate]) {\n sampleRate = Number(span.attributes[AzureMonitorSampleRate]);\n }\n\n // Azure SDK\n if (span.attributes[AzNamespace]) {\n if (span.kind === SpanKind.INTERNAL) {\n baseData.type = `${DependencyTypes.InProc} | ${span.attributes[AzNamespace]}`;\n }\n if (span.attributes[AzNamespace] === MicrosoftEventHub) {\n parseEventHubSpan(span, baseData);\n }\n }\n\n return {\n name,\n sampleRate,\n time,\n instrumentationKey,\n tags,\n version: 1,\n data: {\n baseType,\n baseData: {\n ...baseData,\n properties,\n measurements,\n },\n },\n };\n}\n\n/**\n * Span Events to Azure envelopes parsing.\n * @internal\n */\nexport function spanEventsToEnvelopes(span: ReadableSpan, ikey: string): Envelope[] {\n const envelopes: Envelope[] = [];\n if (span.events) {\n span.events.forEach((event: TimedEvent) => {\n let baseType: \"ExceptionData\" | \"MessageData\";\n const time = hrTimeToDate(event.time);\n let name = \"\";\n let baseData: TelemetryExceptionData | MessageData;\n const properties = createPropertiesFromSpanAttributes(event.attributes);\n\n const tags: Tags = createTagsFromResource(span.resource);\n tags[KnownContextTagKeys.AiOperationId] = span.spanContext().traceId;\n const spanId = span.spanContext()?.spanId;\n if (spanId) {\n tags[KnownContextTagKeys.AiOperationParentId] = spanId;\n }\n\n // Only generate exception telemetry for incoming requests\n if (event.name === \"exception\") {\n if (span.kind === SpanKind.SERVER) {\n name = \"Microsoft.ApplicationInsights.Exception\";\n baseType = \"ExceptionData\";\n let typeName = \"\";\n let message = \"Exception\";\n let stack = \"\";\n let hasFullStack = false;\n if (event.attributes) {\n typeName = String(event.attributes[SEMATTRS_EXCEPTION_TYPE]);\n stack = String(event.attributes[SEMATTRS_EXCEPTION_STACKTRACE]);\n if (stack) {\n hasFullStack = true;\n }\n const exceptionMsg = event.attributes[SEMATTRS_EXCEPTION_MESSAGE];\n if (exceptionMsg) {\n message = String(exceptionMsg);\n }\n const escaped = event.attributes[SEMATTRS_EXCEPTION_ESCAPED];\n if (escaped !== undefined) {\n properties[SEMATTRS_EXCEPTION_ESCAPED] = String(escaped);\n }\n }\n const exceptionDetails: TelemetryExceptionDetails = {\n typeName: typeName,\n message: message,\n stack: stack,\n hasFullStack: hasFullStack,\n };\n const exceptionData: TelemetryExceptionData = {\n exceptions: [exceptionDetails],\n version: 2,\n properties: properties,\n };\n baseData = exceptionData;\n } else {\n // Drop non-server exception span events\n return;\n }\n } else {\n name = \"Microsoft.ApplicationInsights.Message\";\n baseType = \"MessageData\";\n const messageData: MessageData = {\n message: event.name,\n version: 2,\n properties: properties,\n };\n baseData = messageData;\n }\n let sampleRate = 100;\n if (span.attributes[AzureMonitorSampleRate]) {\n sampleRate = Number(span.attributes[AzureMonitorSampleRate]);\n }\n const env: Envelope = {\n name: name,\n time: time,\n instrumentationKey: ikey,\n version: 1,\n sampleRate: sampleRate,\n data: {\n baseType: baseType,\n baseData: baseData,\n },\n tags: tags,\n };\n envelopes.push(env);\n });\n }\n return envelopes;\n}\n"]}
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@azure/monitor-opentelemetry-exporter",
3
3
  "author": "Microsoft Corporation",
4
4
  "sdk-type": "client",
5
- "version": "1.0.0-beta.22",
5
+ "version": "1.0.0-beta.24",
6
6
  "description": "Application Insights exporter for the OpenTelemetry JavaScript (Node.js) SDK",
7
7
  "main": "dist/index.js",
8
8
  "module": "dist-esm/src/index.js",
@@ -13,10 +13,10 @@
13
13
  "build:node": "tsc -p . && dev-tool run bundle --browser-test=false",
14
14
  "build:test": "tsc -p . && dev-tool run bundle --browser-test=false",
15
15
  "build:samples": "echo Obsolete.",
16
- "build": "npm run build:node && npm run build:browser && api-extractor run --local",
16
+ "build": "npm run build:node && npm run build:browser && dev-tool run extract-api",
17
17
  "check-format": "dev-tool run vendored prettier --list-different --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"test/**/*.ts\" \"samples-dev/**/*.ts\" \"*.{js,json}\"",
18
18
  "execute:samples": "dev-tool samples run samples-dev",
19
- "extract-api": "tsc -p . && api-extractor run --local",
19
+ "extract-api": "tsc -p . && dev-tool run extract-api",
20
20
  "format": "dev-tool run vendored prettier --write --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"test/**/*.ts\" \"samples-dev/**/*.ts\" \"*.{js,json}\"",
21
21
  "generate:client": "autorest --typescript ./swagger/README.md",
22
22
  "lint:fix": "eslint package.json api-extractor.json src test --ext .ts --fix --fix-type [problem,suggestion]",
@@ -29,7 +29,7 @@
29
29
  "unit-test:node:debug": "dev-tool run test:node-tsx-ts -- --timeout 1200000 \"test/internal/**/*.test.ts\"",
30
30
  "unit-test": "npm run unit-test:node && npm run unit-test:browser",
31
31
  "integration-test:browser": "echo skipped",
32
- "integration-test:node": "dev-tool run test:node-ts-input --no-test-proxy=true -- --timeout 1200000 \"test/internal/functional/**/*.test.ts\"",
32
+ "integration-test:node": "dev-tool run test:node-ts-input --no-test-proxy -- --timeout 1200000 \"test/internal/functional/**/*.test.ts\"",
33
33
  "integration-test": "npm run integration-test:node && npm run integration-test:browser",
34
34
  "report": "nyc report --reporter=json",
35
35
  "test-opentelemetry-versions": "node test-opentelemetry-versions.js 2>&1",
@@ -83,12 +83,12 @@
83
83
  "@azure/dev-tool": "^1.0.0",
84
84
  "@azure/eslint-plugin-azure-sdk": "^3.0.0",
85
85
  "@microsoft/api-extractor": "^7.31.1",
86
- "@opentelemetry/instrumentation": "^0.50.0",
87
- "@opentelemetry/instrumentation-http": "^0.50.0",
88
- "@opentelemetry/sdk-trace-node": "^1.23.0",
86
+ "@opentelemetry/instrumentation": "^0.52.0",
87
+ "@opentelemetry/instrumentation-http": "^0.52.0",
88
+ "@opentelemetry/sdk-trace-node": "^1.25.0",
89
89
  "@types/mocha": "^10.0.0",
90
90
  "@types/node": "^18.0.0",
91
- "c8": "^9.1.0",
91
+ "nyc": "^15.1.0",
92
92
  "cross-env": "^7.0.2",
93
93
  "dotenv": "^16.0.0",
94
94
  "eslint": "^8.0.0",
@@ -104,14 +104,14 @@
104
104
  "@azure/core-client": "^1.0.0",
105
105
  "@azure/core-auth": "^1.3.0",
106
106
  "@azure/core-rest-pipeline": "^1.1.0",
107
- "@opentelemetry/api": "^1.8.0",
108
- "@opentelemetry/api-logs": "^0.50.0",
109
- "@opentelemetry/core": "^1.23.0",
110
- "@opentelemetry/resources": "^1.23.0",
111
- "@opentelemetry/sdk-metrics": "^1.23.0",
112
- "@opentelemetry/sdk-trace-base": "^1.23.0",
113
- "@opentelemetry/semantic-conventions": "^1.23.0",
114
- "@opentelemetry/sdk-logs": "^0.50.0",
107
+ "@opentelemetry/api": "^1.9.0",
108
+ "@opentelemetry/api-logs": "^0.52.0",
109
+ "@opentelemetry/core": "^1.25.0",
110
+ "@opentelemetry/resources": "^1.25.0",
111
+ "@opentelemetry/sdk-metrics": "^1.25.0",
112
+ "@opentelemetry/sdk-trace-base": "^1.25.0",
113
+ "@opentelemetry/semantic-conventions": "^1.25.0",
114
+ "@opentelemetry/sdk-logs": "^0.52.0",
115
115
  "tslib": "^2.6.2"
116
116
  },
117
117
  "sideEffects": false,