@azure/monitor-opentelemetry-exporter 1.0.0-beta.5 → 1.0.0-beta.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +11 -13
  2. package/dist/index.js +706 -245
  3. package/dist-esm/src/Declarations/Constants.js +1 -1
  4. package/dist-esm/src/Declarations/Constants.js.map +1 -1
  5. package/dist-esm/src/config.js +2 -4
  6. package/dist-esm/src/config.js.map +1 -1
  7. package/dist-esm/src/export/base.js +172 -0
  8. package/dist-esm/src/export/base.js.map +1 -0
  9. package/dist-esm/src/export/metric.js +50 -0
  10. package/dist-esm/src/export/metric.js.map +1 -0
  11. package/dist-esm/src/export/trace.js +14 -145
  12. package/dist-esm/src/export/trace.js.map +1 -1
  13. package/dist-esm/src/generated/applicationInsightsClient.js.map +1 -1
  14. package/dist-esm/src/generated/applicationInsightsClientContext.js +2 -2
  15. package/dist-esm/src/generated/applicationInsightsClientContext.js.map +1 -1
  16. package/dist-esm/src/generated/models/index.js.map +1 -1
  17. package/dist-esm/src/index.js +2 -0
  18. package/dist-esm/src/index.js.map +1 -1
  19. package/dist-esm/src/platform/nodejs/constants.js +1 -1
  20. package/dist-esm/src/platform/nodejs/constants.js.map +1 -1
  21. package/dist-esm/src/platform/nodejs/httpSender.js +12 -3
  22. package/dist-esm/src/platform/nodejs/httpSender.js.map +1 -1
  23. package/dist-esm/src/platform/nodejs/persist/fileAccessControl.js +171 -0
  24. package/dist-esm/src/platform/nodejs/persist/fileAccessControl.js.map +1 -0
  25. package/dist-esm/src/platform/nodejs/persist/fileSystemHelpers.js.map +1 -1
  26. package/dist-esm/src/platform/nodejs/persist/fileSystemPersist.js +40 -19
  27. package/dist-esm/src/platform/nodejs/persist/fileSystemPersist.js.map +1 -1
  28. package/dist-esm/src/utils/breezeUtils.js +5 -4
  29. package/dist-esm/src/utils/breezeUtils.js.map +1 -1
  30. package/dist-esm/src/utils/constants/applicationinsights.js +1 -1
  31. package/dist-esm/src/utils/constants/applicationinsights.js.map +1 -1
  32. package/dist-esm/src/utils/eventhub.js +1 -1
  33. package/dist-esm/src/utils/eventhub.js.map +1 -1
  34. package/dist-esm/src/utils/metricUtils.js +53 -0
  35. package/dist-esm/src/utils/metricUtils.js.map +1 -0
  36. package/dist-esm/src/utils/resourceUtils.js +35 -0
  37. package/dist-esm/src/utils/resourceUtils.js.map +1 -0
  38. package/dist-esm/src/utils/spanUtils.js +118 -49
  39. package/dist-esm/src/utils/spanUtils.js.map +1 -1
  40. package/package.json +25 -26
  41. package/types/monitor-opentelemetry-exporter.d.ts +110 -7
  42. package/CHANGELOG.md +0 -38
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/generated/models/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAyQH,sEAAsE;AACtE,MAAM,CAAN,IAAY,kBAGX;AAHD,WAAY,kBAAkB;IAC5B,iDAA2B,CAAA;IAC3B,iDAA2B,CAAA;AAC7B,CAAC,EAHW,kBAAkB,KAAlB,kBAAkB,QAG7B;AAYD,sEAAsE;AACtE,MAAM,CAAN,IAAY,kBAMX;AAND,WAAY,kBAAkB;IAC5B,yCAAmB,CAAA;IACnB,iDAA2B,CAAA;IAC3B,yCAAmB,CAAA;IACnB,qCAAe,CAAA;IACf,2CAAqB,CAAA;AACvB,CAAC,EANW,kBAAkB,KAAlB,kBAAkB,QAM7B;AAeD,uEAAuE;AACvE,MAAM,CAAN,IAAY,mBA6BX;AA7BD,WAAY,mBAAmB;IAC7B,8DAAuC,CAAA;IACvC,kDAA2B,CAAA;IAC3B,0DAAmC,CAAA;IACnC,wDAAiC,CAAA;IACjC,4DAAqC,CAAA;IACrC,gEAAyC,CAAA;IACzC,sDAA+B,CAAA;IAC/B,sDAA+B,CAAA;IAC/B,gEAAyC,CAAA;IACzC,kEAA2C,CAAA;IAC3C,0DAAmC,CAAA;IACnC,wDAAiC,CAAA;IACjC,4DAAqC,CAAA;IACrC,oEAA6C,CAAA;IAC7C,kFAA2D,CAAA;IAC3D,sFAA+D,CAAA;IAC/D,oDAA6B,CAAA;IAC7B,8DAAuC,CAAA;IACvC,4DAAqC,CAAA;IACrC,8CAAuB,CAAA;IACvB,8DAAuC,CAAA;IACvC,oDAA6B,CAAA;IAC7B,0DAAmC,CAAA;IACnC,oEAA6C,CAAA;IAC7C,4DAAqC,CAAA;IACrC,sEAA+C,CAAA;IAC/C,0EAAmD,CAAA;IACnD,kEAA2C,CAAA;AAC7C,CAAC,EA7BW,mBAAmB,KAAnB,mBAAmB,QA6B9B","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\";\n\n/** System variables for a telemetry item. */\nexport interface TelemetryItem {\n /** Envelope version. For internal use only. By assigning this the default, it will not be serialized within the payload unless changed to a value other than #1. */\n version?: number;\n /** Type name of telemetry data item. */\n name: string;\n /** Event date time when telemetry item was created. This is the wall clock time on the client when the event was generated. There is no guarantee that the client's time is accurate. This field must be formatted in UTC ISO 8601 format, with a trailing 'Z' character, as described publicly on https://en.wikipedia.org/wiki/ISO_8601#UTC. Note: the number of decimal seconds digits provided are variable (and unspecified). Consumers should handle this, i.e. managed code consumers should not use format 'O' for parsing as it specifies a fixed length. Example: 2009-06-15T13:45:30.0000000Z. */\n time: Date;\n /** Sampling rate used in application. This telemetry item represents 1 / sampleRate actual telemetry items. */\n sampleRate?: number;\n /** Sequence field used to track absolute order of uploaded events. */\n sequence?: string;\n /** The instrumentation key of the Application Insights resource. */\n instrumentationKey?: string;\n /** Key/value collection of context properties. See ContextTagKeys for information on available properties. */\n tags?: { [propertyName: string]: string };\n /** Telemetry data item. */\n data?: MonitorBase;\n}\n\n/** Data struct to contain only C section with custom fields. */\nexport interface MonitorBase {\n /** Name of item (B section) if any. If telemetry data is derived straight from this, this should be null. */\n baseType?: string;\n /** The data payload for the telemetry request */\n baseData?: MonitorDomain;\n}\n\n/** The abstract common base of all domains. */\nexport interface MonitorDomain {\n /** Describes unknown properties. The value of an unknown property can be of \"any\" type. */\n [property: string]: any;\n /** Schema version */\n version: number;\n}\n\n/** Response containing the status of each telemetry item. */\nexport interface TrackResponse {\n /** The number of items received. */\n itemsReceived?: number;\n /** The number of items accepted. */\n itemsAccepted?: number;\n /** An array of error detail objects. */\n errors?: TelemetryErrorDetails[];\n}\n\n/** The error details */\nexport interface TelemetryErrorDetails {\n /** The index in the original payload of the item. */\n index?: number;\n /** The item specific [HTTP Response status code](#Response Status Codes). */\n statusCode?: number;\n /** The error message. */\n message?: string;\n}\n\n/** Metric data single measurement. */\nexport interface MetricDataPoint {\n /** Namespace of the metric. */\n namespace?: string;\n /** Name of the metric. */\n name: string;\n /** Metric type. Single measurement or the aggregated value. */\n dataPointType?: DataPointType;\n /** Single value for measurement. Sum of individual measurements for the aggregation. */\n value: number;\n /** Metric weight of the aggregated metric. Should not be set for a measurement. */\n count?: number;\n /** Minimum value of the aggregated metric. Should not be set for a measurement. */\n min?: number;\n /** Maximum value of the aggregated metric. Should not be set for a measurement. */\n max?: number;\n /** Standard deviation of the aggregated metric. Should not be set for a measurement. */\n stdDev?: number;\n}\n\n/** Exception details of the exception in a chain. */\nexport interface TelemetryExceptionDetails {\n /** In case exception is nested (outer exception contains inner one), the id and outerId properties are used to represent the nesting. */\n id?: number;\n /** The value of outerId is a reference to an element in ExceptionDetails that represents the outer exception */\n outerId?: number;\n /** Exception type name. */\n typeName?: string;\n /** Exception message. */\n message: string;\n /** Indicates if full exception stack is provided in the exception. The stack may be trimmed, such as in the case of a StackOverflow exception. */\n hasFullStack?: boolean;\n /** Text describing the stack. Either stack or parsedStack should have a value. */\n stack?: string;\n /** List of stack frames. Either stack or parsedStack should have a value. */\n parsedStack?: StackFrame[];\n}\n\n/** Stack frame information. */\nexport interface StackFrame {\n level: number;\n /** Method name. */\n method: string;\n /** Name of the assembly (dll, jar, etc.) containing this function. */\n assembly?: string;\n /** File name or URL of the method implementation. */\n fileName?: string;\n /** Line number of the code implementation. */\n line?: number;\n}\n\n/** Instances of AvailabilityData represent the result of executing an availability test. */\nexport type AvailabilityData = MonitorDomain & {\n /** Identifier of a test run. Use it to correlate steps of test run and telemetry generated by the service. */\n id: string;\n /** Name of the test that these availability results represent. */\n name: string;\n /** Duration in format: DD.HH:MM:SS.MMMMMM. Must be less than 1000 days. */\n duration: string;\n /** Success flag. */\n success: boolean;\n /** Name of the location where the test was run from. */\n runLocation?: string;\n /** Diagnostic message for the result. */\n message?: string;\n /** Collection of custom properties. */\n properties?: { [propertyName: string]: string };\n /** Collection of custom measurements. */\n measurements?: { [propertyName: string]: number };\n};\n\n/** Instances of Event represent structured event records that can be grouped and searched by their properties. Event data item also creates a metric of event count by name. */\nexport type TelemetryEventData = MonitorDomain & {\n /** Event name. Keep it low cardinality to allow proper grouping and useful metrics. */\n name: string;\n /** Collection of custom properties. */\n properties?: { [propertyName: string]: string };\n /** Collection of custom measurements. */\n measurements?: { [propertyName: string]: number };\n};\n\n/** An instance of Exception represents a handled or unhandled exception that occurred during execution of the monitored application. */\nexport type TelemetryExceptionData = MonitorDomain & {\n /** Exception chain - list of inner exceptions. */\n exceptions: TelemetryExceptionDetails[];\n /** Severity level. Mostly used to indicate exception severity level when it is reported by logging library. */\n severityLevel?: SeverityLevel;\n /** Identifier of where the exception was thrown in code. Used for exceptions grouping. Typically a combination of exception type and a function from the call stack. */\n problemId?: string;\n /** Collection of custom properties. */\n properties?: { [propertyName: string]: string };\n /** Collection of custom measurements. */\n measurements?: { [propertyName: string]: number };\n};\n\n/** Instances of Message represent printf-like trace statements that are text-searched. Log4Net, NLog and other text-based log file entries are translated into instances of this type. The message does not have measurements. */\nexport type MessageData = MonitorDomain & {\n /** Trace message */\n message: string;\n /** Trace severity level. */\n severityLevel?: SeverityLevel;\n /** Collection of custom properties. */\n properties?: { [propertyName: string]: string };\n /** Collection of custom measurements. */\n measurements?: { [propertyName: string]: number };\n};\n\n/** An instance of the Metric item is a list of measurements (single data points) and/or aggregations. */\nexport type MetricsData = MonitorDomain & {\n /** List of metrics. Only one metric in the list is currently supported by Application Insights storage. If multiple data points were sent only the first one will be used. */\n metrics: MetricDataPoint[];\n /** Collection of custom properties. */\n properties?: { [propertyName: string]: string };\n};\n\n/** An instance of PageView represents a generic action on a page like a button click. It is also the base type for PageView. */\nexport type PageViewData = MonitorDomain & {\n /** Identifier of a page view instance. Used for correlation between page view and other telemetry items. */\n id: string;\n /** Event name. Keep it low cardinality to allow proper grouping and useful metrics. */\n name: string;\n /** Request URL with all query string parameters */\n url?: string;\n /** Request duration in format: DD.HH:MM:SS.MMMMMM. For a page view (PageViewData), this is the duration. For a page view with performance information (PageViewPerfData), this is the page load time. Must be less than 1000 days. */\n duration?: string;\n /** Fully qualified page URI or URL of the referring page; if unknown, leave blank */\n referredUri?: string;\n /** Collection of custom properties. */\n properties?: { [propertyName: string]: string };\n /** Collection of custom measurements. */\n measurements?: { [propertyName: string]: number };\n};\n\n/** An instance of PageViewPerf represents: a page view with no performance data, a page view with performance data, or just the performance data of an earlier page request. */\nexport type PageViewPerfData = MonitorDomain & {\n /** Identifier of a page view instance. Used for correlation between page view and other telemetry items. */\n id: string;\n /** Event name. Keep it low cardinality to allow proper grouping and useful metrics. */\n name: string;\n /** Request URL with all query string parameters */\n url?: string;\n /** Request duration in format: DD.HH:MM:SS.MMMMMM. For a page view (PageViewData), this is the duration. For a page view with performance information (PageViewPerfData), this is the page load time. Must be less than 1000 days. */\n duration?: string;\n /** Performance total in TimeSpan 'G' (general long) format: d:hh:mm:ss.fffffff */\n perfTotal?: string;\n /** Network connection time in TimeSpan 'G' (general long) format: d:hh:mm:ss.fffffff */\n networkConnect?: string;\n /** Sent request time in TimeSpan 'G' (general long) format: d:hh:mm:ss.fffffff */\n sentRequest?: string;\n /** Received response time in TimeSpan 'G' (general long) format: d:hh:mm:ss.fffffff */\n receivedResponse?: string;\n /** DOM processing time in TimeSpan 'G' (general long) format: d:hh:mm:ss.fffffff */\n domProcessing?: string;\n /** Collection of custom properties. */\n properties?: { [propertyName: string]: string };\n /** Collection of custom measurements. */\n measurements?: { [propertyName: string]: number };\n};\n\n/** An instance of Remote Dependency represents an interaction of the monitored component with a remote component/service like SQL or an HTTP endpoint. */\nexport type RemoteDependencyData = MonitorDomain & {\n /** Identifier of a dependency call instance. Used for correlation with the request telemetry item corresponding to this dependency call. */\n id?: string;\n /** Name of the command initiated with this dependency call. Low cardinality value. Examples are stored procedure name and URL path template. */\n name: string;\n /** Result code of a dependency call. Examples are SQL error code and HTTP status code. */\n resultCode?: string;\n /** Command initiated by this dependency call. Examples are SQL statement and HTTP URL with all query parameters. */\n data?: string;\n /** Dependency type name. Very low cardinality value for logical grouping of dependencies and interpretation of other fields like commandName and resultCode. Examples are SQL, Azure table, and HTTP. */\n type?: string;\n /** Target site of a dependency call. Examples are server name, host address. */\n target?: string;\n /** Request duration in format: DD.HH:MM:SS.MMMMMM. Must be less than 1000 days. */\n duration: string;\n /** Indication of successful or unsuccessful call. */\n success?: boolean;\n /** Collection of custom properties. */\n properties?: { [propertyName: string]: string };\n /** Collection of custom measurements. */\n measurements?: { [propertyName: string]: number };\n};\n\n/** An instance of Request represents completion of an external request to the application to do work and contains a summary of that request execution and the results. */\nexport type RequestData = MonitorDomain & {\n /** Identifier of a request call instance. Used for correlation between request and other telemetry items. */\n id: string;\n /** Name of the request. Represents code path taken to process request. Low cardinality value to allow better grouping of requests. For HTTP requests it represents the HTTP method and URL path template like 'GET /values/{id}'. */\n name?: string;\n /** Request duration in format: DD.HH:MM:SS.MMMMMM. Must be less than 1000 days. */\n duration: string;\n /** Indication of successful or unsuccessful call. */\n success: boolean;\n /** Result of a request execution. HTTP status code for HTTP requests. */\n responseCode: string;\n /** Source of the request. Examples are the instrumentation key of the caller or the ip address of the caller. */\n source?: string;\n /** Request URL with all query string parameters. */\n url?: string;\n /** Collection of custom properties. */\n properties?: { [propertyName: string]: string };\n /** Collection of custom measurements. */\n measurements?: { [propertyName: string]: number };\n};\n\n/** Known values of {@link DataPointType} that the service accepts. */\nexport enum KnownDataPointType {\n Measurement = \"Measurement\",\n Aggregation = \"Aggregation\"\n}\n\n/**\n * Defines values for DataPointType. \\\n * {@link KnownDataPointType} can be used interchangeably with DataPointType,\n * this enum contains the known values that the service supports.\n * ### Known values supported by the service\n * **Measurement** \\\n * **Aggregation**\n */\nexport type DataPointType = string;\n\n/** Known values of {@link SeverityLevel} that the service accepts. */\nexport enum KnownSeverityLevel {\n Verbose = \"Verbose\",\n Information = \"Information\",\n Warning = \"Warning\",\n Error = \"Error\",\n Critical = \"Critical\"\n}\n\n/**\n * Defines values for SeverityLevel. \\\n * {@link KnownSeverityLevel} can be used interchangeably with SeverityLevel,\n * this enum contains the known values that the service supports.\n * ### Known values supported by the service\n * **Verbose** \\\n * **Information** \\\n * **Warning** \\\n * **Error** \\\n * **Critical**\n */\nexport type SeverityLevel = string;\n\n/** Known values of {@link ContextTagKeys} that the service accepts. */\nexport enum KnownContextTagKeys {\n AiApplicationVer = \"ai.application.ver\",\n AiDeviceId = \"ai.device.id\",\n AiDeviceLocale = \"ai.device.locale\",\n AiDeviceModel = \"ai.device.model\",\n AiDeviceOemName = \"ai.device.oemName\",\n AiDeviceOsVersion = \"ai.device.osVersion\",\n AiDeviceType = \"ai.device.type\",\n AiLocationIp = \"ai.location.ip\",\n AiLocationCountry = \"ai.location.country\",\n AiLocationProvince = \"ai.location.province\",\n AiLocationCity = \"ai.location.city\",\n AiOperationId = \"ai.operation.id\",\n AiOperationName = \"ai.operation.name\",\n AiOperationParentId = \"ai.operation.parentId\",\n AiOperationSyntheticSource = \"ai.operation.syntheticSource\",\n AiOperationCorrelationVector = \"ai.operation.correlationVector\",\n AiSessionId = \"ai.session.id\",\n AiSessionIsFirst = \"ai.session.isFirst\",\n AiUserAccountId = \"ai.user.accountId\",\n AiUserId = \"ai.user.id\",\n AiUserAuthUserId = \"ai.user.authUserId\",\n AiCloudRole = \"ai.cloud.role\",\n AiCloudRoleVer = \"ai.cloud.roleVer\",\n AiCloudRoleInstance = \"ai.cloud.roleInstance\",\n AiCloudLocation = \"ai.cloud.location\",\n AiInternalSdkVersion = \"ai.internal.sdkVersion\",\n AiInternalAgentVersion = \"ai.internal.agentVersion\",\n AiInternalNodeName = \"ai.internal.nodeName\"\n}\n\n/**\n * Defines values for ContextTagKeys. \\\n * {@link KnownContextTagKeys} can be used interchangeably with ContextTagKeys,\n * this enum contains the known values that the service supports.\n * ### Known values supported by the service\n * **ai.application.ver** \\\n * **ai.device.id** \\\n * **ai.device.locale** \\\n * **ai.device.model** \\\n * **ai.device.oemName** \\\n * **ai.device.osVersion** \\\n * **ai.device.type** \\\n * **ai.location.ip** \\\n * **ai.location.country** \\\n * **ai.location.province** \\\n * **ai.location.city** \\\n * **ai.operation.id** \\\n * **ai.operation.name** \\\n * **ai.operation.parentId** \\\n * **ai.operation.syntheticSource** \\\n * **ai.operation.correlationVector** \\\n * **ai.session.id** \\\n * **ai.session.isFirst** \\\n * **ai.user.accountId** \\\n * **ai.user.id** \\\n * **ai.user.authUserId** \\\n * **ai.cloud.role** \\\n * **ai.cloud.roleVer** \\\n * **ai.cloud.roleInstance** \\\n * **ai.cloud.location** \\\n * **ai.internal.sdkVersion** \\\n * **ai.internal.agentVersion** \\\n * **ai.internal.nodeName**\n */\nexport type ContextTagKeys = string;\n\n/** Optional parameters. */\nexport interface ApplicationInsightsClientTrackOptionalParams\n extends coreClient.OperationOptions {}\n\n/** Contains response data for the track operation. */\nexport type ApplicationInsightsClientTrackResponse = TrackResponse;\n\n/** Optional parameters. */\nexport interface ApplicationInsightsClientOptionalParams\n extends coreClient.ServiceClientOptions {\n /** Breeze endpoint: https://dc.services.visualstudio.com */\n host?: string;\n /** Overrides client endpoint. */\n endpoint?: string;\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/generated/models/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAyQH,sEAAsE;AACtE,MAAM,CAAN,IAAY,kBAGX;AAHD,WAAY,kBAAkB;IAC5B,iDAA2B,CAAA;IAC3B,iDAA2B,CAAA;AAC7B,CAAC,EAHW,kBAAkB,KAAlB,kBAAkB,QAG7B;AAYD,sEAAsE;AACtE,MAAM,CAAN,IAAY,kBAMX;AAND,WAAY,kBAAkB;IAC5B,yCAAmB,CAAA;IACnB,iDAA2B,CAAA;IAC3B,yCAAmB,CAAA;IACnB,qCAAe,CAAA;IACf,2CAAqB,CAAA;AACvB,CAAC,EANW,kBAAkB,KAAlB,kBAAkB,QAM7B;AAeD,uEAAuE;AACvE,MAAM,CAAN,IAAY,mBA6BX;AA7BD,WAAY,mBAAmB;IAC7B,8DAAuC,CAAA;IACvC,kDAA2B,CAAA;IAC3B,0DAAmC,CAAA;IACnC,wDAAiC,CAAA;IACjC,4DAAqC,CAAA;IACrC,gEAAyC,CAAA;IACzC,sDAA+B,CAAA;IAC/B,sDAA+B,CAAA;IAC/B,gEAAyC,CAAA;IACzC,kEAA2C,CAAA;IAC3C,0DAAmC,CAAA;IACnC,wDAAiC,CAAA;IACjC,4DAAqC,CAAA;IACrC,oEAA6C,CAAA;IAC7C,kFAA2D,CAAA;IAC3D,sFAA+D,CAAA;IAC/D,oDAA6B,CAAA;IAC7B,8DAAuC,CAAA;IACvC,4DAAqC,CAAA;IACrC,8CAAuB,CAAA;IACvB,8DAAuC,CAAA;IACvC,oDAA6B,CAAA;IAC7B,0DAAmC,CAAA;IACnC,oEAA6C,CAAA;IAC7C,4DAAqC,CAAA;IACrC,sEAA+C,CAAA;IAC/C,0EAAmD,CAAA;IACnD,kEAA2C,CAAA;AAC7C,CAAC,EA7BW,mBAAmB,KAAnB,mBAAmB,QA6B9B","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\";\n\n/** System variables for a telemetry item. */\nexport interface TelemetryItem {\n /** Envelope version. For internal use only. By assigning this the default, it will not be serialized within the payload unless changed to a value other than #1. */\n version?: number;\n /** Type name of telemetry data item. */\n name: string;\n /** Event date time when telemetry item was created. This is the wall clock time on the client when the event was generated. There is no guarantee that the client's time is accurate. This field must be formatted in UTC ISO 8601 format, with a trailing 'Z' character, as described publicly on https://en.wikipedia.org/wiki/ISO_8601#UTC. Note: the number of decimal seconds digits provided are variable (and unspecified). Consumers should handle this, i.e. managed code consumers should not use format 'O' for parsing as it specifies a fixed length. Example: 2009-06-15T13:45:30.0000000Z. */\n time: Date;\n /** Sampling rate used in application. This telemetry item represents 100 / sampleRate actual telemetry items. */\n sampleRate?: number;\n /** Sequence field used to track absolute order of uploaded events. */\n sequence?: string;\n /** The instrumentation key of the Application Insights resource. */\n instrumentationKey?: string;\n /** Key/value collection of context properties. See ContextTagKeys for information on available properties. */\n tags?: { [propertyName: string]: string };\n /** Telemetry data item. */\n data?: MonitorBase;\n}\n\n/** Data struct to contain only C section with custom fields. */\nexport interface MonitorBase {\n /** Name of item (B section) if any. If telemetry data is derived straight from this, this should be null. */\n baseType?: string;\n /** The data payload for the telemetry request */\n baseData?: MonitorDomain;\n}\n\n/** The abstract common base of all domains. */\nexport interface MonitorDomain {\n /** Describes unknown properties. The value of an unknown property can be of \"any\" type. */\n [property: string]: any;\n /** Schema version */\n version: number;\n}\n\n/** Response containing the status of each telemetry item. */\nexport interface TrackResponse {\n /** The number of items received. */\n itemsReceived?: number;\n /** The number of items accepted. */\n itemsAccepted?: number;\n /** An array of error detail objects. */\n errors?: TelemetryErrorDetails[];\n}\n\n/** The error details */\nexport interface TelemetryErrorDetails {\n /** The index in the original payload of the item. */\n index?: number;\n /** The item specific [HTTP Response status code](#Response Status Codes). */\n statusCode?: number;\n /** The error message. */\n message?: string;\n}\n\n/** Metric data single measurement. */\nexport interface MetricDataPoint {\n /** Namespace of the metric. */\n namespace?: string;\n /** Name of the metric. */\n name: string;\n /** Metric type. Single measurement or the aggregated value. */\n dataPointType?: DataPointType;\n /** Single value for measurement. Sum of individual measurements for the aggregation. */\n value: number;\n /** Metric weight of the aggregated metric. Should not be set for a measurement. */\n count?: number;\n /** Minimum value of the aggregated metric. Should not be set for a measurement. */\n min?: number;\n /** Maximum value of the aggregated metric. Should not be set for a measurement. */\n max?: number;\n /** Standard deviation of the aggregated metric. Should not be set for a measurement. */\n stdDev?: number;\n}\n\n/** Exception details of the exception in a chain. */\nexport interface TelemetryExceptionDetails {\n /** In case exception is nested (outer exception contains inner one), the id and outerId properties are used to represent the nesting. */\n id?: number;\n /** The value of outerId is a reference to an element in ExceptionDetails that represents the outer exception */\n outerId?: number;\n /** Exception type name. */\n typeName?: string;\n /** Exception message. */\n message: string;\n /** Indicates if full exception stack is provided in the exception. The stack may be trimmed, such as in the case of a StackOverflow exception. */\n hasFullStack?: boolean;\n /** Text describing the stack. Either stack or parsedStack should have a value. */\n stack?: string;\n /** List of stack frames. Either stack or parsedStack should have a value. */\n parsedStack?: StackFrame[];\n}\n\n/** Stack frame information. */\nexport interface StackFrame {\n level: number;\n /** Method name. */\n method: string;\n /** Name of the assembly (dll, jar, etc.) containing this function. */\n assembly?: string;\n /** File name or URL of the method implementation. */\n fileName?: string;\n /** Line number of the code implementation. */\n line?: number;\n}\n\n/** Instances of AvailabilityData represent the result of executing an availability test. */\nexport type AvailabilityData = MonitorDomain & {\n /** Identifier of a test run. Use it to correlate steps of test run and telemetry generated by the service. */\n id: string;\n /** Name of the test that these availability results represent. */\n name: string;\n /** Duration in format: DD.HH:MM:SS.MMMMMM. Must be less than 1000 days. */\n duration: string;\n /** Success flag. */\n success: boolean;\n /** Name of the location where the test was run from. */\n runLocation?: string;\n /** Diagnostic message for the result. */\n message?: string;\n /** Collection of custom properties. */\n properties?: { [propertyName: string]: string };\n /** Collection of custom measurements. */\n measurements?: { [propertyName: string]: number };\n};\n\n/** Instances of Event represent structured event records that can be grouped and searched by their properties. Event data item also creates a metric of event count by name. */\nexport type TelemetryEventData = MonitorDomain & {\n /** Event name. Keep it low cardinality to allow proper grouping and useful metrics. */\n name: string;\n /** Collection of custom properties. */\n properties?: { [propertyName: string]: string };\n /** Collection of custom measurements. */\n measurements?: { [propertyName: string]: number };\n};\n\n/** An instance of Exception represents a handled or unhandled exception that occurred during execution of the monitored application. */\nexport type TelemetryExceptionData = MonitorDomain & {\n /** Exception chain - list of inner exceptions. */\n exceptions: TelemetryExceptionDetails[];\n /** Severity level. Mostly used to indicate exception severity level when it is reported by logging library. */\n severityLevel?: SeverityLevel;\n /** Identifier of where the exception was thrown in code. Used for exceptions grouping. Typically a combination of exception type and a function from the call stack. */\n problemId?: string;\n /** Collection of custom properties. */\n properties?: { [propertyName: string]: string };\n /** Collection of custom measurements. */\n measurements?: { [propertyName: string]: number };\n};\n\n/** Instances of Message represent printf-like trace statements that are text-searched. Log4Net, NLog and other text-based log file entries are translated into instances of this type. The message does not have measurements. */\nexport type MessageData = MonitorDomain & {\n /** Trace message */\n message: string;\n /** Trace severity level. */\n severityLevel?: SeverityLevel;\n /** Collection of custom properties. */\n properties?: { [propertyName: string]: string };\n /** Collection of custom measurements. */\n measurements?: { [propertyName: string]: number };\n};\n\n/** An instance of the Metric item is a list of measurements (single data points) and/or aggregations. */\nexport type MetricsData = MonitorDomain & {\n /** List of metrics. Only one metric in the list is currently supported by Application Insights storage. If multiple data points were sent only the first one will be used. */\n metrics: MetricDataPoint[];\n /** Collection of custom properties. */\n properties?: { [propertyName: string]: string };\n};\n\n/** An instance of PageView represents a generic action on a page like a button click. It is also the base type for PageView. */\nexport type PageViewData = MonitorDomain & {\n /** Identifier of a page view instance. Used for correlation between page view and other telemetry items. */\n id: string;\n /** Event name. Keep it low cardinality to allow proper grouping and useful metrics. */\n name: string;\n /** Request URL with all query string parameters */\n url?: string;\n /** Request duration in format: DD.HH:MM:SS.MMMMMM. For a page view (PageViewData), this is the duration. For a page view with performance information (PageViewPerfData), this is the page load time. Must be less than 1000 days. */\n duration?: string;\n /** Fully qualified page URI or URL of the referring page; if unknown, leave blank */\n referredUri?: string;\n /** Collection of custom properties. */\n properties?: { [propertyName: string]: string };\n /** Collection of custom measurements. */\n measurements?: { [propertyName: string]: number };\n};\n\n/** An instance of PageViewPerf represents: a page view with no performance data, a page view with performance data, or just the performance data of an earlier page request. */\nexport type PageViewPerfData = MonitorDomain & {\n /** Identifier of a page view instance. Used for correlation between page view and other telemetry items. */\n id: string;\n /** Event name. Keep it low cardinality to allow proper grouping and useful metrics. */\n name: string;\n /** Request URL with all query string parameters */\n url?: string;\n /** Request duration in format: DD.HH:MM:SS.MMMMMM. For a page view (PageViewData), this is the duration. For a page view with performance information (PageViewPerfData), this is the page load time. Must be less than 1000 days. */\n duration?: string;\n /** Performance total in TimeSpan 'G' (general long) format: d:hh:mm:ss.fffffff */\n perfTotal?: string;\n /** Network connection time in TimeSpan 'G' (general long) format: d:hh:mm:ss.fffffff */\n networkConnect?: string;\n /** Sent request time in TimeSpan 'G' (general long) format: d:hh:mm:ss.fffffff */\n sentRequest?: string;\n /** Received response time in TimeSpan 'G' (general long) format: d:hh:mm:ss.fffffff */\n receivedResponse?: string;\n /** DOM processing time in TimeSpan 'G' (general long) format: d:hh:mm:ss.fffffff */\n domProcessing?: string;\n /** Collection of custom properties. */\n properties?: { [propertyName: string]: string };\n /** Collection of custom measurements. */\n measurements?: { [propertyName: string]: number };\n};\n\n/** An instance of Remote Dependency represents an interaction of the monitored component with a remote component/service like SQL or an HTTP endpoint. */\nexport type RemoteDependencyData = MonitorDomain & {\n /** Identifier of a dependency call instance. Used for correlation with the request telemetry item corresponding to this dependency call. */\n id?: string;\n /** Name of the command initiated with this dependency call. Low cardinality value. Examples are stored procedure name and URL path template. */\n name: string;\n /** Result code of a dependency call. Examples are SQL error code and HTTP status code. */\n resultCode?: string;\n /** Command initiated by this dependency call. Examples are SQL statement and HTTP URL with all query parameters. */\n data?: string;\n /** Dependency type name. Very low cardinality value for logical grouping of dependencies and interpretation of other fields like commandName and resultCode. Examples are SQL, Azure table, and HTTP. */\n type?: string;\n /** Target site of a dependency call. Examples are server name, host address. */\n target?: string;\n /** Request duration in format: DD.HH:MM:SS.MMMMMM. Must be less than 1000 days. */\n duration: string;\n /** Indication of successful or unsuccessful call. */\n success?: boolean;\n /** Collection of custom properties. */\n properties?: { [propertyName: string]: string };\n /** Collection of custom measurements. */\n measurements?: { [propertyName: string]: number };\n};\n\n/** An instance of Request represents completion of an external request to the application to do work and contains a summary of that request execution and the results. */\nexport type RequestData = MonitorDomain & {\n /** Identifier of a request call instance. Used for correlation between request and other telemetry items. */\n id: string;\n /** Name of the request. Represents code path taken to process request. Low cardinality value to allow better grouping of requests. For HTTP requests it represents the HTTP method and URL path template like 'GET /values/{id}'. */\n name?: string;\n /** Request duration in format: DD.HH:MM:SS.MMMMMM. Must be less than 1000 days. */\n duration: string;\n /** Indication of successful or unsuccessful call. */\n success: boolean;\n /** Result of a request execution. HTTP status code for HTTP requests. */\n responseCode: string;\n /** Source of the request. Examples are the instrumentation key of the caller or the ip address of the caller. */\n source?: string;\n /** Request URL with all query string parameters. */\n url?: string;\n /** Collection of custom properties. */\n properties?: { [propertyName: string]: string };\n /** Collection of custom measurements. */\n measurements?: { [propertyName: string]: number };\n};\n\n/** Known values of {@link DataPointType} that the service accepts. */\nexport enum KnownDataPointType {\n Measurement = \"Measurement\",\n Aggregation = \"Aggregation\"\n}\n\n/**\n * Defines values for DataPointType. \\\n * {@link KnownDataPointType} can be used interchangeably with DataPointType,\n * this enum contains the known values that the service supports.\n * ### Known values supported by the service\n * **Measurement** \\\n * **Aggregation**\n */\nexport type DataPointType = string;\n\n/** Known values of {@link SeverityLevel} that the service accepts. */\nexport enum KnownSeverityLevel {\n Verbose = \"Verbose\",\n Information = \"Information\",\n Warning = \"Warning\",\n Error = \"Error\",\n Critical = \"Critical\"\n}\n\n/**\n * Defines values for SeverityLevel. \\\n * {@link KnownSeverityLevel} can be used interchangeably with SeverityLevel,\n * this enum contains the known values that the service supports.\n * ### Known values supported by the service\n * **Verbose** \\\n * **Information** \\\n * **Warning** \\\n * **Error** \\\n * **Critical**\n */\nexport type SeverityLevel = string;\n\n/** Known values of {@link ContextTagKeys} that the service accepts. */\nexport enum KnownContextTagKeys {\n AiApplicationVer = \"ai.application.ver\",\n AiDeviceId = \"ai.device.id\",\n AiDeviceLocale = \"ai.device.locale\",\n AiDeviceModel = \"ai.device.model\",\n AiDeviceOemName = \"ai.device.oemName\",\n AiDeviceOsVersion = \"ai.device.osVersion\",\n AiDeviceType = \"ai.device.type\",\n AiLocationIp = \"ai.location.ip\",\n AiLocationCountry = \"ai.location.country\",\n AiLocationProvince = \"ai.location.province\",\n AiLocationCity = \"ai.location.city\",\n AiOperationId = \"ai.operation.id\",\n AiOperationName = \"ai.operation.name\",\n AiOperationParentId = \"ai.operation.parentId\",\n AiOperationSyntheticSource = \"ai.operation.syntheticSource\",\n AiOperationCorrelationVector = \"ai.operation.correlationVector\",\n AiSessionId = \"ai.session.id\",\n AiSessionIsFirst = \"ai.session.isFirst\",\n AiUserAccountId = \"ai.user.accountId\",\n AiUserId = \"ai.user.id\",\n AiUserAuthUserId = \"ai.user.authUserId\",\n AiCloudRole = \"ai.cloud.role\",\n AiCloudRoleVer = \"ai.cloud.roleVer\",\n AiCloudRoleInstance = \"ai.cloud.roleInstance\",\n AiCloudLocation = \"ai.cloud.location\",\n AiInternalSdkVersion = \"ai.internal.sdkVersion\",\n AiInternalAgentVersion = \"ai.internal.agentVersion\",\n AiInternalNodeName = \"ai.internal.nodeName\"\n}\n\n/**\n * Defines values for ContextTagKeys. \\\n * {@link KnownContextTagKeys} can be used interchangeably with ContextTagKeys,\n * this enum contains the known values that the service supports.\n * ### Known values supported by the service\n * **ai.application.ver** \\\n * **ai.device.id** \\\n * **ai.device.locale** \\\n * **ai.device.model** \\\n * **ai.device.oemName** \\\n * **ai.device.osVersion** \\\n * **ai.device.type** \\\n * **ai.location.ip** \\\n * **ai.location.country** \\\n * **ai.location.province** \\\n * **ai.location.city** \\\n * **ai.operation.id** \\\n * **ai.operation.name** \\\n * **ai.operation.parentId** \\\n * **ai.operation.syntheticSource** \\\n * **ai.operation.correlationVector** \\\n * **ai.session.id** \\\n * **ai.session.isFirst** \\\n * **ai.user.accountId** \\\n * **ai.user.id** \\\n * **ai.user.authUserId** \\\n * **ai.cloud.role** \\\n * **ai.cloud.roleVer** \\\n * **ai.cloud.roleInstance** \\\n * **ai.cloud.location** \\\n * **ai.internal.sdkVersion** \\\n * **ai.internal.agentVersion** \\\n * **ai.internal.nodeName**\n */\nexport type ContextTagKeys = string;\n\n/** Optional parameters. */\nexport interface TrackOptionalParams extends coreClient.OperationOptions {}\n\n/** Contains response data for the track operation. */\nexport type TrackOperationResponse = TrackResponse;\n\n/** Optional parameters. */\nexport interface ApplicationInsightsClientOptionalParams\n extends coreClient.ServiceClientOptions {\n /** Breeze endpoint: https://dc.services.visualstudio.com */\n host?: string;\n /** Overrides client endpoint. */\n endpoint?: string;\n}\n"]}
@@ -1,5 +1,7 @@
1
1
  // Copyright (c) Microsoft Corporation.
2
2
  // Licensed under the MIT license.
3
+ export { AzureMonitorBaseExporter } from "./export/base";
3
4
  export { AzureMonitorTraceExporter } from "./export/trace";
5
+ export { AzureMonitorMetricExporter } from "./export/metric";
4
6
  export { ServiceApiVersion } from "./Declarations/Constants";
5
7
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,yBAAyB,EAAE,MAAM,gBAAgB,CAAC;AAE3D,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nexport { AzureMonitorTraceExporter } from \"./export/trace\";\nexport { AzureExporterConfig } from \"./config\";\nexport { ServiceApiVersion } from \"./Declarations/Constants\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,wBAAwB,EAAE,MAAM,eAAe,CAAC;AACzD,OAAO,EAAE,yBAAyB,EAAE,MAAM,gBAAgB,CAAC;AAC3D,OAAO,EAAE,0BAA0B,EAAE,MAAM,iBAAiB,CAAC;AAE7D,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nexport { AzureMonitorBaseExporter } from \"./export/base\";\nexport { AzureMonitorTraceExporter } from \"./export/trace\";\nexport { AzureMonitorMetricExporter } from \"./export/metric\";\nexport { AzureExporterConfig } from \"./config\";\nexport { ServiceApiVersion } from \"./Declarations/Constants\";\nexport { MonitorBase, MonitorDomain, TelemetryItem } from \"./generated/models\";\n"]}
@@ -7,6 +7,6 @@
7
7
  export const SDK_INFO = {
8
8
  NAME: "opentelemetry",
9
9
  RUNTIME: "node",
10
- LANGUAGE: "nodejs"
10
+ LANGUAGE: "nodejs",
11
11
  };
12
12
  //# sourceMappingURL=constants.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../../src/platform/nodejs/constants.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC;;;GAGG;AACH,MAAM,CAAC,MAAM,QAAQ,GAAG;IACtB,IAAI,EAAE,eAAe;IACrB,OAAO,EAAE,MAAM;IACf,QAAQ,EAAE,QAAQ;CACnB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/**\n * SDK info\n * @internal\n */\nexport const SDK_INFO = {\n NAME: \"opentelemetry\",\n RUNTIME: \"node\",\n LANGUAGE: \"nodejs\"\n};\n"]}
1
+ {"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../../src/platform/nodejs/constants.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC;;;GAGG;AACH,MAAM,CAAC,MAAM,QAAQ,GAAG;IACtB,IAAI,EAAE,eAAe;IACrB,OAAO,EAAE,MAAM;IACf,QAAQ,EAAE,QAAQ;CACnB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/**\n * SDK info\n * @internal\n */\nexport const SDK_INFO = {\n NAME: \"opentelemetry\",\n RUNTIME: \"node\",\n LANGUAGE: \"nodejs\",\n};\n"]}
@@ -2,8 +2,9 @@
2
2
  // Licensed under the MIT license.
3
3
  import url from "url";
4
4
  import { diag } from "@opentelemetry/api";
5
- import { redirectPolicyName } from "@azure/core-rest-pipeline";
6
- import { ApplicationInsightsClient } from "../../generated";
5
+ import { bearerTokenAuthenticationPolicy, redirectPolicyName } from "@azure/core-rest-pipeline";
6
+ import { ApplicationInsightsClient, } from "../../generated";
7
+ const applicationInsightsResource = "https://monitor.azure.com//.default";
7
8
  /**
8
9
  * Exporter HTTP sender class
9
10
  * @internal
@@ -13,10 +14,18 @@ export class HttpSender {
13
14
  this._exporterOptions = _exporterOptions;
14
15
  // Build endpoint using provided configuration or default values
15
16
  this._appInsightsClientOptions = {
16
- host: this._exporterOptions.endpointUrl
17
+ host: this._exporterOptions.endpointUrl,
17
18
  };
18
19
  this._appInsightsClient = new ApplicationInsightsClient(Object.assign({}, this._appInsightsClientOptions));
20
+ // Handle redirects in HTTP Sender
19
21
  this._appInsightsClient.pipeline.removePolicy({ name: redirectPolicyName });
22
+ if (this._exporterOptions.aadTokenCredential) {
23
+ let scopes = [applicationInsightsResource];
24
+ this._appInsightsClient.pipeline.addPolicy(bearerTokenAuthenticationPolicy({
25
+ credential: this._exporterOptions.aadTokenCredential,
26
+ scopes: scopes,
27
+ }));
28
+ }
20
29
  }
21
30
  /**
22
31
  * Send Azure envelopes
@@ -1 +1 @@
1
- {"version":3,"file":"httpSender.js","sourceRoot":"","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,CAAE,UAAU,mCAAI,EAAE,EAAE,CAAC;SAC7E;QAAC,OAAO,CAAC,EAAE;YACV,MAAM,CAAC,CAAC;SACT;IACH,CAAC;IAED;;;OAGG;IACH,KAAK,CAAC,QAAQ;QACZ,IAAI,CAAC,IAAI,CAAC,0BAA0B,CAAC,CAAC;IACxC,CAAC;IAED,uBAAuB,CAAC,QAA4B;QAClD,IAAI,QAAQ,EAAE;YACZ,MAAM,MAAM,GAAG,IAAI,GAAG,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;YACrC,IAAI,MAAM,IAAI,MAAM,CAAC,IAAI,EAAE;gBACzB,IAAI,CAAC,kBAAkB,CAAC,IAAI,GAAG,UAAU,GAAG,MAAM,CAAC,IAAI,CAAC;aACzD;SACF;IACH,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\nimport url from \"url\";\nimport { diag } from \"@opentelemetry/api\";\nimport { FullOperationResponse } from \"@azure/core-client\";\nimport { redirectPolicyName } from \"@azure/core-rest-pipeline\";\nimport { Sender, SenderResult } from \"../../types\";\nimport {\n TelemetryItem as Envelope,\n ApplicationInsightsClient,\n ApplicationInsightsClientOptionalParams,\n ApplicationInsightsClientTrackOptionalParams\n} from \"../../generated\";\nimport { AzureExporterInternalConfig } from \"../../config\";\n\n/**\n * Exporter HTTP sender class\n * @internal\n */\nexport class HttpSender implements Sender {\n private readonly _appInsightsClient: ApplicationInsightsClient;\n private _appInsightsClientOptions: ApplicationInsightsClientOptionalParams;\n\n constructor(private _exporterOptions: AzureExporterInternalConfig) {\n // Build endpoint using provided configuration or default values\n this._appInsightsClientOptions = {\n host: this._exporterOptions.endpointUrl\n };\n\n this._appInsightsClient = new ApplicationInsightsClient({\n ...this._appInsightsClientOptions\n });\n\n this._appInsightsClient.pipeline.removePolicy({ name: redirectPolicyName });\n }\n\n /**\n * Send Azure envelopes\n * @internal\n */\n async send(envelopes: Envelope[]): Promise<SenderResult> {\n let options: ApplicationInsightsClientTrackOptionalParams = {};\n try {\n let response: FullOperationResponse | undefined;\n function onResponse(rawResponse: FullOperationResponse, flatResponse: unknown): void {\n response = rawResponse;\n if (options.onResponse) {\n options.onResponse(rawResponse, flatResponse);\n }\n }\n await this._appInsightsClient.track(envelopes, {\n ...options,\n onResponse\n });\n\n return { statusCode: response?.status, result: response?.bodyAsText ?? \"\" };\n } catch (e) {\n throw e;\n }\n }\n\n /**\n * Shutdown sender\n * @internal\n */\n async shutdown(): Promise<void> {\n diag.info(\"HttpSender shutting down\");\n }\n\n handlePermanentRedirect(location: string | undefined) {\n if (location) {\n const locUrl = new url.URL(location);\n if (locUrl && locUrl.host) {\n this._appInsightsClient.host = \"https://\" + locUrl.host;\n }\n }\n }\n}\n"]}
1
+ {"version":3,"file":"httpSender.js","sourceRoot":"","sources":["../../../../src/platform/nodejs/httpSender.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAClC,OAAO,GAAG,MAAM,KAAK,CAAC;AACtB,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAE1C,OAAO,EAAE,+BAA+B,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAEhG,OAAO,EAEL,yBAAyB,GAG1B,MAAM,iBAAiB,CAAC;AAGzB,MAAM,2BAA2B,GAAG,qCAAqC,CAAC;AAE1E;;;GAGG;AACH,MAAM,OAAO,UAAU;IAIrB,YAAoB,gBAA6C;QAA7C,qBAAgB,GAAhB,gBAAgB,CAA6B;QAC/D,gEAAgE;QAChE,IAAI,CAAC,yBAAyB,GAAG;YAC/B,IAAI,EAAE,IAAI,CAAC,gBAAgB,CAAC,WAAW;SACxC,CAAC;QACF,IAAI,CAAC,kBAAkB,GAAG,IAAI,yBAAyB,mBAClD,IAAI,CAAC,yBAAyB,EACjC,CAAC;QACH,kCAAkC;QAClC,IAAI,CAAC,kBAAkB,CAAC,QAAQ,CAAC,YAAY,CAAC,EAAE,IAAI,EAAE,kBAAkB,EAAE,CAAC,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ACzB,IAAI,CAAC,kBAAkB,CAAC,IAAI,GAAG,UAAU,GAAG,MAAM,CAAC,IAAI,CAAC;aACzD;SACF;IACH,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\nimport url from \"url\";\nimport { diag } from \"@opentelemetry/api\";\nimport { FullOperationResponse } from \"@azure/core-client\";\nimport { bearerTokenAuthenticationPolicy, redirectPolicyName } from \"@azure/core-rest-pipeline\";\nimport { Sender, SenderResult } from \"../../types\";\nimport {\n TelemetryItem as Envelope,\n ApplicationInsightsClient,\n ApplicationInsightsClientOptionalParams,\n TrackOptionalParams,\n} from \"../../generated\";\nimport { AzureExporterInternalConfig } from \"../../config\";\n\nconst applicationInsightsResource = \"https://monitor.azure.com//.default\";\n\n/**\n * Exporter HTTP sender class\n * @internal\n */\nexport class HttpSender implements Sender {\n private readonly _appInsightsClient: ApplicationInsightsClient;\n private _appInsightsClientOptions: ApplicationInsightsClientOptionalParams;\n\n constructor(private _exporterOptions: AzureExporterInternalConfig) {\n // Build endpoint using provided configuration or default values\n this._appInsightsClientOptions = {\n host: this._exporterOptions.endpointUrl,\n };\n this._appInsightsClient = new ApplicationInsightsClient({\n ...this._appInsightsClientOptions,\n });\n // Handle redirects in HTTP Sender\n this._appInsightsClient.pipeline.removePolicy({ name: redirectPolicyName });\n\n if (this._exporterOptions.aadTokenCredential) {\n let scopes: string[] = [applicationInsightsResource];\n this._appInsightsClient.pipeline.addPolicy(\n bearerTokenAuthenticationPolicy({\n credential: this._exporterOptions.aadTokenCredential,\n scopes: scopes,\n })\n );\n }\n }\n\n /**\n * Send Azure envelopes\n * @internal\n */\n async send(envelopes: Envelope[]): Promise<SenderResult> {\n let options: TrackOptionalParams = {};\n try {\n let response: FullOperationResponse | undefined;\n function onResponse(rawResponse: FullOperationResponse, flatResponse: unknown): void {\n response = rawResponse;\n if (options.onResponse) {\n options.onResponse(rawResponse, flatResponse);\n }\n }\n await this._appInsightsClient.track(envelopes, {\n ...options,\n onResponse,\n });\n\n return { statusCode: response?.status, result: response?.bodyAsText ?? \"\" };\n } catch (e: any) {\n throw e;\n }\n }\n\n /**\n * Shutdown sender\n * @internal\n */\n async shutdown(): Promise<void> {\n diag.info(\"HttpSender shutting down\");\n }\n\n handlePermanentRedirect(location: string | undefined) {\n if (location) {\n const locUrl = new url.URL(location);\n if (locUrl && locUrl.host) {\n this._appInsightsClient.host = \"https://\" + locUrl.host;\n }\n }\n }\n}\n"]}
@@ -0,0 +1,171 @@
1
+ // Copyright (c) Microsoft Corporation.
2
+ // Licensed under the MIT license.
3
+ import * as fs from "fs";
4
+ import * as os from "os";
5
+ import * as child_process from "child_process";
6
+ import { diag } from "@opentelemetry/api";
7
+ export class FileAccessControl {
8
+ // Check if file access control could be enabled
9
+ static checkFileProtection() {
10
+ if (!FileAccessControl.OS_PROVIDES_FILE_PROTECTION &&
11
+ !FileAccessControl.OS_FILE_PROTECTION_CHECKED) {
12
+ FileAccessControl.OS_FILE_PROTECTION_CHECKED = true;
13
+ // Node's chmod levels do not appropriately restrict file access on Windows
14
+ // Use the built-in command line tool ICACLS on Windows to properly restrict
15
+ // access to the temporary directory used for disk retry mode.
16
+ if (FileAccessControl.USE_ICACLS) {
17
+ // This should be async - but it's currently safer to have this synchronous
18
+ // This guarantees we can immediately fail setDiskRetryMode if we need to
19
+ try {
20
+ FileAccessControl.OS_PROVIDES_FILE_PROTECTION = fs.existsSync(FileAccessControl.ICACLS_PATH);
21
+ }
22
+ catch (e) {
23
+ // Ignore error
24
+ }
25
+ if (!FileAccessControl.OS_PROVIDES_FILE_PROTECTION) {
26
+ diag.warn("Could not find ICACLS in expected location! This is necessary to use disk retry mode on Windows.");
27
+ }
28
+ }
29
+ else {
30
+ // chmod works everywhere else
31
+ FileAccessControl.OS_PROVIDES_FILE_PROTECTION = true;
32
+ }
33
+ }
34
+ }
35
+ static async applyACLRules(directory) {
36
+ if (FileAccessControl.USE_ICACLS) {
37
+ if (FileAccessControl.ACLED_DIRECTORIES[directory] === undefined) {
38
+ // Avoid multiple calls race condition by setting ACLED_DIRECTORIES to false for this directory immediately
39
+ // If batches are being failed faster than the processes spawned below return, some data won't be stored to disk
40
+ // This is better than the alternative of potentially infinitely spawned processes
41
+ FileAccessControl.ACLED_DIRECTORIES[directory] = false;
42
+ try {
43
+ // Restrict this directory to only current user and administrator access
44
+ let identity = await this._getACLIdentity();
45
+ await this._runICACLS(this._getACLArguments(directory, identity));
46
+ FileAccessControl.ACLED_DIRECTORIES[directory] = true;
47
+ }
48
+ catch (ex) {
49
+ FileAccessControl.ACLED_DIRECTORIES[directory] = false; // false is used to cache failed (vs undefined which is "not yet tried")
50
+ throw ex;
51
+ }
52
+ }
53
+ else {
54
+ if (!FileAccessControl.ACLED_DIRECTORIES[directory]) {
55
+ throw new Error("Setting ACL restrictions did not succeed (cached result)");
56
+ }
57
+ }
58
+ }
59
+ }
60
+ static applyACLRulesSync(directory) {
61
+ if (FileAccessControl.USE_ICACLS) {
62
+ // For performance, only run ACL rules if we haven't already during this session
63
+ if (FileAccessControl.ACLED_DIRECTORIES[directory] === undefined) {
64
+ this._runICACLSSync(this._getACLArguments(directory, this._getACLIdentitySync()));
65
+ FileAccessControl.ACLED_DIRECTORIES[directory] = true; // If we get here, it succeeded. _runIACLSSync will throw on failures
66
+ return;
67
+ }
68
+ else if (!FileAccessControl.ACLED_DIRECTORIES[directory]) {
69
+ // falsy but not undefined
70
+ throw new Error("Setting ACL restrictions did not succeed (cached result)");
71
+ }
72
+ }
73
+ }
74
+ static _runICACLS(args) {
75
+ return new Promise((resolve, reject) => {
76
+ var aclProc = child_process.spawn(FileAccessControl.ICACLS_PATH, args, {
77
+ windowsHide: true,
78
+ });
79
+ aclProc.on("error", (e) => reject(e));
80
+ aclProc.on("close", (code) => {
81
+ if (code === 0) {
82
+ resolve();
83
+ }
84
+ else {
85
+ reject(new Error(`Setting ACL restrictions did not succeed (ICACLS returned code ${code})`));
86
+ }
87
+ });
88
+ });
89
+ }
90
+ static _runICACLSSync(args) {
91
+ // Some very old versions of Node (< 0.11) don't have this
92
+ if (child_process.spawnSync) {
93
+ var aclProc = child_process.spawnSync(FileAccessControl.ICACLS_PATH, args, {
94
+ windowsHide: true,
95
+ });
96
+ if (aclProc.error) {
97
+ throw aclProc.error;
98
+ }
99
+ else if (aclProc.status !== 0) {
100
+ throw new Error(`Setting ACL restrictions did not succeed (ICACLS returned code ${aclProc.status})`);
101
+ }
102
+ }
103
+ else {
104
+ throw new Error("Could not synchronously call ICACLS under current version of Node.js");
105
+ }
106
+ }
107
+ static _getACLIdentity() {
108
+ return new Promise((resolve, reject) => {
109
+ if (FileAccessControl.ACL_IDENTITY) {
110
+ resolve(FileAccessControl.ACL_IDENTITY);
111
+ }
112
+ var psProc = child_process.spawn(FileAccessControl.POWERSHELL_PATH, ["-Command", "[System.Security.Principal.WindowsIdentity]::GetCurrent().Name"], {
113
+ windowsHide: true,
114
+ stdio: ["ignore", "pipe", "pipe"], // Needed to prevent hanging on Win 7
115
+ });
116
+ let data = "";
117
+ psProc.stdout.on("data", (d) => (data += d));
118
+ psProc.on("error", (e) => reject(e));
119
+ psProc.on("close", (code) => {
120
+ FileAccessControl.ACL_IDENTITY = data && data.trim();
121
+ if (code === 0) {
122
+ resolve(FileAccessControl.ACL_IDENTITY);
123
+ }
124
+ else {
125
+ reject(new Error(`Getting ACL identity did not succeed (PS returned code ${code})`));
126
+ }
127
+ });
128
+ });
129
+ }
130
+ static _getACLIdentitySync() {
131
+ if (FileAccessControl.ACL_IDENTITY) {
132
+ return FileAccessControl.ACL_IDENTITY;
133
+ }
134
+ // Some very old versions of Node (< 0.11) don't have this
135
+ if (child_process.spawnSync) {
136
+ var psProc = child_process.spawnSync(FileAccessControl.POWERSHELL_PATH, ["-Command", "[System.Security.Principal.WindowsIdentity]::GetCurrent().Name"], {
137
+ windowsHide: true,
138
+ stdio: ["ignore", "pipe", "pipe"], // Needed to prevent hanging on Win 7
139
+ });
140
+ if (psProc.error) {
141
+ throw psProc.error;
142
+ }
143
+ else if (psProc.status !== 0) {
144
+ throw new Error(`Getting ACL identity did not succeed (PS returned code ${psProc.status})`);
145
+ }
146
+ FileAccessControl.ACL_IDENTITY = psProc.stdout && psProc.stdout.toString().trim();
147
+ return FileAccessControl.ACL_IDENTITY;
148
+ }
149
+ else {
150
+ throw new Error("Could not synchronously get ACL identity under current version of Node.js");
151
+ }
152
+ }
153
+ static _getACLArguments(directory, identity) {
154
+ return [
155
+ directory,
156
+ "/grant",
157
+ "*S-1-5-32-544:(OI)(CI)F",
158
+ "/grant",
159
+ `${identity}:(OI)(CI)F`,
160
+ "/inheritance:r",
161
+ ]; // Remove all inherited permissions
162
+ }
163
+ }
164
+ FileAccessControl.ICACLS_PATH = `${process.env.systemdrive}/windows/system32/icacls.exe`;
165
+ FileAccessControl.POWERSHELL_PATH = `${process.env.systemdrive}/windows/system32/windowspowershell/v1.0/powershell.exe`;
166
+ FileAccessControl.ACLED_DIRECTORIES = {};
167
+ FileAccessControl.ACL_IDENTITY = null;
168
+ FileAccessControl.OS_FILE_PROTECTION_CHECKED = false;
169
+ FileAccessControl.OS_PROVIDES_FILE_PROTECTION = false;
170
+ FileAccessControl.USE_ICACLS = os.type() === "Windows_NT";
171
+ //# sourceMappingURL=fileAccessControl.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fileAccessControl.js","sourceRoot":"","sources":["../../../../../src/platform/nodejs/persist/fileAccessControl.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,KAAK,aAAa,MAAM,eAAe,CAAC;AAC/C,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAE1C,MAAM,OAAO,iBAAiB;IAS5B,gDAAgD;IACzC,MAAM,CAAC,mBAAmB;QAC/B,IACE,CAAC,iBAAiB,CAAC,2BAA2B;YAC9C,CAAC,i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E,CAAC,CAAC;SAC9F;IACH,CAAC;IAEO,MAAM,CAAC,gBAAgB,CAAC,SAAiB,EAAE,QAAgB;QACjE,OAAO;YACL,SAAS;YACT,QAAQ;YACR,yBAAyB;YACzB,QAAQ;YACR,GAAG,QAAQ,YAAY;YACvB,gBAAgB;SACjB,CAAC,CAAC,mCAAmC;IACxC,CAAC;;AAhLc,6BAAW,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,WAAW,8BAA8B,CAAC;AACvE,iCAAe,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,WAAW,yDAAyD,CAAC;AACtG,mCAAiB,GAA8B,EAAE,CAAC;AAClD,8BAAY,GAAkB,IAAI,CAAC;AACnC,4CAA0B,GAAG,KAAK,CAAC;AACpC,6CAA2B,GAAG,KAAK,CAAC;AACpC,4BAAU,GAAG,EAAE,CAAC,IAAI,EAAE,KAAK,YAAY,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 child_process from \"child_process\";\nimport { diag } from \"@opentelemetry/api\";\n\nexport class FileAccessControl {\n private static ICACLS_PATH = `${process.env.systemdrive}/windows/system32/icacls.exe`;\n private static POWERSHELL_PATH = `${process.env.systemdrive}/windows/system32/windowspowershell/v1.0/powershell.exe`;\n private static ACLED_DIRECTORIES: { [id: string]: boolean } = {};\n private static ACL_IDENTITY: string | null = null;\n private static OS_FILE_PROTECTION_CHECKED = false;\n public static OS_PROVIDES_FILE_PROTECTION = false;\n public static USE_ICACLS = os.type() === \"Windows_NT\";\n\n // Check if file access control could be enabled\n public static checkFileProtection() {\n if (\n !FileAccessControl.OS_PROVIDES_FILE_PROTECTION &&\n !FileAccessControl.OS_FILE_PROTECTION_CHECKED\n ) {\n FileAccessControl.OS_FILE_PROTECTION_CHECKED = true;\n // Node's chmod levels do not appropriately restrict file access on Windows\n // Use the built-in command line tool ICACLS on Windows to properly restrict\n // access to the temporary directory used for disk retry mode.\n if (FileAccessControl.USE_ICACLS) {\n // This should be async - but it's currently safer to have this synchronous\n // This guarantees we can immediately fail setDiskRetryMode if we need to\n try {\n FileAccessControl.OS_PROVIDES_FILE_PROTECTION = fs.existsSync(\n FileAccessControl.ICACLS_PATH\n );\n } catch (e: any) {\n // Ignore error\n }\n if (!FileAccessControl.OS_PROVIDES_FILE_PROTECTION) {\n diag.warn(\n \"Could not find ICACLS in expected location! This is necessary to use disk retry mode on Windows.\"\n );\n }\n } else {\n // chmod works everywhere else\n FileAccessControl.OS_PROVIDES_FILE_PROTECTION = true;\n }\n }\n }\n\n public static async applyACLRules(directory: string): Promise<void> {\n if (FileAccessControl.USE_ICACLS) {\n if (FileAccessControl.ACLED_DIRECTORIES[directory] === undefined) {\n // Avoid multiple calls race condition by setting ACLED_DIRECTORIES to false for this directory immediately\n // If batches are being failed faster than the processes spawned below return, some data won't be stored to disk\n // This is better than the alternative of potentially infinitely spawned processes\n FileAccessControl.ACLED_DIRECTORIES[directory] = false;\n try {\n // Restrict this directory to only current user and administrator access\n let identity = await this._getACLIdentity();\n await this._runICACLS(this._getACLArguments(directory, identity));\n FileAccessControl.ACLED_DIRECTORIES[directory] = true;\n } catch (ex: any) {\n FileAccessControl.ACLED_DIRECTORIES[directory] = false; // false is used to cache failed (vs undefined which is \"not yet tried\")\n throw ex;\n }\n } else {\n if (!FileAccessControl.ACLED_DIRECTORIES[directory]) {\n throw new Error(\"Setting ACL restrictions did not succeed (cached result)\");\n }\n }\n }\n }\n\n public static applyACLRulesSync(directory: string) {\n if (FileAccessControl.USE_ICACLS) {\n // For performance, only run ACL rules if we haven't already during this session\n if (FileAccessControl.ACLED_DIRECTORIES[directory] === undefined) {\n this._runICACLSSync(this._getACLArguments(directory, this._getACLIdentitySync()));\n FileAccessControl.ACLED_DIRECTORIES[directory] = true; // If we get here, it succeeded. _runIACLSSync will throw on failures\n return;\n } else if (!FileAccessControl.ACLED_DIRECTORIES[directory]) {\n // falsy but not undefined\n throw new Error(\"Setting ACL restrictions did not succeed (cached result)\");\n }\n }\n }\n\n private static _runICACLS(args: string[]): Promise<void> {\n return new Promise((resolve, reject) => {\n var aclProc = child_process.spawn(FileAccessControl.ICACLS_PATH, args, <any>{\n windowsHide: true,\n });\n aclProc.on(\"error\", (e: Error) => reject(e));\n aclProc.on(\"close\", (code: number) => {\n if (code === 0) {\n resolve();\n } else {\n reject(\n new Error(`Setting ACL restrictions did not succeed (ICACLS returned code ${code})`)\n );\n }\n });\n });\n }\n\n private static _runICACLSSync(args: string[]) {\n // Some very old versions of Node (< 0.11) don't have this\n if (child_process.spawnSync) {\n var aclProc = child_process.spawnSync(FileAccessControl.ICACLS_PATH, args, <any>{\n windowsHide: true,\n });\n if (aclProc.error) {\n throw aclProc.error;\n } else if (aclProc.status !== 0) {\n throw new Error(\n `Setting ACL restrictions did not succeed (ICACLS returned code ${aclProc.status})`\n );\n }\n } else {\n throw new Error(\"Could not synchronously call ICACLS under current version of Node.js\");\n }\n }\n\n private static _getACLIdentity(): Promise<string> {\n return new Promise((resolve, reject) => {\n if (FileAccessControl.ACL_IDENTITY) {\n resolve(FileAccessControl.ACL_IDENTITY);\n }\n var psProc = child_process.spawn(\n FileAccessControl.POWERSHELL_PATH,\n [\"-Command\", \"[System.Security.Principal.WindowsIdentity]::GetCurrent().Name\"],\n <any>{\n windowsHide: true,\n stdio: [\"ignore\", \"pipe\", \"pipe\"], // Needed to prevent hanging on Win 7\n }\n );\n let data = \"\";\n psProc.stdout.on(\"data\", (d: string) => (data += d));\n psProc.on(\"error\", (e: Error) => reject(e));\n psProc.on(\"close\", (code: number) => {\n FileAccessControl.ACL_IDENTITY = data && data.trim();\n if (code === 0) {\n resolve(FileAccessControl.ACL_IDENTITY);\n } else {\n reject(new Error(`Getting ACL identity did not succeed (PS returned code ${code})`));\n }\n });\n });\n }\n\n private static _getACLIdentitySync() {\n if (FileAccessControl.ACL_IDENTITY) {\n return FileAccessControl.ACL_IDENTITY;\n }\n // Some very old versions of Node (< 0.11) don't have this\n if (child_process.spawnSync) {\n var psProc = child_process.spawnSync(\n FileAccessControl.POWERSHELL_PATH,\n [\"-Command\", \"[System.Security.Principal.WindowsIdentity]::GetCurrent().Name\"],\n <any>{\n windowsHide: true,\n stdio: [\"ignore\", \"pipe\", \"pipe\"], // Needed to prevent hanging on Win 7\n }\n );\n if (psProc.error) {\n throw psProc.error;\n } else if (psProc.status !== 0) {\n throw new Error(`Getting ACL identity did not succeed (PS returned code ${psProc.status})`);\n }\n FileAccessControl.ACL_IDENTITY = psProc.stdout && psProc.stdout.toString().trim();\n return FileAccessControl.ACL_IDENTITY;\n } else {\n throw new Error(\"Could not synchronously get ACL identity under current version of Node.js\");\n }\n }\n\n private static _getACLArguments(directory: string, identity: string) {\n return [\n directory,\n \"/grant\",\n \"*S-1-5-32-544:(OI)(CI)F\", // Full permission for Administrators\n \"/grant\",\n `${identity}:(OI)(CI)F`, // Full permission for current user\n \"/inheritance:r\",\n ]; // Remove all inherited permissions\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"fileSystemHelpers.js","sourceRoot":"","sources":["../../../../../src/platform/nodejs/persist/fileSystemHelpers.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAC7B,OAAO,EAAE,SAAS,EAAE,MAAM,MAAM,CAAC;AAEjC,MAAM,YAAY,GAAG,SAAS,CAAC,EAAE,CAAC,OAAO,CAAC,CAAC;AAC3C,MAAM,SAAS,GAAG,SAAS,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC;AACrC,MAAM,UAAU,GAAG,SAAS,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC;AACvC,MAAM,UAAU,GAAG,SAAS,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC;AAEvC;;;GAGG;AACH,MAAM,CAAC,MAAM,uBAAuB,GAAG,KAAK,EAAE,SAAiB,EAAmB,EAAE;IAClF,4BAA4B;IAC5B,MAAM,KAAK,GAAG,MAAM,YAAY,CAAC,SAAS,CAAC,CAAC;IAE5C,IAAI,SAAS,GAAG,CAAC,CAAC;IAElB,uBAAuB;IACvB,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE;QACxB,MAAM,SAAS,GAAG,MAAM,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC,CAAC;QAC9D,IAAI,SAAS,CAAC,MAAM,EAAE,EAAE;YACtB,SAAS,IAAI,SAAS,CAAC,IAAI,CAAC;SAC7B;KACF;IAED,OAAO,SAAS,CAAC;AACnB,CAAC,CAAC;AAEF;;;GAGG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,KAAK,EAAE,SAAiB,EAAiB,EAAE;IACzE,IAAI;QACF,MAAM,KAAK,GAAG,MAAM,UAAU,CAAC,SAAS,CAAC,CAAC;QAC1C,IAAI,CAAC,KAAK,CAAC,WAAW,EAAE,EAAE;YACxB,MAAM,IAAI,KAAK,CAAC,sCAAsC,CAAC,CAAC;SACzD;KACF;IAAC,OAAO,GAAG,EAAE;QACZ,IAAI,GAAG,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ,EAAE;YAChC,IAAI;gBACF,MAAM,UAAU,CAAC,SAAS,CAAC,CAAC;aAC7B;YAAC,OAAO,QAAQ,EAAE;gBACjB,IAAI,QAAQ,IAAI,QAAQ,CAAC,IAAI,KAAK,QAAQ,EAAE;oBAC1C,2CAA2C;oBAC3C,MAAM,QAAQ,CAAC;iBAChB;aACF;SACF;KACF;AACH,CAAC,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport * as fs from \"fs\";\nimport * as path from \"path\";\nimport { promisify } from \"util\";\n\nconst readdirAsync = promisify(fs.readdir);\nconst statAsync = promisify(fs.stat);\nconst lstatAsync = promisify(fs.lstat);\nconst mkdirAsync = promisify(fs.mkdir);\n\n/**\n * Computes the size (in bytes) of all files in a directory at the root level. Asynchronously.\n * @internal\n */\nexport const getShallowDirectorySize = async (directory: string): Promise<number> => {\n // Get the directory listing\n const files = await readdirAsync(directory);\n\n let totalSize = 0;\n\n // Query all file sizes\n for (const file of files) {\n const fileStats = await statAsync(path.join(directory, file));\n if (fileStats.isFile()) {\n totalSize += fileStats.size;\n }\n }\n\n return totalSize;\n};\n\n/**\n * Validate directory exists.\n * @internal\n */\nexport const confirmDirExists = async (directory: string): Promise<void> => {\n try {\n const stats = await lstatAsync(directory);\n if (!stats.isDirectory()) {\n throw new Error(\"Path existed but was not a directory\");\n }\n } catch (err) {\n if (err && err.code === \"ENOENT\") {\n try {\n await mkdirAsync(directory);\n } catch (mkdirErr) {\n if (mkdirErr && mkdirErr.code !== \"EEXIST\") {\n // Handle race condition by ignoring EEXIST\n throw mkdirErr;\n }\n }\n }\n }\n};\n"]}
1
+ {"version":3,"file":"fileSystemHelpers.js","sourceRoot":"","sources":["../../../../../src/platform/nodejs/persist/fileSystemHelpers.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAC7B,OAAO,EAAE,SAAS,EAAE,MAAM,MAAM,CAAC;AAEjC,MAAM,YAAY,GAAG,SAAS,CAAC,EAAE,CAAC,OAAO,CAAC,CAAC;AAC3C,MAAM,SAAS,GAAG,SAAS,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC;AACrC,MAAM,UAAU,GAAG,SAAS,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC;AACvC,MAAM,UAAU,GAAG,SAAS,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC;AAEvC;;;GAGG;AACH,MAAM,CAAC,MAAM,uBAAuB,GAAG,KAAK,EAAE,SAAiB,EAAmB,EAAE;IAClF,4BAA4B;IAC5B,MAAM,KAAK,GAAG,MAAM,YAAY,CAAC,SAAS,CAAC,CAAC;IAE5C,IAAI,SAAS,GAAG,CAAC,CAAC;IAElB,uBAAuB;IACvB,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE;QACxB,MAAM,SAAS,GAAG,MAAM,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC,CAAC;QAC9D,IAAI,SAAS,CAAC,MAAM,EAAE,EAAE;YACtB,SAAS,IAAI,SAAS,CAAC,IAAI,CAAC;SAC7B;KACF;IAED,OAAO,SAAS,CAAC;AACnB,CAAC,CAAC;AAEF;;;GAGG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,KAAK,EAAE,SAAiB,EAAiB,EAAE;IACzE,IAAI;QACF,MAAM,KAAK,GAAG,MAAM,UAAU,CAAC,SAAS,CAAC,CAAC;QAC1C,IAAI,CAAC,KAAK,CAAC,WAAW,EAAE,EAAE;YACxB,MAAM,IAAI,KAAK,CAAC,sCAAsC,CAAC,CAAC;SACzD;KACF;IAAC,OAAO,GAAQ,EAAE;QACjB,IAAI,GAAG,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ,EAAE;YAChC,IAAI;gBACF,MAAM,UAAU,CAAC,SAAS,CAAC,CAAC;aAC7B;YAAC,OAAO,QAAa,EAAE;gBACtB,IAAI,QAAQ,IAAI,QAAQ,CAAC,IAAI,KAAK,QAAQ,EAAE;oBAC1C,2CAA2C;oBAC3C,MAAM,QAAQ,CAAC;iBAChB;aACF;SACF;KACF;AACH,CAAC,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport * as fs from \"fs\";\nimport * as path from \"path\";\nimport { promisify } from \"util\";\n\nconst readdirAsync = promisify(fs.readdir);\nconst statAsync = promisify(fs.stat);\nconst lstatAsync = promisify(fs.lstat);\nconst mkdirAsync = promisify(fs.mkdir);\n\n/**\n * Computes the size (in bytes) of all files in a directory at the root level. Asynchronously.\n * @internal\n */\nexport const getShallowDirectorySize = async (directory: string): Promise<number> => {\n // Get the directory listing\n const files = await readdirAsync(directory);\n\n let totalSize = 0;\n\n // Query all file sizes\n for (const file of files) {\n const fileStats = await statAsync(path.join(directory, file));\n if (fileStats.isFile()) {\n totalSize += fileStats.size;\n }\n }\n\n return totalSize;\n};\n\n/**\n * Validate directory exists.\n * @internal\n */\nexport const confirmDirExists = async (directory: string): Promise<void> => {\n try {\n const stats = await lstatAsync(directory);\n if (!stats.isDirectory()) {\n throw new Error(\"Path existed but was not a directory\");\n }\n } catch (err: any) {\n if (err && err.code === \"ENOENT\") {\n try {\n await mkdirAsync(directory);\n } catch (mkdirErr: any) {\n if (mkdirErr && mkdirErr.code !== \"EEXIST\") {\n // Handle race condition by ignoring EEXIST\n throw mkdirErr;\n }\n }\n }\n }\n};\n"]}
@@ -5,6 +5,7 @@ import * as os from "os";
5
5
  import * as path from "path";
6
6
  import { diag } from "@opentelemetry/api";
7
7
  import { DEFAULT_EXPORTER_CONFIG } from "../../../config";
8
+ import { FileAccessControl } from "./fileAccessControl";
8
9
  import { confirmDirExists, getShallowDirectorySize } from "./fileSystemHelpers";
9
10
  import { promisify } from "util";
10
11
  const statAsync = promisify(fs.stat);
@@ -21,36 +22,56 @@ export class FileSystemPersist {
21
22
  this.fileRetemptionPeriod = 7 * 24 * 60 * 60 * 1000; // 7 days
22
23
  this.cleanupTimeOut = 60 * 60 * 1000; // 1 hour
23
24
  this.maxBytesOnDisk = 50000000; // ~50MB
25
+ this._tempDirectory = "";
24
26
  this._fileCleanupTimer = null;
25
27
  this._options = Object.assign(Object.assign({}, DEFAULT_EXPORTER_CONFIG), options);
28
+ this._enabled = true;
29
+ FileAccessControl.checkFileProtection();
30
+ if (!FileAccessControl.OS_PROVIDES_FILE_PROTECTION) {
31
+ this._enabled = false;
32
+ diag.error("Sufficient file protection capabilities were not detected. Files will not be persisted");
33
+ }
26
34
  if (!this._options.instrumentationKey) {
27
- diag.error(`No instrumentation key was provided to FileSystemPersister. Files may not be properly persisted`);
35
+ this._enabled = false;
36
+ diag.error(`No instrumentation key was provided to FileSystemPersister. Files will not be persisted`);
28
37
  }
29
- this._tempDirectory = path.join(os.tmpdir(), FileSystemPersist.TEMPDIR_PREFIX + this._options.instrumentationKey);
30
- // Starts file cleanup task
31
- if (!this._fileCleanupTimer) {
32
- this._fileCleanupTimer = setTimeout(() => {
33
- this._fileCleanupTask();
34
- }, this.cleanupTimeOut);
35
- this._fileCleanupTimer.unref();
38
+ if (this._enabled) {
39
+ this._tempDirectory = path.join(os.tmpdir(), FileSystemPersist.TEMPDIR_PREFIX + this._options.instrumentationKey);
40
+ // Starts file cleanup task
41
+ if (!this._fileCleanupTimer) {
42
+ this._fileCleanupTimer = setTimeout(() => {
43
+ this._fileCleanupTask();
44
+ }, this.cleanupTimeOut);
45
+ this._fileCleanupTimer.unref();
46
+ }
36
47
  }
37
48
  }
38
49
  push(value) {
39
- diag.debug("Pushing value to persistent storage", value.toString());
40
- return this._storeToDisk(JSON.stringify(value));
50
+ if (this._enabled) {
51
+ diag.debug("Pushing value to persistent storage", value.toString());
52
+ return this._storeToDisk(JSON.stringify(value));
53
+ }
54
+ return new Promise((resolve) => {
55
+ resolve(false);
56
+ });
41
57
  }
42
58
  async shift() {
43
- diag.debug("Searching for filesystem persisted files");
44
- try {
45
- const buffer = await this._getFirstFileOnDisk();
46
- if (buffer) {
47
- return JSON.parse(buffer.toString("utf8"));
59
+ if (this._enabled) {
60
+ diag.debug("Searching for filesystem persisted files");
61
+ try {
62
+ const buffer = await this._getFirstFileOnDisk();
63
+ if (buffer) {
64
+ return JSON.parse(buffer.toString("utf8"));
65
+ }
48
66
  }
67
+ catch (e) {
68
+ diag.debug("Failed to read persisted file", e);
69
+ }
70
+ return null;
49
71
  }
50
- catch (e) {
51
- diag.debug("Failed to read persisted file", e);
52
- }
53
- return null;
72
+ return new Promise((resolve) => {
73
+ resolve(null);
74
+ });
54
75
  }
55
76
  /**
56
77
  * Check for temp telemetry files
@@ -1 +1 @@
1
- {"version":3,"file":"fileSystemP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AAK,CAAC;iBACd;qBAAM;oBACL,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;4BACX,MAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,cAAc,EAAE,IAAI,CAAC,CAAC;4BACtD,MAAM,WAAW,CAAC,QAAQ,CAAC,CAAC;yBAC7B;oBACH,CAAC,CAAC,CAAC;oBACH,OAAO,IAAI,CAAC;iBACb;aACF;YACD,OAAO,KAAK,CAAC;SACd;QAAC,OAAO,KAAK,EAAE;YACd,IAAI,CAAC,IAAI,CAAC,yDAAyD,EAAE,KAAK,CAAC,CAAC;YAC5E,OAAO,KAAK,CAAC;SACd;IACH,CAAC;;AAtJM,gCAAc,GAAG,oBAAoB,CAAC;AAEtC,iCAAe,GAAG,UAAU,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 { DEFAULT_EXPORTER_CONFIG, AzureExporterInternalConfig } from \"../../../config\";\nimport { confirmDirExists, getShallowDirectorySize } from \"./fileSystemHelpers\";\nimport { promisify } from \"util\";\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\n static FILENAME_SUFFIX = \".ai.json\";\n\n fileRetemptionPeriod = 7 * 24 * 60 * 60 * 1000; // 7 days\n cleanupTimeOut = 60 * 60 * 1000; // 1 hour\n maxBytesOnDisk: number = 50_000_000; // ~50MB\n\n private _tempDirectory: string;\n private _fileCleanupTimer: NodeJS.Timer | null = null;\n\n private readonly _options: AzureExporterInternalConfig;\n\n constructor(options: Partial<AzureExporterInternalConfig> = {}) {\n this._options = { ...DEFAULT_EXPORTER_CONFIG, ...options };\n if (!this._options.instrumentationKey) {\n diag.error(\n `No instrumentation key was provided to FileSystemPersister. Files may not be properly persisted`\n );\n }\n this._tempDirectory = path.join(\n os.tmpdir(),\n FileSystemPersist.TEMPDIR_PREFIX + this._options.instrumentationKey\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 push(value: unknown[]): Promise<boolean> {\n diag.debug(\"Pushing value to persistent storage\", value.toString());\n return this._storeToDisk(JSON.stringify(value));\n }\n\n async shift(): Promise<unknown> {\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) {\n diag.debug(\"Failed to read persisted file\", e);\n }\n return null;\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) {\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) {\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) {\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) {\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) {\n diag.info(`Failed cleanup of persistent file storage expired files`, error);\n return false;\n }\n }\n}\n"]}
1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ACtD,MAAM,WAAW,CAAC,QAAQ,CAAC,CAAC;yBAC7B;oBACH,CAAC,CAAC,CAAC;oBACH,OAAO,IAAI,CAAC;iBACb;aACF;YACD,OAAO,KAAK,CAAC;SACd;QAAC,OAAO,KAAU,EAAE;YACnB,IAAI,CAAC,IAAI,CAAC,yDAAyD,EAAE,KAAK,CAAC,CAAC;YAC5E,OAAO,KAAK,CAAC;SACd;IACH,CAAC;;AA9KM,gCAAc,GAAG,oBAAoB,CAAC;AAEtC,iCAAe,GAAG,UAAU,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 { DEFAULT_EXPORTER_CONFIG, AzureExporterInternalConfig } from \"../../../config\";\nimport { FileAccessControl } from \"./fileAccessControl\";\nimport { confirmDirExists, getShallowDirectorySize } from \"./fileSystemHelpers\";\nimport { promisify } from \"util\";\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\n static FILENAME_SUFFIX = \".ai.json\";\n\n fileRetemptionPeriod = 7 * 24 * 60 * 60 * 1000; // 7 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.Timer | null = null;\n\n private readonly _options: AzureExporterInternalConfig;\n\n constructor(options: Partial<AzureExporterInternalConfig> = {}) {\n this._options = { ...DEFAULT_EXPORTER_CONFIG, ...options };\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._options.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 os.tmpdir(),\n FileSystemPersist.TEMPDIR_PREFIX + this._options.instrumentationKey\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"]}
@@ -5,12 +5,13 @@
5
5
  * @internal
6
6
  */
7
7
  export function isRetriable(statusCode) {
8
- return (statusCode === 206 || // Retriable
8
+ return (statusCode === 206 || // Partial Accept
9
+ statusCode === 401 || // Unauthorized
10
+ statusCode === 403 || // Forbidden
9
11
  statusCode === 408 || // Timeout
10
- statusCode === 429 || // Throttle
11
- statusCode === 439 || // Quota
12
+ statusCode === 429 || // Too many requests
12
13
  statusCode === 500 || // Server Error
13
- statusCode === 503 // Server Unavilable
14
+ statusCode === 503 // Server Unavailable
14
15
  );
15
16
  }
16
17
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"breezeUtils.js","sourceRoot":"","sources":["../../../src/utils/breezeUtils.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAsBlC;;;GAGG;AACH,MAAM,UAAU,WAAW,CAAC,UAAkB;IAC5C,OAAO,CACL,UAAU,KAAK,GAAG,IAAI,YAAY;QAClC,UAAU,KAAK,GAAG,IAAI,UAAU;QAChC,UAAU,KAAK,GAAG,IAAI,WAAW;QACjC,UAAU,KAAK,GAAG,IAAI,QAAQ;QAC9B,UAAU,KAAK,GAAG,IAAI,eAAe;QACrC,UAAU,KAAK,GAAG,CAAC,oBAAoB;KACxC,CAAC;AACJ,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,YAAY,CAAC,EAAU;IACrC,IAAI,OAAO,GAAG,EAAE,CAAC;IACjB,IAAI,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,OAAO,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,EAAE,CAAC,EAAE;QAChE,OAAO,GAAG,CAAC,CAAC;KACb;IAED,IAAI,GAAG,GAAG,CAAC,CAAC,OAAO,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,SAAS,EAAE,EAAE,CAAC,CAAC;IACpE,IAAI,GAAG,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,GAAG,CAAC,IAAI,GAAG,EAAE,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC;IACtD,IAAI,IAAI,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,GAAG,CAAC,IAAI,GAAG,EAAE,GAAG,EAAE,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC;IAC5D,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,GAAG,CAAC,IAAI,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC,CAAC,CAAC;IAEzD,GAAG,GAAG,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,GAAG,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC;IAC7C,GAAG,GAAG,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,GAAG,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC;IACvC,IAAI,GAAG,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;IAC3C,MAAM,QAAQ,GAAG,IAAI,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC;IAE5C,OAAO,GAAG,QAAQ,GAAG,IAAI,IAAI,GAAG,IAAI,GAAG,EAAE,CAAC;AAC5C,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/**\n * Breeze errors.\n * @internal\n */\nexport interface BreezeError {\n index: number;\n statusCode: number;\n message: string;\n}\n\n/**\n * Breeze response definition.\n * @internal\n */\nexport interface BreezeResponse {\n itemsReceived: number;\n itemsAccepted: number;\n errors: BreezeError[];\n}\n\n/**\n * Breeze retriable status codes.\n * @internal\n */\nexport function isRetriable(statusCode: number): boolean {\n return (\n statusCode === 206 || // Retriable\n statusCode === 408 || // Timeout\n statusCode === 429 || // Throttle\n statusCode === 439 || // Quota\n statusCode === 500 || // Server Error\n statusCode === 503 // Server Unavilable\n );\n}\n\n/**\n * Convert milliseconds to Breeze expected time.\n * @internal\n */\nexport function msToTimeSpan(ms: number): string {\n let totalms = ms;\n if (Number.isNaN(totalms) || totalms < 0 || !Number.isFinite(ms)) {\n totalms = 0;\n }\n\n let sec = ((totalms / 1000) % 60).toFixed(7).replace(/0{0,4}$/, \"\");\n let min = `${Math.floor(totalms / (1000 * 60)) % 60}`;\n let hour = `${Math.floor(totalms / (1000 * 60 * 60)) % 24}`;\n const days = Math.floor(totalms / (1000 * 60 * 60 * 24));\n\n sec = sec.indexOf(\".\") < 2 ? `0${sec}` : sec;\n min = min.length < 2 ? `0${min}` : min;\n hour = hour.length < 2 ? `0${hour}` : hour;\n const daysText = days > 0 ? `${days}.` : \"\";\n\n return `${daysText + hour}:${min}:${sec}`;\n}\n"]}
1
+ {"version":3,"file":"breezeUtils.js","sourceRoot":"","sources":["../../../src/utils/breezeUtils.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAsBlC;;;GAGG;AACH,MAAM,UAAU,WAAW,CAAC,UAAkB;IAC5C,OAAO,CACL,UAAU,KAAK,GAAG,IAAI,iBAAiB;QACvC,UAAU,KAAK,GAAG,IAAI,eAAe;QACrC,UAAU,KAAK,GAAG,IAAI,YAAY;QAClC,UAAU,KAAK,GAAG,IAAI,UAAU;QAChC,UAAU,KAAK,GAAG,IAAI,oBAAoB;QAC1C,UAAU,KAAK,GAAG,IAAI,eAAe;QACrC,UAAU,KAAK,GAAG,CAAC,qBAAqB;KACzC,CAAC;AACJ,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,YAAY,CAAC,EAAU;IACrC,IAAI,OAAO,GAAG,EAAE,CAAC;IACjB,IAAI,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,OAAO,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,EAAE,CAAC,EAAE;QAChE,OAAO,GAAG,CAAC,CAAC;KACb;IAED,IAAI,GAAG,GAAG,CAAC,CAAC,OAAO,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,SAAS,EAAE,EAAE,CAAC,CAAC;IACpE,IAAI,GAAG,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,GAAG,CAAC,IAAI,GAAG,EAAE,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC;IACtD,IAAI,IAAI,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,GAAG,CAAC,IAAI,GAAG,EAAE,GAAG,EAAE,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC;IAC5D,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,GAAG,CAAC,IAAI,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC,CAAC,CAAC;IAEzD,GAAG,GAAG,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,GAAG,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC;IAC7C,GAAG,GAAG,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,GAAG,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC;IACvC,IAAI,GAAG,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;IAC3C,MAAM,QAAQ,GAAG,IAAI,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC;IAE5C,OAAO,GAAG,QAAQ,GAAG,IAAI,IAAI,GAAG,IAAI,GAAG,EAAE,CAAC;AAC5C,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/**\n * Breeze errors.\n * @internal\n */\nexport interface BreezeError {\n index: number;\n statusCode: number;\n message: string;\n}\n\n/**\n * Breeze response definition.\n * @internal\n */\nexport interface BreezeResponse {\n itemsReceived: number;\n itemsAccepted: number;\n errors: BreezeError[];\n}\n\n/**\n * Breeze retriable status codes.\n * @internal\n */\nexport function isRetriable(statusCode: number): boolean {\n return (\n statusCode === 206 || // Partial Accept\n statusCode === 401 || // Unauthorized\n statusCode === 403 || // Forbidden\n statusCode === 408 || // Timeout\n statusCode === 429 || // Too many requests\n statusCode === 500 || // Server Error\n statusCode === 503 // Server Unavailable\n );\n}\n\n/**\n * Convert milliseconds to Breeze expected time.\n * @internal\n */\nexport function msToTimeSpan(ms: number): string {\n let totalms = ms;\n if (Number.isNaN(totalms) || totalms < 0 || !Number.isFinite(ms)) {\n totalms = 0;\n }\n\n let sec = ((totalms / 1000) % 60).toFixed(7).replace(/0{0,4}$/, \"\");\n let min = `${Math.floor(totalms / (1000 * 60)) % 60}`;\n let hour = `${Math.floor(totalms / (1000 * 60 * 60)) % 24}`;\n const days = Math.floor(totalms / (1000 * 60 * 60 * 24));\n\n sec = sec.indexOf(\".\") < 2 ? `0${sec}` : sec;\n min = min.length < 2 ? `0${min}` : min;\n hour = hour.length < 2 ? `0${hour}` : hour;\n const daysText = days > 0 ? `${days}.` : \"\";\n\n return `${daysText + hour}:${min}:${sec}`;\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.5";
22
+ export const packageVersion = "1.0.0-beta.8";
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,kCAAkC;AAElC;;;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,cAAc,CAAC;AAE7C,MAAM,CAAN,IAAY,eAMX;AAND,WAAY,eAAe;IACzB,oCAAiB,CAAA;IACjB,iDAA8B,CAAA;IAC9B,8BAAW,CAAA;IACX,gCAAa,CAAA;IACb,gCAAa,CAAA;AACf,CAAC,EANW,eAAe,KAAf,eAAe,QAM1B","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.5\";\n\nexport enum DependencyTypes {\n InProc = \"InProc\",\n QueueMessage = \"Queue Message\",\n Sql = \"SQL\",\n Http = \"Http\",\n Grpc = \"GRPC\"\n}\n"]}
1
+ {"version":3,"file":"applicationinsights.js","sourceRoot":"","sources":["../../../../src/utils/constants/applicationinsights.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC;;;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,cAAc,CAAC;AAE7C,MAAM,CAAN,IAAY,eAMX;AAND,WAAY,eAAe;IACzB,oCAAiB,CAAA;IACjB,iDAA8B,CAAA;IAC9B,8BAAW,CAAA;IACX,gCAAa,CAAA;IACb,gCAAa,CAAA;AACf,CAAC,EANW,eAAe,KAAf,eAAe,QAM1B","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.8\";\n\nexport enum DependencyTypes {\n InProc = \"InProc\",\n QueueMessage = \"Queue Message\",\n Sql = \"SQL\",\n Http = \"Http\",\n Grpc = \"GRPC\",\n}\n"]}