@opentelemetry/otlp-grpc-exporter-base 0.52.1 → 0.54.0

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.
@@ -1,18 +1,15 @@
1
- import { GRPCQueueItem, OTLPGRPCExporterConfigNode } from './types';
2
- import { CompressionAlgorithm, OTLPExporterBase, OTLPExporterError } from '@opentelemetry/otlp-exporter-base';
1
+ import { OTLPGRPCExporterConfigNode } from './types';
2
+ import { OTLPExporterBase, OTLPExporterError } from '@opentelemetry/otlp-exporter-base';
3
3
  import { ISerializer } from '@opentelemetry/otlp-transformer';
4
4
  /**
5
5
  * OTLP Exporter abstract base class
6
6
  */
7
7
  export declare abstract class OTLPGRPCExporterNodeBase<ExportItem, ServiceResponse> extends OTLPExporterBase<OTLPGRPCExporterConfigNode, ExportItem> {
8
- grpcQueue: GRPCQueueItem<ExportItem>[];
9
- compression: CompressionAlgorithm;
10
8
  private _transport;
11
9
  private _serializer;
12
- constructor(config: OTLPGRPCExporterConfigNode | undefined, signalSpecificMetadata: Record<string, string>, grpcName: string, grpcPath: string, serializer: ISerializer<ExportItem[], ServiceResponse>);
13
- onInit(): void;
10
+ private _timeoutMillis;
11
+ constructor(config: OTLPGRPCExporterConfigNode | undefined, serializer: ISerializer<ExportItem[], ServiceResponse>, grpcName: string, grpcPath: string, signalIdentifier: string);
14
12
  onShutdown(): void;
15
13
  send(objects: ExportItem[], onSuccess: () => void, onError: (error: OTLPExporterError) => void): void;
16
- abstract getUrlFromConfig(config: OTLPGRPCExporterConfigNode): string;
17
14
  }
18
15
  //# sourceMappingURL=OTLPGRPCExporterNodeBase.d.ts.map
@@ -17,60 +17,47 @@
17
17
  Object.defineProperty(exports, "__esModule", { value: true });
18
18
  exports.OTLPGRPCExporterNodeBase = void 0;
19
19
  const api_1 = require("@opentelemetry/api");
20
- const core_1 = require("@opentelemetry/core");
21
20
  const otlp_exporter_base_1 = require("@opentelemetry/otlp-exporter-base");
22
21
  const grpc_exporter_transport_1 = require("./grpc-exporter-transport");
23
- const util_1 = require("./util");
22
+ const otlp_grpc_configuration_1 = require("./configuration/otlp-grpc-configuration");
23
+ const otlp_grpc_env_configuration_1 = require("./configuration/otlp-grpc-env-configuration");
24
24
  /**
25
25
  * OTLP Exporter abstract base class
26
26
  */
27
27
  class OTLPGRPCExporterNodeBase extends otlp_exporter_base_1.OTLPExporterBase {
28
- constructor(config = {}, signalSpecificMetadata, grpcName, grpcPath, serializer) {
29
- var _a;
28
+ constructor(config = {}, serializer, grpcName, grpcPath, signalIdentifier) {
30
29
  super(config);
31
- this.grpcQueue = [];
30
+ // keep credentials locally in case user updates the reference on the config object
31
+ const userProvidedCredentials = config.credentials;
32
+ const actualConfig = (0, otlp_grpc_configuration_1.mergeOtlpGrpcConfigurationWithDefaults)({
33
+ url: config.url,
34
+ metadata: () => {
35
+ var _a;
36
+ // metadata resolution strategy is merge, so we can return empty here, and it will not override the rest of the settings.
37
+ return (_a = config.metadata) !== null && _a !== void 0 ? _a : (0, grpc_exporter_transport_1.createEmptyMetadata)();
38
+ },
39
+ compression: config.compression,
40
+ timeoutMillis: config.timeoutMillis,
41
+ concurrencyLimit: config.concurrencyLimit,
42
+ credentials: userProvidedCredentials != null
43
+ ? () => userProvidedCredentials
44
+ : undefined,
45
+ }, (0, otlp_grpc_env_configuration_1.getOtlpGrpcConfigurationFromEnv)(signalIdentifier), (0, otlp_grpc_configuration_1.getOtlpGrpcDefaultConfiguration)());
32
46
  this._serializer = serializer;
47
+ this._timeoutMillis = actualConfig.timeoutMillis;
48
+ this._concurrencyLimit = actualConfig.concurrencyLimit;
33
49
  if (config.headers) {
34
50
  api_1.diag.warn('Headers cannot be set when using grpc');
35
51
  }
36
- const nonSignalSpecificMetadata = core_1.baggageUtils.parseKeyPairsIntoRecord((0, core_1.getEnv)().OTEL_EXPORTER_OTLP_HEADERS);
37
- const rawMetadata = Object.assign({}, nonSignalSpecificMetadata, signalSpecificMetadata);
38
- let credentialProvider = () => {
39
- return (0, util_1.configureCredentials)(undefined, this.getUrlFromConfig(config));
40
- };
41
- if (config.credentials != null) {
42
- const credentials = config.credentials;
43
- credentialProvider = () => {
44
- return credentials;
45
- };
46
- }
47
- // Ensure we don't modify the original.
48
- const configMetadata = (_a = config.metadata) === null || _a === void 0 ? void 0 : _a.clone();
49
- const metadataProvider = () => {
50
- const metadata = configMetadata !== null && configMetadata !== void 0 ? configMetadata : (0, grpc_exporter_transport_1.createEmptyMetadata)();
51
- for (const [key, value] of Object.entries(rawMetadata)) {
52
- // only override with env var data if the key has no values.
53
- // not using Metadata.merge() as it will keep both values.
54
- if (metadata.get(key).length < 1) {
55
- metadata.set(key, value);
56
- }
57
- }
58
- return metadata;
59
- };
60
- this.compression = (0, util_1.configureCompression)(config.compression);
61
52
  this._transport = new grpc_exporter_transport_1.GrpcExporterTransport({
62
- address: this.getDefaultUrl(config),
63
- compression: this.compression,
64
- credentials: credentialProvider,
53
+ address: actualConfig.url,
54
+ compression: actualConfig.compression,
55
+ credentials: actualConfig.credentials,
65
56
  grpcName: grpcName,
66
57
  grpcPath: grpcPath,
67
- metadata: metadataProvider,
68
- timeoutMillis: this.timeoutMillis,
58
+ metadata: actualConfig.metadata,
69
59
  });
70
60
  }
71
- onInit() {
72
- // Intentionally left empty; nothing to do.
73
- }
74
61
  onShutdown() {
75
62
  this._transport.shutdown();
76
63
  }
@@ -84,15 +71,21 @@ class OTLPGRPCExporterNodeBase extends otlp_exporter_base_1.OTLPExporterBase {
84
71
  onError(new Error('Could not serialize message'));
85
72
  return;
86
73
  }
87
- const promise = this._transport.send(data).then(response => {
74
+ const promise = this._transport
75
+ .send(data, this._timeoutMillis)
76
+ .then(response => {
88
77
  if (response.status === 'success') {
89
78
  onSuccess();
90
- return;
91
79
  }
92
- if (response.status === 'failure' && response.error) {
80
+ else if (response.status === 'failure' && response.error) {
93
81
  onError(response.error);
94
82
  }
95
- onError(new otlp_exporter_base_1.OTLPExporterError('Export failed with unknown error'));
83
+ else if (response.status === 'retryable') {
84
+ onError(new otlp_exporter_base_1.OTLPExporterError('Export failed with retryable status'));
85
+ }
86
+ else {
87
+ onError(new otlp_exporter_base_1.OTLPExporterError('Export failed with unknown error'));
88
+ }
96
89
  }, onError);
97
90
  this._sendingPromises.push(promise);
98
91
  const popPromise = () => {
@@ -1 +1 @@
1
- {"version":3,"file":"OTLPGRPCExporterNodeBase.js","sourceRoot":"","sources":["../../src/OTLPGRPCExporterNodeBase.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,4CAA0C;AAE1C,8CAA2D;AAC3D,0EAI2C;AAC3C,uEAGmC;AACnC,iCAAoE;AAIpE;;GAEG;AACH,MAAsB,wBAGpB,SAAQ,qCAAwD;IAMhE,YACE,SAAqC,EAAE,EACvC,sBAA8C,EAC9C,QAAgB,EAChB,QAAgB,EAChB,UAAsD;;QAEtD,KAAK,CAAC,MAAM,CAAC,CAAC;QAZhB,cAAS,GAAgC,EAAE,CAAC;QAa1C,IAAI,CAAC,WAAW,GAAG,UAAU,CAAC;QAC9B,IAAI,MAAM,CAAC,OAAO,EAAE;YAClB,UAAI,CAAC,IAAI,CAAC,uCAAuC,CAAC,CAAC;SACpD;QACD,MAAM,yBAAyB,GAAG,mBAAY,CAAC,uBAAuB,CACpE,IAAA,aAAM,GAAE,CAAC,0BAA0B,CACpC,CAAC;QACF,MAAM,WAAW,GAAG,MAAM,CAAC,MAAM,CAC/B,EAAE,EACF,yBAAyB,EACzB,sBAAsB,CACvB,CAAC;QAEF,IAAI,kBAAkB,GAAG,GAAG,EAAE;YAC5B,OAAO,IAAA,2BAAoB,EAAC,SAAS,EAAE,IAAI,CAAC,gBAAgB,CAAC,MAAM,CAAC,CAAC,CAAC;QACxE,CAAC,CAAC;QAEF,IAAI,MAAM,CAAC,WAAW,IAAI,IAAI,EAAE;YAC9B,MAAM,WAAW,GAAG,MAAM,CAAC,WAAW,CAAC;YACvC,kBAAkB,GAAG,GAAG,EAAE;gBACxB,OAAO,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CAAC,CAAC;YAC5D,OAAO;SACR;QAED,MAAM,IAAI,GAAG,IAAI,CAAC,WAAW,CAAC,gBAAgB,CAAC,OAAO,CAAC,CAAC;QAExD,IAAI,IAAI,IAAI,IAAI,EAAE;YAChB,OAAO,CAAC,IAAI,KAAK,CAAC,6BAA6B,CAAC,CAAC,CAAC;YAClD,OAAO;SACR;QAED,MAAM,OAAO,GAAG,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE;YACzD,IAAI,QAAQ,CAAC,MAAM,KAAK,SAAS,EAAE;gBACjC,SAAS,EAAE,CAAC;gBACZ,OAAO;aACR;YACD,IAAI,QAAQ,CAAC,MAAM,KAAK,SAAS,IAAI,QAAQ,CAAC,KAAK,EAAE;gBACnD,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;aACzB;YACD,OAAO,CAAC,IAAI,sCAAiB,CAAC,kCAAkC,CAAC,CAAC,CAAC;QACrE,CAAC,EAAE,OAAO,CAAC,CAAC;QAEZ,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QACpC,MAAM,UAAU,GAAG,GAAG,EAAE;YACtB,MAAM,KAAK,GAAG,IAAI,CAAC,gBAAgB,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;YACrD,IAAI,CAAC,gBAAgB,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;QACzC,CAAC,CAAC;QACF,OAAO,CAAC,IAAI,CAAC,UAAU,EAAE,UAAU,CAAC,CAAC;IACvC,CAAC;CAGF;AAjHD,4DAiHC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { diag } from '@opentelemetry/api';\nimport { GRPCQueueItem, OTLPGRPCExporterConfigNode } from './types';\nimport { baggageUtils, getEnv } from '@opentelemetry/core';\nimport {\n CompressionAlgorithm,\n OTLPExporterBase,\n OTLPExporterError,\n} from '@opentelemetry/otlp-exporter-base';\nimport {\n createEmptyMetadata,\n GrpcExporterTransport,\n} from './grpc-exporter-transport';\nimport { configureCompression, configureCredentials } from './util';\nimport { ISerializer } from '@opentelemetry/otlp-transformer';\nimport { IExporterTransport } from './exporter-transport';\n\n/**\n * OTLP Exporter abstract base class\n */\nexport abstract class OTLPGRPCExporterNodeBase<\n ExportItem,\n ServiceResponse,\n> extends OTLPExporterBase<OTLPGRPCExporterConfigNode, ExportItem> {\n grpcQueue: GRPCQueueItem<ExportItem>[] = [];\n compression: CompressionAlgorithm;\n private _transport: IExporterTransport;\n private _serializer: ISerializer<ExportItem[], ServiceResponse>;\n\n constructor(\n config: OTLPGRPCExporterConfigNode = {},\n signalSpecificMetadata: Record<string, string>,\n grpcName: string,\n grpcPath: string,\n serializer: ISerializer<ExportItem[], ServiceResponse>\n ) {\n super(config);\n this._serializer = serializer;\n if (config.headers) {\n diag.warn('Headers cannot be set when using grpc');\n }\n const nonSignalSpecificMetadata = baggageUtils.parseKeyPairsIntoRecord(\n getEnv().OTEL_EXPORTER_OTLP_HEADERS\n );\n const rawMetadata = Object.assign(\n {},\n nonSignalSpecificMetadata,\n signalSpecificMetadata\n );\n\n let credentialProvider = () => {\n return configureCredentials(undefined, this.getUrlFromConfig(config));\n };\n\n if (config.credentials != null) {\n const credentials = config.credentials;\n credentialProvider = () => {\n return credentials;\n };\n }\n\n // Ensure we don't modify the original.\n const configMetadata = config.metadata?.clone();\n const metadataProvider = () => {\n const metadata = configMetadata ?? createEmptyMetadata();\n for (const [key, value] of Object.entries(rawMetadata)) {\n // only override with env var data if the key has no values.\n // not using Metadata.merge() as it will keep both values.\n if (metadata.get(key).length < 1) {\n metadata.set(key, value);\n }\n }\n\n return metadata;\n };\n\n this.compression = configureCompression(config.compression);\n this._transport = new GrpcExporterTransport({\n address: this.getDefaultUrl(config),\n compression: this.compression,\n credentials: credentialProvider,\n grpcName: grpcName,\n grpcPath: grpcPath,\n metadata: metadataProvider,\n timeoutMillis: this.timeoutMillis,\n });\n }\n\n onInit() {\n // Intentionally left empty; nothing to do.\n }\n\n override onShutdown() {\n this._transport.shutdown();\n }\n\n send(\n objects: ExportItem[],\n onSuccess: () => void,\n onError: (error: OTLPExporterError) => void\n ): void {\n if (this._shutdownOnce.isCalled) {\n diag.debug('Shutdown already started. Cannot send objects');\n return;\n }\n\n const data = this._serializer.serializeRequest(objects);\n\n if (data == null) {\n onError(new Error('Could not serialize message'));\n return;\n }\n\n const promise = this._transport.send(data).then(response => {\n if (response.status === 'success') {\n onSuccess();\n return;\n }\n if (response.status === 'failure' && response.error) {\n onError(response.error);\n }\n onError(new OTLPExporterError('Export failed with unknown error'));\n }, onError);\n\n this._sendingPromises.push(promise);\n const popPromise = () => {\n const index = this._sendingPromises.indexOf(promise);\n this._sendingPromises.splice(index, 1);\n };\n promise.then(popPromise, popPromise);\n }\n\n abstract getUrlFromConfig(config: OTLPGRPCExporterConfigNode): string;\n}\n"]}
1
+ {"version":3,"file":"OTLPGRPCExporterNodeBase.js","sourceRoot":"","sources":["../../src/OTLPGRPCExporterNodeBase.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,4CAA0C;AAE1C,0EAG2C;AAC3C,uEAGmC;AAGnC,qFAGiD;AACjD,6FAA8F;AAE9F;;GAEG;AACH,MAAsB,wBAGpB,SAAQ,qCAAwD;IAKhE,YACE,SAAqC,EAAE,EACvC,UAAsD,EACtD,QAAgB,EAChB,QAAgB,EAChB,gBAAwB;QAExB,KAAK,CAAC,MAAM,CAAC,CAAC;QACd,mFAAmF;QACnF,MAAM,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A+FC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { diag } from '@opentelemetry/api';\nimport { OTLPGRPCExporterConfigNode } from './types';\nimport {\n OTLPExporterBase,\n OTLPExporterError,\n} from '@opentelemetry/otlp-exporter-base';\nimport {\n createEmptyMetadata,\n GrpcExporterTransport,\n} from './grpc-exporter-transport';\nimport { ISerializer } from '@opentelemetry/otlp-transformer';\nimport { IExporterTransport } from '@opentelemetry/otlp-exporter-base';\nimport {\n getOtlpGrpcDefaultConfiguration,\n mergeOtlpGrpcConfigurationWithDefaults,\n} from './configuration/otlp-grpc-configuration';\nimport { getOtlpGrpcConfigurationFromEnv } from './configuration/otlp-grpc-env-configuration';\n\n/**\n * OTLP Exporter abstract base class\n */\nexport abstract class OTLPGRPCExporterNodeBase<\n ExportItem,\n ServiceResponse,\n> extends OTLPExporterBase<OTLPGRPCExporterConfigNode, ExportItem> {\n private _transport: IExporterTransport;\n private _serializer: ISerializer<ExportItem[], ServiceResponse>;\n private _timeoutMillis: number;\n\n constructor(\n config: OTLPGRPCExporterConfigNode = {},\n serializer: ISerializer<ExportItem[], ServiceResponse>,\n grpcName: string,\n grpcPath: string,\n signalIdentifier: string\n ) {\n super(config);\n // keep credentials locally in case user updates the reference on the config object\n const userProvidedCredentials = config.credentials;\n const actualConfig = mergeOtlpGrpcConfigurationWithDefaults(\n {\n url: config.url,\n metadata: () => {\n // metadata resolution strategy is merge, so we can return empty here, and it will not override the rest of the settings.\n return config.metadata ?? createEmptyMetadata();\n },\n compression: config.compression,\n timeoutMillis: config.timeoutMillis,\n concurrencyLimit: config.concurrencyLimit,\n credentials:\n userProvidedCredentials != null\n ? () => userProvidedCredentials\n : undefined,\n },\n getOtlpGrpcConfigurationFromEnv(signalIdentifier),\n getOtlpGrpcDefaultConfiguration()\n );\n this._serializer = serializer;\n this._timeoutMillis = actualConfig.timeoutMillis;\n this._concurrencyLimit = actualConfig.concurrencyLimit;\n if (config.headers) {\n diag.warn('Headers cannot be set when using grpc');\n }\n\n this._transport = new GrpcExporterTransport({\n address: actualConfig.url,\n compression: actualConfig.compression,\n credentials: actualConfig.credentials,\n grpcName: grpcName,\n grpcPath: grpcPath,\n metadata: actualConfig.metadata,\n });\n }\n\n override onShutdown() {\n this._transport.shutdown();\n }\n\n send(\n objects: ExportItem[],\n onSuccess: () => void,\n onError: (error: OTLPExporterError) => void\n ): void {\n if (this._shutdownOnce.isCalled) {\n diag.debug('Shutdown already started. Cannot send objects');\n return;\n }\n\n const data = this._serializer.serializeRequest(objects);\n\n if (data == null) {\n onError(new Error('Could not serialize message'));\n return;\n }\n\n const promise = this._transport\n .send(data, this._timeoutMillis)\n .then(response => {\n if (response.status === 'success') {\n onSuccess();\n } else if (response.status === 'failure' && response.error) {\n onError(response.error);\n } else if (response.status === 'retryable') {\n onError(new OTLPExporterError('Export failed with retryable status'));\n } else {\n onError(new OTLPExporterError('Export failed with unknown error'));\n }\n }, onError);\n\n this._sendingPromises.push(promise);\n const popPromise = () => {\n const index = this._sendingPromises.indexOf(promise);\n this._sendingPromises.splice(index, 1);\n };\n promise.then(popPromise, popPromise);\n }\n}\n"]}
@@ -0,0 +1,22 @@
1
+ import { OtlpSharedConfiguration } from '@opentelemetry/otlp-exporter-base';
2
+ import type { ChannelCredentials, Metadata } from '@grpc/grpc-js';
3
+ export interface OtlpGrpcConfiguration extends OtlpSharedConfiguration {
4
+ url: string;
5
+ metadata: () => Metadata;
6
+ credentials: () => ChannelCredentials;
7
+ }
8
+ /**
9
+ * Unresolved configuration where parts of the config may depend on other config options being resolved first.
10
+ */
11
+ export interface UnresolvedOtlpGrpcConfiguration extends OtlpSharedConfiguration {
12
+ url: string;
13
+ metadata: () => Metadata;
14
+ /**
15
+ * Credentials are based on the final resolved URL
16
+ */
17
+ credentials: (url: string) => () => ChannelCredentials;
18
+ }
19
+ export declare function validateAndNormalizeUrl(url: string): string;
20
+ export declare function mergeOtlpGrpcConfigurationWithDefaults(userProvidedConfiguration: Partial<OtlpGrpcConfiguration>, fallbackConfiguration: Partial<UnresolvedOtlpGrpcConfiguration>, defaultConfiguration: UnresolvedOtlpGrpcConfiguration): OtlpGrpcConfiguration;
21
+ export declare function getOtlpGrpcDefaultConfiguration(): UnresolvedOtlpGrpcConfiguration;
22
+ //# sourceMappingURL=otlp-grpc-configuration.d.ts.map
@@ -0,0 +1,82 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright The OpenTelemetry Authors
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * https://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.getOtlpGrpcDefaultConfiguration = exports.mergeOtlpGrpcConfigurationWithDefaults = exports.validateAndNormalizeUrl = void 0;
19
+ const otlp_exporter_base_1 = require("@opentelemetry/otlp-exporter-base");
20
+ const grpc_exporter_transport_1 = require("../grpc-exporter-transport");
21
+ const version_1 = require("../version");
22
+ const url_1 = require("url");
23
+ const api_1 = require("@opentelemetry/api");
24
+ function validateAndNormalizeUrl(url) {
25
+ var _a;
26
+ url = url.trim();
27
+ const hasProtocol = url.match(/^([\w]{1,8}):\/\//);
28
+ if (!hasProtocol) {
29
+ url = `https://${url}`;
30
+ }
31
+ const target = new url_1.URL(url);
32
+ if (target.protocol === 'unix:') {
33
+ return url;
34
+ }
35
+ if (target.pathname && target.pathname !== '/') {
36
+ api_1.diag.warn('URL path should not be set when using grpc, the path part of the URL will be ignored.');
37
+ }
38
+ if (target.protocol !== '' && !((_a = target.protocol) === null || _a === void 0 ? void 0 : _a.match(/^(http)s?:$/))) {
39
+ api_1.diag.warn('URL protocol should be http(s)://. Using http://.');
40
+ }
41
+ return target.host;
42
+ }
43
+ exports.validateAndNormalizeUrl = validateAndNormalizeUrl;
44
+ function overrideMetadataEntriesIfNotPresent(metadata, additionalMetadata) {
45
+ for (const [key, value] of Object.entries(additionalMetadata.getMap())) {
46
+ // only override with env var data if the key has no values.
47
+ // not using Metadata.merge() as it will keep both values.
48
+ if (metadata.get(key).length < 1) {
49
+ metadata.set(key, value);
50
+ }
51
+ }
52
+ }
53
+ function mergeOtlpGrpcConfigurationWithDefaults(userProvidedConfiguration, fallbackConfiguration, defaultConfiguration) {
54
+ var _a, _b, _c, _d, _e;
55
+ const rawUrl = (_b = (_a = userProvidedConfiguration.url) !== null && _a !== void 0 ? _a : fallbackConfiguration.url) !== null && _b !== void 0 ? _b : defaultConfiguration.url;
56
+ return Object.assign(Object.assign({}, (0, otlp_exporter_base_1.mergeOtlpSharedConfigurationWithDefaults)(userProvidedConfiguration, fallbackConfiguration, defaultConfiguration)), { metadata: () => {
57
+ var _a, _b, _c, _d;
58
+ const metadata = defaultConfiguration.metadata();
59
+ overrideMetadataEntriesIfNotPresent(metadata,
60
+ // clone to ensure we don't modify what the user gave us in case they hold on to the returned reference
61
+ (_b = (_a = userProvidedConfiguration.metadata) === null || _a === void 0 ? void 0 : _a.call(userProvidedConfiguration).clone()) !== null && _b !== void 0 ? _b : (0, grpc_exporter_transport_1.createEmptyMetadata)());
62
+ overrideMetadataEntriesIfNotPresent(metadata, (_d = (_c = fallbackConfiguration.metadata) === null || _c === void 0 ? void 0 : _c.call(fallbackConfiguration)) !== null && _d !== void 0 ? _d : (0, grpc_exporter_transport_1.createEmptyMetadata)());
63
+ return metadata;
64
+ }, url: validateAndNormalizeUrl(rawUrl), credentials: (_e = (_c = userProvidedConfiguration.credentials) !== null && _c !== void 0 ? _c : (_d = fallbackConfiguration.credentials) === null || _d === void 0 ? void 0 : _d.call(fallbackConfiguration, rawUrl)) !== null && _e !== void 0 ? _e : defaultConfiguration.credentials(rawUrl) });
65
+ }
66
+ exports.mergeOtlpGrpcConfigurationWithDefaults = mergeOtlpGrpcConfigurationWithDefaults;
67
+ function getOtlpGrpcDefaultConfiguration() {
68
+ return Object.assign(Object.assign({}, (0, otlp_exporter_base_1.getSharedConfigurationDefaults)()), { metadata: () => {
69
+ const metadata = (0, grpc_exporter_transport_1.createEmptyMetadata)();
70
+ metadata.set('User-Agent', `OTel-OTLP-Exporter-JavaScript/${version_1.VERSION}`);
71
+ return metadata;
72
+ }, url: 'http://localhost:4317', credentials: (url) => {
73
+ if (url.startsWith('http://')) {
74
+ return () => (0, grpc_exporter_transport_1.createInsecureCredentials)();
75
+ }
76
+ else {
77
+ return () => (0, grpc_exporter_transport_1.createSslCredentials)();
78
+ }
79
+ } });
80
+ }
81
+ exports.getOtlpGrpcDefaultConfiguration = getOtlpGrpcDefaultConfiguration;
82
+ //# sourceMappingURL=otlp-grpc-configuration.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"otlp-grpc-configuration.js","sourceRoot":"","sources":["../../../src/configuration/otlp-grpc-configuration.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,0EAI2C;AAC3C,wEAIoC;AACpC,wCAAqC;AACrC,6BAA0B;AAC1B,4CAA0C;AAwB1C,SAAgB,uBAAuB,CAAC,GAAW;;IACjD,GAAG,GAAG,GAAG,CAAC,IAAI,EAAE,CAAC;IACjB,MAAM,WAAW,GAAG,GAAG,CAAC,KAAK,CAAC,mBAAmB,CAAC,CAAC;IACnD,IAAI,CAAC,WAAW,EAAE;QAChB,GAAG,GAAG,WA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AAC,QAAQ,EAAE,CAAC;YACjD,mCAAmC,CACjC,QAAQ;YACR,uGAAuG;YACvG,MAAA,MAAA,yBAAyB,CAAC,QAAQ,+CAAlC,yBAAyB,EAAc,KAAK,EAAE,mCAAI,IAAA,6CAAmB,GAAE,CACxE,CAAC;YACF,mCAAmC,CACjC,QAAQ,EACR,MAAA,MAAA,qBAAqB,CAAC,QAAQ,+CAA9B,qBAAqB,CAAa,mCAAI,IAAA,6CAAmB,GAAE,CAC5D,CAAC;YACF,OAAO,QAAQ,CAAC;QAClB,CAAC,EACD,GAAG,EAAE,uBAAuB,CAAC,MAAM,CAAC,EACpC,WAAW,EACT,MAAA,MAAA,yBAAyB,CAAC,WAAW,mCACrC,MAAA,qBAAqB,CAAC,WAAW,+CAAjC,qBAAqB,EAAe,MAAM,CAAC,mCAC3C,oBAAoB,CAAC,WAAW,CAAC,MAAM,CAAC,IAC1C;AACJ,CAAC;AAnCD,wFAmCC;AAED,SAAgB,+BAA+B;IAC7C,uCACK,IAAA,mDAA8B,GAAE,KACnC,QAAQ,EAAE,GAAG,EAAE;YACb,MAAM,QAAQ,GAAG,IAAA,6CAAmB,GAAE,CAAC;YACvC,QAAQ,CAAC,GAAG,CAAC,YAAY,EAAE,iCAAiC,iBAAO,EAAE,CAAC,CAAC;YACvE,OAAO,QAAQ,CAAC;QAClB,CAAC,EACD,GAAG,EAAE,uBAAuB,EAC5B,WAAW,EAAE,CAAC,GAAW,EAAE,EAAE;YAC3B,IAAI,GAAG,CAAC,UAAU,CAAC,SAAS,CAAC,EAAE;gBAC7B,OAAO,GAAG,EAAE,CAAC,IAAA,mDAAyB,GAAE,CAAC;aAC1C;iBAAM;gBACL,OAAO,GAAG,EAAE,CAAC,IAAA,8CAAoB,GAAE,CAAC;aACrC;QACH,CAAC,IACD;AACJ,CAAC;AAjBD,0EAiBC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n getSharedConfigurationDefaults,\n mergeOtlpSharedConfigurationWithDefaults,\n OtlpSharedConfiguration,\n} from '@opentelemetry/otlp-exporter-base';\nimport {\n createEmptyMetadata,\n createInsecureCredentials,\n createSslCredentials,\n} from '../grpc-exporter-transport';\nimport { VERSION } from '../version';\nimport { URL } from 'url';\nimport { diag } from '@opentelemetry/api';\n\n// NOTE: do not change this to be an actual import, doing so will break `@opentelemetry/instrumentation-grpc`\nimport type { ChannelCredentials, Metadata } from '@grpc/grpc-js';\n\nexport interface OtlpGrpcConfiguration extends OtlpSharedConfiguration {\n url: string;\n metadata: () => Metadata;\n credentials: () => ChannelCredentials;\n}\n\n/**\n * Unresolved configuration where parts of the config may depend on other config options being resolved first.\n */\nexport interface UnresolvedOtlpGrpcConfiguration\n extends OtlpSharedConfiguration {\n url: string;\n metadata: () => Metadata;\n /**\n * Credentials are based on the final resolved URL\n */\n credentials: (url: string) => () => ChannelCredentials;\n}\n\nexport function validateAndNormalizeUrl(url: string): string {\n url = url.trim();\n const hasProtocol = url.match(/^([\\w]{1,8}):\\/\\//);\n if (!hasProtocol) {\n url = `https://${url}`;\n }\n const target = new URL(url);\n if (target.protocol === 'unix:') {\n return url;\n }\n if (target.pathname && target.pathname !== '/') {\n diag.warn(\n 'URL path should not be set when using grpc, the path part of the URL will be ignored.'\n );\n }\n if (target.protocol !== '' && !target.protocol?.match(/^(http)s?:$/)) {\n diag.warn('URL protocol should be http(s)://. Using http://.');\n }\n return target.host;\n}\n\nfunction overrideMetadataEntriesIfNotPresent(\n metadata: Metadata,\n additionalMetadata: Metadata\n): void {\n for (const [key, value] of Object.entries(additionalMetadata.getMap())) {\n // only override with env var data if the key has no values.\n // not using Metadata.merge() as it will keep both values.\n if (metadata.get(key).length < 1) {\n metadata.set(key, value);\n }\n }\n}\n\nexport function mergeOtlpGrpcConfigurationWithDefaults(\n userProvidedConfiguration: Partial<OtlpGrpcConfiguration>,\n fallbackConfiguration: Partial<UnresolvedOtlpGrpcConfiguration>,\n defaultConfiguration: UnresolvedOtlpGrpcConfiguration\n): OtlpGrpcConfiguration {\n const rawUrl =\n userProvidedConfiguration.url ??\n fallbackConfiguration.url ??\n defaultConfiguration.url;\n\n return {\n ...mergeOtlpSharedConfigurationWithDefaults(\n userProvidedConfiguration,\n fallbackConfiguration,\n defaultConfiguration\n ),\n metadata: () => {\n const metadata = defaultConfiguration.metadata();\n overrideMetadataEntriesIfNotPresent(\n metadata,\n // clone to ensure we don't modify what the user gave us in case they hold on to the returned reference\n userProvidedConfiguration.metadata?.().clone() ?? createEmptyMetadata()\n );\n overrideMetadataEntriesIfNotPresent(\n metadata,\n fallbackConfiguration.metadata?.() ?? createEmptyMetadata()\n );\n return metadata;\n },\n url: validateAndNormalizeUrl(rawUrl),\n credentials:\n userProvidedConfiguration.credentials ??\n fallbackConfiguration.credentials?.(rawUrl) ??\n defaultConfiguration.credentials(rawUrl),\n };\n}\n\nexport function getOtlpGrpcDefaultConfiguration(): UnresolvedOtlpGrpcConfiguration {\n return {\n ...getSharedConfigurationDefaults(),\n metadata: () => {\n const metadata = createEmptyMetadata();\n metadata.set('User-Agent', `OTel-OTLP-Exporter-JavaScript/${VERSION}`);\n return metadata;\n },\n url: 'http://localhost:4317',\n credentials: (url: string) => {\n if (url.startsWith('http://')) {\n return () => createInsecureCredentials();\n } else {\n return () => createSslCredentials();\n }\n },\n };\n}\n"]}
@@ -0,0 +1,3 @@
1
+ import { UnresolvedOtlpGrpcConfiguration } from './otlp-grpc-configuration';
2
+ export declare function getOtlpGrpcConfigurationFromEnv(signalIdentifier: string): Partial<UnresolvedOtlpGrpcConfiguration>;
3
+ //# sourceMappingURL=otlp-grpc-env-configuration.d.ts.map
@@ -0,0 +1,154 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getOtlpGrpcConfigurationFromEnv = void 0;
4
+ const core_1 = require("@opentelemetry/core");
5
+ const grpc_exporter_transport_1 = require("../grpc-exporter-transport");
6
+ const otlp_exporter_base_1 = require("@opentelemetry/otlp-exporter-base");
7
+ const fs = require("fs");
8
+ const path = require("path");
9
+ const api_1 = require("@opentelemetry/api");
10
+ function fallbackIfNullishOrBlank(signalSpecific, nonSignalSpecific) {
11
+ if (signalSpecific != null && signalSpecific !== '') {
12
+ return signalSpecific;
13
+ }
14
+ if (nonSignalSpecific != null && nonSignalSpecific !== '') {
15
+ return nonSignalSpecific;
16
+ }
17
+ return undefined;
18
+ }
19
+ function getMetadataFromEnv(signalIdentifier) {
20
+ var _a, _b;
21
+ const signalSpecificRawHeaders = (_a = process.env[`OTEL_EXPORTER_OTLP_${signalIdentifier}_HEADERS`]) === null || _a === void 0 ? void 0 : _a.trim();
22
+ const nonSignalSpecificRawHeaders = (_b = process.env['OTEL_EXPORTER_OTLP_HEADERS']) === null || _b === void 0 ? void 0 : _b.trim();
23
+ const signalSpecificHeaders = core_1.baggageUtils.parseKeyPairsIntoRecord(signalSpecificRawHeaders);
24
+ const nonSignalSpecificHeaders = core_1.baggageUtils.parseKeyPairsIntoRecord(nonSignalSpecificRawHeaders);
25
+ if (Object.keys(signalSpecificHeaders).length === 0 &&
26
+ Object.keys(nonSignalSpecificHeaders).length === 0) {
27
+ return undefined;
28
+ }
29
+ const mergeHeaders = Object.assign({}, nonSignalSpecificHeaders, signalSpecificHeaders);
30
+ const metadata = (0, grpc_exporter_transport_1.createEmptyMetadata)();
31
+ // for this to work, metadata MUST be empty - otherwise `Metadata#set()` will merge items.
32
+ for (const [key, value] of Object.entries(mergeHeaders)) {
33
+ metadata.set(key, value);
34
+ }
35
+ return metadata;
36
+ }
37
+ function getMetadataProviderFromEnv(signalIdentifier) {
38
+ const metadata = getMetadataFromEnv(signalIdentifier);
39
+ if (metadata == null) {
40
+ return undefined;
41
+ }
42
+ return () => metadata;
43
+ }
44
+ function getUrlFromEnv(signalIdentifier) {
45
+ // This does not change the string beyond trimming on purpose.
46
+ // Normally a user would just use a host and port for gRPC, but the OTLP Exporter specification requires us to
47
+ // use the raw provided endpoint to derive credential settings. Therefore, we only normalize right when
48
+ // we merge user-provided, env-provided and defaults together, and we have determined which credentials to use.
49
+ //
50
+ // Examples:
51
+ // - example.test:4317 -> use secure credentials from environment (or provided via code)
52
+ // - http://example.test:4317 -> use insecure credentials if nothing else is provided
53
+ // - https://example.test:4317 -> use secure credentials from environment (or provided via code)
54
+ var _a, _b;
55
+ const specificEndpoint = (_a = process.env[`OTEL_EXPORTER_OTLP_${signalIdentifier}_ENDPOINT`]) === null || _a === void 0 ? void 0 : _a.trim();
56
+ const nonSpecificEndpoint = (_b = process.env[`OTEL_EXPORTER_OTLP_ENDPOINT`]) === null || _b === void 0 ? void 0 : _b.trim();
57
+ return fallbackIfNullishOrBlank(specificEndpoint, nonSpecificEndpoint);
58
+ }
59
+ /**
60
+ * Determines whether the env var for insecure credentials is set to {@code true}.
61
+ *
62
+ * It will allow the following values as {@code true}
63
+ * - 'true'
64
+ * - 'true '
65
+ * - ' true'
66
+ * - 'TrUE'
67
+ * - 'TRUE'
68
+ *
69
+ * It will not allow:
70
+ * - 'true false'
71
+ * - 'false true'
72
+ * - 'true!'
73
+ * - 'true,true'
74
+ * - '1'
75
+ * - ' '
76
+ *
77
+ * @param signalIdentifier
78
+ */
79
+ function getInsecureSettingFromEnv(signalIdentifier) {
80
+ var _a, _b;
81
+ const signalSpecificInsecureValue = (_a = process.env[`OTEL_EXPORTER_OTLP_${signalIdentifier}_INSECURE`]) === null || _a === void 0 ? void 0 : _a.toLowerCase().trim();
82
+ const nonSignalSpecificInsecureValue = (_b = process.env[`OTEL_EXPORTER_OTLP_INSECURE`]) === null || _b === void 0 ? void 0 : _b.toLowerCase().trim();
83
+ return (fallbackIfNullishOrBlank(signalSpecificInsecureValue, nonSignalSpecificInsecureValue) === 'true');
84
+ }
85
+ function readFileFromEnv(signalSpecificEnvVar, nonSignalSpecificEnvVar, warningMessage) {
86
+ var _a, _b;
87
+ const signalSpecificPath = (_a = process.env[signalSpecificEnvVar]) === null || _a === void 0 ? void 0 : _a.trim();
88
+ const nonSignalSpecificPath = (_b = process.env[nonSignalSpecificEnvVar]) === null || _b === void 0 ? void 0 : _b.trim();
89
+ const filePath = fallbackIfNullishOrBlank(signalSpecificPath, nonSignalSpecificPath);
90
+ if (filePath != null) {
91
+ try {
92
+ return fs.readFileSync(path.resolve(process.cwd(), filePath));
93
+ }
94
+ catch (_c) {
95
+ api_1.diag.warn(warningMessage);
96
+ return undefined;
97
+ }
98
+ }
99
+ else {
100
+ return undefined;
101
+ }
102
+ }
103
+ function getClientCertificateFromEnv(signalIdentifier) {
104
+ return readFileFromEnv(`OTEL_EXPORTER_OTLP_${signalIdentifier}_CLIENT_CERTIFICATE`, 'OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE', 'Failed to read client certificate chain file');
105
+ }
106
+ function getClientKeyFromEnv(signalIdentifier) {
107
+ return readFileFromEnv(`OTEL_EXPORTER_OTLP_${signalIdentifier}_CLIENT_KEY`, 'OTEL_EXPORTER_OTLP_CLIENT_KEY', 'Failed to read client certificate private key file');
108
+ }
109
+ function getRootCertificateFromEnv(signalIdentifier) {
110
+ return readFileFromEnv(`OTEL_EXPORTER_OTLP_${signalIdentifier}_CERTIFICATE`, 'OTEL_EXPORTER_OTLP_CERTIFICATE', 'Failed to read root certificate file');
111
+ }
112
+ function getCredentialsFromEnvIgnoreInsecure(signalIdentifier) {
113
+ const clientKey = getClientKeyFromEnv(signalIdentifier);
114
+ const clientCertificate = getClientCertificateFromEnv(signalIdentifier);
115
+ const rootCertificate = getRootCertificateFromEnv(signalIdentifier);
116
+ // if the chain is not intact, @grpc/grpc-js will throw. This is fine when a user provides it in code, but env var
117
+ // config is not allowed to throw, so we add this safeguard and try to make the best of it here.
118
+ const clientChainIntact = clientKey != null && clientCertificate != null;
119
+ if (rootCertificate != null && !clientChainIntact) {
120
+ api_1.diag.warn('Client key and certificate must both be provided, but one was missing - attempting to create credentials from just the root certificate');
121
+ return (0, grpc_exporter_transport_1.createSslCredentials)(getRootCertificateFromEnv(signalIdentifier));
122
+ }
123
+ return (0, grpc_exporter_transport_1.createSslCredentials)(rootCertificate, clientKey, clientCertificate);
124
+ }
125
+ function getCredentialsFromEnv(signalIdentifier) {
126
+ if (getInsecureSettingFromEnv(signalIdentifier)) {
127
+ return (0, grpc_exporter_transport_1.createInsecureCredentials)();
128
+ }
129
+ return getCredentialsFromEnvIgnoreInsecure(signalIdentifier);
130
+ }
131
+ function getOtlpGrpcConfigurationFromEnv(signalIdentifier) {
132
+ return Object.assign(Object.assign({}, (0, otlp_exporter_base_1.getSharedConfigurationFromEnvironment)(signalIdentifier)), { metadata: getMetadataProviderFromEnv(signalIdentifier), url: getUrlFromEnv(signalIdentifier), credentials: (finalResolvedUrl) => {
133
+ // Always assume insecure on http:// and secure on https://, the protocol always takes precedence over the insecure setting.
134
+ // note: the spec does not make any exception for
135
+ // - "localhost:4317". If the protocol is omitted, credentials are required unless insecure is set
136
+ // - "unix://", as it's neither http:// nor https:// and therefore credentials are required unless insecure is set
137
+ if (finalResolvedUrl.startsWith('http://')) {
138
+ return () => {
139
+ return (0, grpc_exporter_transport_1.createInsecureCredentials)();
140
+ };
141
+ }
142
+ else if (finalResolvedUrl.startsWith('https://')) {
143
+ return () => {
144
+ return getCredentialsFromEnvIgnoreInsecure(signalIdentifier);
145
+ };
146
+ }
147
+ // defer to env settings in this case
148
+ return () => {
149
+ return getCredentialsFromEnv(signalIdentifier);
150
+ };
151
+ } });
152
+ }
153
+ exports.getOtlpGrpcConfigurationFromEnv = getOtlpGrpcConfigurationFromEnv;
154
+ //# sourceMappingURL=otlp-grpc-env-configuration.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"otlp-grpc-env-configuration.js","sourceRoot":"","sources":["../../../src/configuration/otlp-grpc-env-configuration.ts"],"names":[],"mappings":";;;AAiBA,8CAAmD;AACnD,wEAIoC;AACpC,0EAA0F;AAC1F,yBAAyB;AACzB,6BAA6B;AAC7B,4CAA0C;AAE1C,SAAS,wBAAwB,CAC/B,cAAuB,EACvB,iBAA0B;IAE1B,IAAI,cAAc,IAAI,IAAI,IAAI,cAAc,KAAK,EAAE,EAAE;QACnD,OAAO,cAAc,CAAC;KACvB;IAED,IAAI,iBAAiB,IAAI,IAAI,IAAI,iBAAiB,KAAK,EAAE,EAAE;QACzD,OAAO,iBAAiB,CAAC;KAC1B;IAED,OAAO,SAAS,CAAC;AACnB,CAAC;AAED,SAAS,kBAAkB,CAAC,gBAAwB;;IAClD,MAAM,wBAAwB,GAC5B,MAAA,OAAO,CAAC,GAAG,CAAC,sBAAsB,gBAAgB,UAAU,CAAC,0CAAE,IAAI,EAAE,CAAC;IACxE,MAAM,2BAA2B,GAC/B,MAAA,OAAO,CAAC,GAAG,CAAC,4BAA4B,CAAC,0CAAE,IAAI,EAAE,CAAC;IAEpD,MAAM,qBAAqB,GAAG,mBAAY,CAAC,uBAAuB,CAChE,wBAAwB,CACzB,CAAC;IACF,MAAM,wBAAwB,GAAG,mBAAY,CAAC,uBAAuB,CACnE,2BAA2B,CAC5B,CAAC;IAEF,IACE,MAAM,CAAC,IAAI,CAAC,qBAAqB,CAAC,CAAC,MAAM,KAAK,CAAC;QAC/C,MAAM,CAAC,IAAI,CAAC,wBAAwB,CAAC,CAAC,MAAM,KAAK,CAAC,EAClD;QACA,OAAO,SAAS,CAAC;KAClB;IAED,MAAM,YAAY,GAAG,MAAM,CAAC,MAAM,CAChC,EAAE,EACF,wBAAwB,EACxB,qBAAqB,CACtB,CAAC;IAEF,MAAM,QAAQ,GAAG,IAAA,6CAAmB,GAAE,CAAC;IAEvC,0FAA0F;IAC1F,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CA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CAAC,CAAC;YACjD,CAAC,CAAC;QACJ,CAAC,IACD;AACJ,CAAC;AA5BD,0EA4BC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { UnresolvedOtlpGrpcConfiguration } from './otlp-grpc-configuration';\nimport type { ChannelCredentials, Metadata } from '@grpc/grpc-js';\nimport { baggageUtils } from '@opentelemetry/core';\nimport {\n createEmptyMetadata,\n createInsecureCredentials,\n createSslCredentials,\n} from '../grpc-exporter-transport';\nimport { getSharedConfigurationFromEnvironment } from '@opentelemetry/otlp-exporter-base';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { diag } from '@opentelemetry/api';\n\nfunction fallbackIfNullishOrBlank(\n signalSpecific?: string,\n nonSignalSpecific?: string\n): string | undefined {\n if (signalSpecific != null && signalSpecific !== '') {\n return signalSpecific;\n }\n\n if (nonSignalSpecific != null && nonSignalSpecific !== '') {\n return nonSignalSpecific;\n }\n\n return undefined;\n}\n\nfunction getMetadataFromEnv(signalIdentifier: string): Metadata | undefined {\n const signalSpecificRawHeaders =\n process.env[`OTEL_EXPORTER_OTLP_${signalIdentifier}_HEADERS`]?.trim();\n const nonSignalSpecificRawHeaders =\n process.env['OTEL_EXPORTER_OTLP_HEADERS']?.trim();\n\n const signalSpecificHeaders = baggageUtils.parseKeyPairsIntoRecord(\n signalSpecificRawHeaders\n );\n const nonSignalSpecificHeaders = baggageUtils.parseKeyPairsIntoRecord(\n nonSignalSpecificRawHeaders\n );\n\n if (\n Object.keys(signalSpecificHeaders).length === 0 &&\n Object.keys(nonSignalSpecificHeaders).length === 0\n ) {\n return undefined;\n }\n\n const mergeHeaders = Object.assign(\n {},\n nonSignalSpecificHeaders,\n signalSpecificHeaders\n );\n\n const metadata = createEmptyMetadata();\n\n // for this to work, metadata MUST be empty - otherwise `Metadata#set()` will merge items.\n for (const [key, value] of Object.entries(mergeHeaders)) {\n metadata.set(key, value);\n }\n\n return metadata;\n}\n\nfunction getMetadataProviderFromEnv(\n signalIdentifier: string\n): (() => Metadata) | undefined {\n const metadata = getMetadataFromEnv(signalIdentifier);\n if (metadata == null) {\n return undefined;\n }\n\n return () => metadata;\n}\n\nfunction getUrlFromEnv(signalIdentifier: string) {\n // This does not change the string beyond trimming on purpose.\n // Normally a user would just use a host and port for gRPC, but the OTLP Exporter specification requires us to\n // use the raw provided endpoint to derive credential settings. Therefore, we only normalize right when\n // we merge user-provided, env-provided and defaults together, and we have determined which credentials to use.\n //\n // Examples:\n // - example.test:4317 -> use secure credentials from environment (or provided via code)\n // - http://example.test:4317 -> use insecure credentials if nothing else is provided\n // - https://example.test:4317 -> use secure credentials from environment (or provided via code)\n\n const specificEndpoint =\n process.env[`OTEL_EXPORTER_OTLP_${signalIdentifier}_ENDPOINT`]?.trim();\n const nonSpecificEndpoint =\n process.env[`OTEL_EXPORTER_OTLP_ENDPOINT`]?.trim();\n\n return fallbackIfNullishOrBlank(specificEndpoint, nonSpecificEndpoint);\n}\n\n/**\n * Determines whether the env var for insecure credentials is set to {@code true}.\n *\n * It will allow the following values as {@code true}\n * - 'true'\n * - 'true '\n * - ' true'\n * - 'TrUE'\n * - 'TRUE'\n *\n * It will not allow:\n * - 'true false'\n * - 'false true'\n * - 'true!'\n * - 'true,true'\n * - '1'\n * - ' '\n *\n * @param signalIdentifier\n */\nfunction getInsecureSettingFromEnv(signalIdentifier: string): boolean {\n const signalSpecificInsecureValue = process.env[\n `OTEL_EXPORTER_OTLP_${signalIdentifier}_INSECURE`\n ]\n ?.toLowerCase()\n .trim();\n const nonSignalSpecificInsecureValue = process.env[\n `OTEL_EXPORTER_OTLP_INSECURE`\n ]\n ?.toLowerCase()\n .trim();\n\n return (\n fallbackIfNullishOrBlank(\n signalSpecificInsecureValue,\n nonSignalSpecificInsecureValue\n ) === 'true'\n );\n}\n\nfunction readFileFromEnv(\n signalSpecificEnvVar: string,\n nonSignalSpecificEnvVar: string,\n warningMessage: string\n): Buffer | undefined {\n const signalSpecificPath = process.env[signalSpecificEnvVar]?.trim();\n const nonSignalSpecificPath = process.env[nonSignalSpecificEnvVar]?.trim();\n\n const filePath = fallbackIfNullishOrBlank(\n signalSpecificPath,\n nonSignalSpecificPath\n );\n\n if (filePath != null) {\n try {\n return fs.readFileSync(path.resolve(process.cwd(), filePath));\n } catch {\n diag.warn(warningMessage);\n return undefined;\n }\n } else {\n return undefined;\n }\n}\n\nfunction getClientCertificateFromEnv(\n signalIdentifier: string\n): Buffer | undefined {\n return readFileFromEnv(\n `OTEL_EXPORTER_OTLP_${signalIdentifier}_CLIENT_CERTIFICATE`,\n 'OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE',\n 'Failed to read client certificate chain file'\n );\n}\n\nfunction getClientKeyFromEnv(signalIdentifier: string): Buffer | undefined {\n return readFileFromEnv(\n `OTEL_EXPORTER_OTLP_${signalIdentifier}_CLIENT_KEY`,\n 'OTEL_EXPORTER_OTLP_CLIENT_KEY',\n 'Failed to read client certificate private key file'\n );\n}\n\nfunction getRootCertificateFromEnv(\n signalIdentifier: string\n): Buffer | undefined {\n return readFileFromEnv(\n `OTEL_EXPORTER_OTLP_${signalIdentifier}_CERTIFICATE`,\n 'OTEL_EXPORTER_OTLP_CERTIFICATE',\n 'Failed to read root certificate file'\n );\n}\n\nfunction getCredentialsFromEnvIgnoreInsecure(\n signalIdentifier: string\n): ChannelCredentials {\n const clientKey = getClientKeyFromEnv(signalIdentifier);\n const clientCertificate = getClientCertificateFromEnv(signalIdentifier);\n const rootCertificate = getRootCertificateFromEnv(signalIdentifier);\n\n // if the chain is not intact, @grpc/grpc-js will throw. This is fine when a user provides it in code, but env var\n // config is not allowed to throw, so we add this safeguard and try to make the best of it here.\n const clientChainIntact = clientKey != null && clientCertificate != null;\n if (rootCertificate != null && !clientChainIntact) {\n diag.warn(\n 'Client key and certificate must both be provided, but one was missing - attempting to create credentials from just the root certificate'\n );\n return createSslCredentials(getRootCertificateFromEnv(signalIdentifier));\n }\n\n return createSslCredentials(rootCertificate, clientKey, clientCertificate);\n}\n\nfunction getCredentialsFromEnv(signalIdentifier: string): ChannelCredentials {\n if (getInsecureSettingFromEnv(signalIdentifier)) {\n return createInsecureCredentials();\n }\n\n return getCredentialsFromEnvIgnoreInsecure(signalIdentifier);\n}\n\nexport function getOtlpGrpcConfigurationFromEnv(\n signalIdentifier: string\n): Partial<UnresolvedOtlpGrpcConfiguration> {\n return {\n ...getSharedConfigurationFromEnvironment(signalIdentifier),\n metadata: getMetadataProviderFromEnv(signalIdentifier),\n url: getUrlFromEnv(signalIdentifier),\n credentials: (finalResolvedUrl: string) => {\n // Always assume insecure on http:// and secure on https://, the protocol always takes precedence over the insecure setting.\n // note: the spec does not make any exception for\n // - \"localhost:4317\". If the protocol is omitted, credentials are required unless insecure is set\n // - \"unix://\", as it's neither http:// nor https:// and therefore credentials are required unless insecure is set\n if (finalResolvedUrl.startsWith('http://')) {\n return () => {\n return createInsecureCredentials();\n };\n } else if (finalResolvedUrl.startsWith('https://')) {\n return () => {\n return getCredentialsFromEnvIgnoreInsecure(signalIdentifier);\n };\n }\n\n // defer to env settings in this case\n return () => {\n return getCredentialsFromEnv(signalIdentifier);\n };\n },\n };\n}\n"]}
@@ -1,7 +1,6 @@
1
1
  /// <reference types="node" />
2
2
  import type { Metadata, ChannelCredentials } from '@grpc/grpc-js';
3
- import { ExportResponse } from './export-response';
4
- import { IExporterTransport } from './exporter-transport';
3
+ import { ExportResponse, IExporterTransport } from '@opentelemetry/otlp-exporter-base';
5
4
  export declare function createInsecureCredentials(): ChannelCredentials;
6
5
  export declare function createSslCredentials(rootCert?: Buffer, privateKey?: Buffer, certChain?: Buffer): ChannelCredentials;
7
6
  export declare function createEmptyMetadata(): Metadata;
@@ -27,7 +26,6 @@ export interface GrpcExporterTransportParameters {
27
26
  */
28
27
  metadata: () => Metadata;
29
28
  compression: 'gzip' | 'none';
30
- timeoutMillis: number;
31
29
  }
32
30
  export declare class GrpcExporterTransport implements IExporterTransport {
33
31
  private _parameters;
@@ -35,6 +33,6 @@ export declare class GrpcExporterTransport implements IExporterTransport {
35
33
  private _metadata?;
36
34
  constructor(_parameters: GrpcExporterTransportParameters);
37
35
  shutdown(): void;
38
- send(data: Uint8Array): Promise<ExportResponse>;
36
+ send(data: Uint8Array, timeoutMillis: number): Promise<ExportResponse>;
39
37
  }
40
38
  //# sourceMappingURL=grpc-exporter-transport.d.ts.map
@@ -54,7 +54,7 @@ class GrpcExporterTransport {
54
54
  var _a;
55
55
  (_a = this._client) === null || _a === void 0 ? void 0 : _a.close();
56
56
  }
57
- send(data) {
57
+ send(data, timeoutMillis) {
58
58
  // We need to make a for gRPC
59
59
  const buffer = Buffer.from(data);
60
60
  if (this._client == null) {
@@ -85,9 +85,7 @@ class GrpcExporterTransport {
85
85
  }
86
86
  }
87
87
  return new Promise(resolve => {
88
- // this will always be defined
89
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
90
- const deadline = Date.now() + this._parameters.timeoutMillis;
88
+ const deadline = Date.now() + timeoutMillis;
91
89
  // this should never happen
92
90
  if (this._metadata == null) {
93
91
  return resolve({
@@ -1 +1 @@
1
- {"version":3,"file":"grpc-exporter-transport.js","sourceRoot":"","sources":["../../src/grpc-exporter-transport.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAaH,gFAAgF;AAChF,MAAM,qBAAqB,GAAG,CAAC,CAAC;AAChC,MAAM,qBAAqB,GAAG,CAAC,CAAC;AAEhC,SAAS,iBAAiB,CAAC,WAA4B;IACrD,OAAO,WAAW,KAAK,MAAM,CAAC,CAAC,CAAC,qBAAqB,CAAC,CAAC,CAAC,qBAA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qBAAM;oBACL,OAAO,CAAC;wBACN,IAAI,EAAE,QAAQ;wBACd,MAAM,EAAE,SAAS;qBAClB,CAAC,CAAC;iBACJ;YACH,CAAC,CACF,CAAC;QACJ,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AAxFD,sDAwFC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// NOTE: do not change these type imports to actual imports. Doing so WILL break `@opentelemetry/instrumentation-http`,\n// as they'd be imported before the http/https modules can be wrapped.\nimport type {\n Metadata,\n ServiceError,\n ChannelCredentials,\n Client,\n} from '@grpc/grpc-js';\nimport { ExportResponse } from './export-response';\nimport { IExporterTransport } from './exporter-transport';\n\n// values taken from '@grpc/grpc-js` so that we don't need to require/import it.\nconst GRPC_COMPRESSION_NONE = 0;\nconst GRPC_COMPRESSION_GZIP = 2;\n\nfunction toGrpcCompression(compression: 'gzip' | 'none'): number {\n return compression === 'gzip' ? GRPC_COMPRESSION_GZIP : GRPC_COMPRESSION_NONE;\n}\n\nexport function createInsecureCredentials(): ChannelCredentials {\n // Lazy-load so that we don't need to require/import '@grpc/grpc-js' before it can be wrapped by instrumentation.\n const {\n credentials,\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n } = require('@grpc/grpc-js');\n return credentials.createInsecure();\n}\n\nexport function createSslCredentials(\n rootCert?: Buffer,\n privateKey?: Buffer,\n certChain?: Buffer\n): ChannelCredentials {\n // Lazy-load so that we don't need to require/import '@grpc/grpc-js' before it can be wrapped by instrumentation.\n const {\n credentials,\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n } = require('@grpc/grpc-js');\n return credentials.createSsl(rootCert, privateKey, certChain);\n}\n\nexport function createEmptyMetadata(): Metadata {\n // Lazy-load so that we don't need to require/import '@grpc/grpc-js' before it can be wrapped by instrumentation.\n const {\n Metadata,\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n } = require('@grpc/grpc-js');\n return new Metadata();\n}\n\nexport interface GrpcExporterTransportParameters {\n grpcPath: string;\n grpcName: string;\n address: string;\n /**\n * NOTE: Ensure that you're only importing/requiring gRPC inside the function providing the channel credentials,\n * otherwise, gRPC and http/https instrumentations may break.\n *\n * For common cases, you can avoid to import/require gRPC your function by using\n * - {@link createSslCredentials}\n * - {@link createInsecureCredentials}\n */\n credentials: () => ChannelCredentials;\n /**\n * NOTE: Ensure that you're only importing/requiring gRPC inside the function providing the metadata,\n * otherwise, gRPC and http/https instrumentations may break.\n *\n * To avoid having to import/require gRPC from your function to create a new Metadata object,\n * use {@link createEmptyMetadata}\n */\n metadata: () => Metadata;\n compression: 'gzip' | 'none';\n timeoutMillis: number;\n}\n\nexport class GrpcExporterTransport implements IExporterTransport {\n private _client?: Client;\n private _metadata?: Metadata;\n\n constructor(private _parameters: GrpcExporterTransportParameters) {}\n\n shutdown() {\n this._client?.close();\n }\n\n send(data: Uint8Array): Promise<ExportResponse> {\n // We need to make a for gRPC\n const buffer = Buffer.from(data);\n\n if (this._client == null) {\n // Lazy require to ensure that grpc is not loaded before instrumentations can wrap it\n const {\n createServiceClientConstructor,\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n } = require('./create-service-client-constructor');\n\n try {\n this._metadata = this._parameters.metadata();\n } catch (error) {\n return Promise.resolve({\n status: 'failure',\n error: error,\n });\n }\n\n const clientConstructor = createServiceClientConstructor(\n this._parameters.grpcPath,\n this._parameters.grpcName\n );\n\n try {\n this._client = new clientConstructor(\n this._parameters.address,\n this._parameters.credentials(),\n {\n 'grpc.default_compression_algorithm': toGrpcCompression(\n this._parameters.compression\n ),\n }\n );\n } catch (error) {\n return Promise.resolve({\n status: 'failure',\n error: error,\n });\n }\n }\n\n return new Promise<ExportResponse>(resolve => {\n // this will always be defined\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const deadline = Date.now() + this._parameters.timeoutMillis;\n\n // this should never happen\n if (this._metadata == null) {\n return resolve({\n error: new Error('metadata was null'),\n status: 'failure',\n });\n }\n\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore The gRPC client constructor is created on runtime, so we don't have any types for the resulting client.\n this._client.export(\n buffer,\n this._metadata,\n { deadline: deadline },\n (err: ServiceError, response: Buffer) => {\n if (err) {\n resolve({\n status: 'failure',\n error: err,\n });\n } else {\n resolve({\n data: response,\n status: 'success',\n });\n }\n }\n );\n });\n }\n}\n"]}
1
+ {"version":3,"file":"grpc-exporter-transport.js","sourceRoot":"","sources":["../../src/grpc-exporter-transport.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAeH,gFAAgF;AAChF,MAAM,qBAAqB,GAAG,CAAC,CAAC;AAChC,MAAM,qBAAqB,GAAG,CAAC,CAAC;AAEhC,SAAS,iBAAiB,CAAC,WAA4B;IACrD,OAAO,WAAW,KAAK,MAAM,CAAC,CAAC,CAAC,qBAAqB,CAAC,CAAC,CAAC,qBAAqB,CAAC;AAChF,CAAC;AAED,SAAgB,yBAAyB;IACvC,iHAAiH;IACjH,MAAM,EACJ,WAAW;IACX,8DAA8D;MAC/D,GAAG,OAAO,CAAC,eAAe,CAAC,CAAC;IAC7B,OAAO,WAAW,CAAC,cAAc,EAAE,CAAC;AACtC,CAAC;AAPD,8DAOC;AAED,SAAgB,oBAAoB,CAClC,QAAiB,EACjB,UAAmB,EACnB,SAAkB;IAElB,iHAAiH;IACjH,MAAM,EACJ,WAAW;IACX,8DAA8D;MAC/D,GAAG,OAAO,CAAC,eAAe,CAAC,CAAC;IAC7B,OAAO,WAAW,CAAC,SAAS,CAAC,QAAQ,EAAE,UAAU,EAAE,SAAS,CAAC,CAAC;AAChE,C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,OAAO,KAAK,EAAE;gBACd,OAAO,OAAO,CAAC,OAAO,CAAC;oBACrB,MAAM,EAAE,SAAS;oBACjB,KAAK,EAAE,KAAK;iBACb,CAAC,CAAC;aACJ;SACF;QAED,OAAO,IAAI,OAAO,CAAiB,OAAO,CAAC,EAAE;YAC3C,MAAM,QAAQ,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,aAAa,CAAC;YAE5C,2BAA2B;YAC3B,IAAI,IAAI,CAAC,SAAS,IAAI,IAAI,EAAE;gBAC1B,OAAO,OAAO,CAAC;oBACb,KAAK,EAAE,IAAI,KAAK,CAAC,mBAAmB,CAAC;oBACrC,MAAM,EAAE,SAAS;iBAClB,CAAC,CAAC;aACJ;YAED,6DAA6D;YAC7D,qHAAqH;YACrH,IAAI,CAAC,OAAO,CAAC,MAAM,CACjB,MAAM,EACN,IAAI,CAAC,SAAS,EACd,EAAE,QAAQ,EAAE,QAAQ,EAAE,EACtB,CAAC,GAAiB,EAAE,QAAgB,EAAE,EAAE;gBACtC,IAAI,GAAG,EAAE;oBACP,OAAO,CAAC;wBACN,MAAM,EAAE,SAAS;wBACjB,KAAK,EAAE,GAAG;qBACX,CAAC,CAAC;iBACJ;qBAAM;oBACL,OAAO,CAAC;wBACN,IAAI,EAAE,QAAQ;wBACd,MAAM,EAAE,SAAS;qBAClB,CAAC,CAAC;iBACJ;YACH,CAAC,CACF,CAAC;QACJ,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AAtFD,sDAsFC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// NOTE: do not change these type imports to actual imports. Doing so WILL break `@opentelemetry/instrumentation-http`,\n// as they'd be imported before the http/https modules can be wrapped.\nimport type {\n Metadata,\n ServiceError,\n ChannelCredentials,\n Client,\n} from '@grpc/grpc-js';\nimport {\n ExportResponse,\n IExporterTransport,\n} from '@opentelemetry/otlp-exporter-base';\n\n// values taken from '@grpc/grpc-js` so that we don't need to require/import it.\nconst GRPC_COMPRESSION_NONE = 0;\nconst GRPC_COMPRESSION_GZIP = 2;\n\nfunction toGrpcCompression(compression: 'gzip' | 'none'): number {\n return compression === 'gzip' ? GRPC_COMPRESSION_GZIP : GRPC_COMPRESSION_NONE;\n}\n\nexport function createInsecureCredentials(): ChannelCredentials {\n // Lazy-load so that we don't need to require/import '@grpc/grpc-js' before it can be wrapped by instrumentation.\n const {\n credentials,\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n } = require('@grpc/grpc-js');\n return credentials.createInsecure();\n}\n\nexport function createSslCredentials(\n rootCert?: Buffer,\n privateKey?: Buffer,\n certChain?: Buffer\n): ChannelCredentials {\n // Lazy-load so that we don't need to require/import '@grpc/grpc-js' before it can be wrapped by instrumentation.\n const {\n credentials,\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n } = require('@grpc/grpc-js');\n return credentials.createSsl(rootCert, privateKey, certChain);\n}\n\nexport function createEmptyMetadata(): Metadata {\n // Lazy-load so that we don't need to require/import '@grpc/grpc-js' before it can be wrapped by instrumentation.\n const {\n Metadata,\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n } = require('@grpc/grpc-js');\n return new Metadata();\n}\n\nexport interface GrpcExporterTransportParameters {\n grpcPath: string;\n grpcName: string;\n address: string;\n /**\n * NOTE: Ensure that you're only importing/requiring gRPC inside the function providing the channel credentials,\n * otherwise, gRPC and http/https instrumentations may break.\n *\n * For common cases, you can avoid to import/require gRPC your function by using\n * - {@link createSslCredentials}\n * - {@link createInsecureCredentials}\n */\n credentials: () => ChannelCredentials;\n /**\n * NOTE: Ensure that you're only importing/requiring gRPC inside the function providing the metadata,\n * otherwise, gRPC and http/https instrumentations may break.\n *\n * To avoid having to import/require gRPC from your function to create a new Metadata object,\n * use {@link createEmptyMetadata}\n */\n metadata: () => Metadata;\n compression: 'gzip' | 'none';\n}\n\nexport class GrpcExporterTransport implements IExporterTransport {\n private _client?: Client;\n private _metadata?: Metadata;\n\n constructor(private _parameters: GrpcExporterTransportParameters) {}\n\n shutdown() {\n this._client?.close();\n }\n\n send(data: Uint8Array, timeoutMillis: number): Promise<ExportResponse> {\n // We need to make a for gRPC\n const buffer = Buffer.from(data);\n\n if (this._client == null) {\n // Lazy require to ensure that grpc is not loaded before instrumentations can wrap it\n const {\n createServiceClientConstructor,\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n } = require('./create-service-client-constructor');\n\n try {\n this._metadata = this._parameters.metadata();\n } catch (error) {\n return Promise.resolve({\n status: 'failure',\n error: error,\n });\n }\n\n const clientConstructor = createServiceClientConstructor(\n this._parameters.grpcPath,\n this._parameters.grpcName\n );\n\n try {\n this._client = new clientConstructor(\n this._parameters.address,\n this._parameters.credentials(),\n {\n 'grpc.default_compression_algorithm': toGrpcCompression(\n this._parameters.compression\n ),\n }\n );\n } catch (error) {\n return Promise.resolve({\n status: 'failure',\n error: error,\n });\n }\n }\n\n return new Promise<ExportResponse>(resolve => {\n const deadline = Date.now() + timeoutMillis;\n\n // this should never happen\n if (this._metadata == null) {\n return resolve({\n error: new Error('metadata was null'),\n status: 'failure',\n });\n }\n\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore The gRPC client constructor is created on runtime, so we don't have any types for the resulting client.\n this._client.export(\n buffer,\n this._metadata,\n { deadline: deadline },\n (err: ServiceError, response: Buffer) => {\n if (err) {\n resolve({\n status: 'failure',\n error: err,\n });\n } else {\n resolve({\n data: response,\n status: 'success',\n });\n }\n }\n );\n });\n }\n}\n"]}
@@ -1,4 +1,3 @@
1
1
  export { OTLPGRPCExporterNodeBase } from './OTLPGRPCExporterNodeBase';
2
2
  export { OTLPGRPCExporterConfigNode } from './types';
3
- export { DEFAULT_COLLECTOR_URL, validateAndNormalizeUrl } from './util';
4
3
  //# sourceMappingURL=index.d.ts.map
@@ -15,10 +15,7 @@
15
15
  * limitations under the License.
16
16
  */
17
17
  Object.defineProperty(exports, "__esModule", { value: true });
18
- exports.validateAndNormalizeUrl = exports.DEFAULT_COLLECTOR_URL = exports.OTLPGRPCExporterNodeBase = void 0;
18
+ exports.OTLPGRPCExporterNodeBase = void 0;
19
19
  var OTLPGRPCExporterNodeBase_1 = require("./OTLPGRPCExporterNodeBase");
20
20
  Object.defineProperty(exports, "OTLPGRPCExporterNodeBase", { enumerable: true, get: function () { return OTLPGRPCExporterNodeBase_1.OTLPGRPCExporterNodeBase; } });
21
- var util_1 = require("./util");
22
- Object.defineProperty(exports, "DEFAULT_COLLECTOR_URL", { enumerable: true, get: function () { return util_1.DEFAULT_COLLECTOR_URL; } });
23
- Object.defineProperty(exports, "validateAndNormalizeUrl", { enumerable: true, get: function () { return util_1.validateAndNormalizeUrl; } });
24
21
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,uEAAsE;AAA7D,oIAAA,wBAAwB,OAAA;AAEjC,+BAAwE;AAA/D,6GAAA,qBAAqB,OAAA;AAAE,+GAAA,uBAAuB,OAAA","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport { OTLPGRPCExporterNodeBase } from './OTLPGRPCExporterNodeBase';\nexport { OTLPGRPCExporterConfigNode } from './types';\nexport { DEFAULT_COLLECTOR_URL, validateAndNormalizeUrl } from './util';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,uEAAsE;AAA7D,oIAAA,wBAAwB,OAAA","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport { OTLPGRPCExporterNodeBase } from './OTLPGRPCExporterNodeBase';\nexport { OTLPGRPCExporterConfigNode } from './types';\n"]}
@@ -1,14 +1,5 @@
1
1
  import type { ChannelCredentials, Metadata } from '@grpc/grpc-js';
2
- import { CompressionAlgorithm, OTLPExporterConfigBase, OTLPExporterError } from '@opentelemetry/otlp-exporter-base';
3
- /**
4
- * Queue item to be used to save temporary spans/metrics/logs in case the GRPC service
5
- * hasn't been fully initialized yet
6
- */
7
- export interface GRPCQueueItem<ExportedItem> {
8
- objects: ExportedItem[];
9
- onSuccess: () => void;
10
- onError: (error: OTLPExporterError) => void;
11
- }
2
+ import { CompressionAlgorithm, OTLPExporterConfigBase } from '@opentelemetry/otlp-exporter-base';
12
3
  /**
13
4
  * OTLP Exporter Config for Node
14
5
  */
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { ChannelCredentials, Metadata } from '@grpc/grpc-js';\n\nimport {\n CompressionAlgorithm,\n OTLPExporterConfigBase,\n OTLPExporterError,\n} from '@opentelemetry/otlp-exporter-base';\n\n/**\n * Queue item to be used to save temporary spans/metrics/logs in case the GRPC service\n * hasn't been fully initialized yet\n */\nexport interface GRPCQueueItem<ExportedItem> {\n objects: ExportedItem[];\n onSuccess: () => void;\n onError: (error: OTLPExporterError) => void;\n}\n\n/**\n * OTLP Exporter Config for Node\n */\nexport interface OTLPGRPCExporterConfigNode extends OTLPExporterConfigBase {\n credentials?: ChannelCredentials;\n metadata?: Metadata;\n compression?: CompressionAlgorithm;\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { ChannelCredentials, Metadata } from '@grpc/grpc-js';\n\nimport {\n CompressionAlgorithm,\n OTLPExporterConfigBase,\n} from '@opentelemetry/otlp-exporter-base';\n\n/**\n * OTLP Exporter Config for Node\n */\nexport interface OTLPGRPCExporterConfigNode extends OTLPExporterConfigBase {\n credentials?: ChannelCredentials;\n metadata?: Metadata;\n compression?: CompressionAlgorithm;\n}\n"]}
@@ -1,2 +1,2 @@
1
- export declare const VERSION = "0.52.1";
1
+ export declare const VERSION = "0.54.0";
2
2
  //# sourceMappingURL=version.d.ts.map
@@ -17,5 +17,5 @@
17
17
  Object.defineProperty(exports, "__esModule", { value: true });
18
18
  exports.VERSION = void 0;
19
19
  // this is autogenerated file, see scripts/version-update.js
20
- exports.VERSION = '0.52.1';
20
+ exports.VERSION = '0.54.0';
21
21
  //# sourceMappingURL=version.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,4DAA4D;AAC/C,QAAA,OAAO,GAAG,QAAQ,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '0.52.1';\n"]}
1
+ {"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,4DAA4D;AAC/C,QAAA,OAAO,GAAG,QAAQ,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '0.54.0';\n"]}
package/package.json CHANGED
@@ -1,19 +1,18 @@
1
1
  {
2
2
  "name": "@opentelemetry/otlp-grpc-exporter-base",
3
- "version": "0.52.1",
3
+ "version": "0.54.0",
4
4
  "description": "OpenTelemetry OTLP-gRPC Exporter base (for internal use only)",
5
5
  "main": "build/src/index.js",
6
6
  "types": "build/src/index.d.ts",
7
7
  "repository": "open-telemetry/opentelemetry-js",
8
8
  "scripts": {
9
9
  "prepublishOnly": "npm run compile",
10
- "codecov": "nyc report --reporter=json && codecov -f coverage/*.json -p ../../../",
11
10
  "compile": "tsc --build",
12
11
  "clean": "tsc --build --clean",
13
12
  "lint": "eslint . --ext .ts",
14
13
  "lint:fix": "eslint . --ext .ts --fix",
15
14
  "tdd": "npm run test -- --watch-extensions ts --watch",
16
- "test": "nyc ts-mocha -p tsconfig.json 'test/**/*.test.ts'",
15
+ "test": "nyc mocha 'test/**/*.test.ts'",
17
16
  "version": "node ../../../scripts/version-update.js",
18
17
  "watch": "tsc -w",
19
18
  "precompile": "cross-var lerna run version --scope $npm_package_name --include-dependencies",
@@ -48,31 +47,29 @@
48
47
  },
49
48
  "devDependencies": {
50
49
  "@opentelemetry/api": "1.9.0",
51
- "@opentelemetry/resources": "1.25.1",
52
- "@opentelemetry/sdk-trace-base": "1.25.1",
53
- "@types/mocha": "10.0.6",
50
+ "@opentelemetry/resources": "1.27.0",
51
+ "@opentelemetry/sdk-trace-base": "1.27.0",
52
+ "@types/mocha": "10.0.8",
54
53
  "@types/node": "18.6.5",
55
54
  "@types/sinon": "17.0.3",
56
- "codecov": "3.8.3",
57
55
  "cross-var": "1.1.0",
58
56
  "lerna": "6.6.2",
59
- "mocha": "10.2.0",
57
+ "mocha": "10.7.3",
60
58
  "nyc": "15.1.0",
61
59
  "sinon": "15.1.2",
62
60
  "ts-loader": "9.5.1",
63
- "ts-mocha": "10.0.0",
64
61
  "typescript": "4.4.4"
65
62
  },
66
63
  "peerDependencies": {
67
- "@opentelemetry/api": "^1.0.0"
64
+ "@opentelemetry/api": "^1.3.0"
68
65
  },
69
66
  "dependencies": {
70
67
  "@grpc/grpc-js": "^1.7.1",
71
- "@opentelemetry/core": "1.25.1",
72
- "@opentelemetry/otlp-exporter-base": "0.52.1",
73
- "@opentelemetry/otlp-transformer": "0.52.1"
68
+ "@opentelemetry/core": "1.27.0",
69
+ "@opentelemetry/otlp-exporter-base": "0.54.0",
70
+ "@opentelemetry/otlp-transformer": "0.54.0"
74
71
  },
75
72
  "homepage": "https://github.com/open-telemetry/opentelemetry-js/tree/main/experimental/packages/otlp-grpc-exporter-base",
76
73
  "sideEffects": false,
77
- "gitHead": "0608f405573901e54db01e44c533009cf28be262"
74
+ "gitHead": "eb3ca4fb07ee31c62093f5fcec56575573c902ce"
78
75
  }
@@ -1,10 +0,0 @@
1
- export interface ExportResponseSuccess {
2
- status: 'success';
3
- data?: Uint8Array;
4
- }
5
- export interface ExportResponseFailure {
6
- status: 'failure';
7
- error: Error;
8
- }
9
- export declare type ExportResponse = ExportResponseSuccess | ExportResponseFailure;
10
- //# sourceMappingURL=export-response.d.ts.map
@@ -1,18 +0,0 @@
1
- "use strict";
2
- /*
3
- * Copyright The OpenTelemetry Authors
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * https://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
- Object.defineProperty(exports, "__esModule", { value: true });
18
- //# sourceMappingURL=export-response.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"export-response.js","sourceRoot":"","sources":["../../src/export-response.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface ExportResponseSuccess {\n status: 'success';\n data?: Uint8Array;\n}\n\nexport interface ExportResponseFailure {\n status: 'failure';\n error: Error;\n}\n\nexport type ExportResponse = ExportResponseSuccess | ExportResponseFailure;\n"]}
@@ -1,6 +0,0 @@
1
- import { ExportResponse } from './export-response';
2
- export interface IExporterTransport {
3
- send(data: Uint8Array): Promise<ExportResponse>;
4
- shutdown(): void;
5
- }
6
- //# sourceMappingURL=exporter-transport.d.ts.map
@@ -1,18 +0,0 @@
1
- "use strict";
2
- /*
3
- * Copyright The OpenTelemetry Authors
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * https://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
- Object.defineProperty(exports, "__esModule", { value: true });
18
- //# sourceMappingURL=exporter-transport.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"exporter-transport.js","sourceRoot":"","sources":["../../src/exporter-transport.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ExportResponse } from './export-response';\n\nexport interface IExporterTransport {\n send(data: Uint8Array): Promise<ExportResponse>;\n shutdown(): void;\n}\n"]}
@@ -1,11 +0,0 @@
1
- import { CompressionAlgorithm } from '@opentelemetry/otlp-exporter-base';
2
- import type { ChannelCredentials } from '@grpc/grpc-js';
3
- export declare const DEFAULT_COLLECTOR_URL = "http://localhost:4317";
4
- export declare function validateAndNormalizeUrl(url: string): string;
5
- export declare function configureCredentials(credentials: ChannelCredentials | undefined, endpoint: string): ChannelCredentials;
6
- /**
7
- * Exported for testing
8
- */
9
- export declare function getCredentialsFromEnvironment(): ChannelCredentials;
10
- export declare function configureCompression(compression: CompressionAlgorithm | undefined): CompressionAlgorithm;
11
- //# sourceMappingURL=util.d.ts.map
package/build/src/util.js DELETED
@@ -1,153 +0,0 @@
1
- "use strict";
2
- /*
3
- * Copyright The OpenTelemetry Authors
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * https://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
- Object.defineProperty(exports, "__esModule", { value: true });
18
- exports.configureCompression = exports.getCredentialsFromEnvironment = exports.configureCredentials = exports.validateAndNormalizeUrl = exports.DEFAULT_COLLECTOR_URL = void 0;
19
- const api_1 = require("@opentelemetry/api");
20
- const core_1 = require("@opentelemetry/core");
21
- const path = require("path");
22
- const url_1 = require("url");
23
- const fs = require("fs");
24
- const otlp_exporter_base_1 = require("@opentelemetry/otlp-exporter-base");
25
- const grpc_exporter_transport_1 = require("./grpc-exporter-transport");
26
- exports.DEFAULT_COLLECTOR_URL = 'http://localhost:4317';
27
- function validateAndNormalizeUrl(url) {
28
- var _a;
29
- const hasProtocol = url.match(/^([\w]{1,8}):\/\//);
30
- if (!hasProtocol) {
31
- url = `https://${url}`;
32
- }
33
- const target = new url_1.URL(url);
34
- if (target.protocol === 'unix:') {
35
- return url;
36
- }
37
- if (target.pathname && target.pathname !== '/') {
38
- api_1.diag.warn('URL path should not be set when using grpc, the path part of the URL will be ignored.');
39
- }
40
- if (target.protocol !== '' && !((_a = target.protocol) === null || _a === void 0 ? void 0 : _a.match(/^(http)s?:$/))) {
41
- api_1.diag.warn('URL protocol should be http(s)://. Using http://.');
42
- }
43
- return target.host;
44
- }
45
- exports.validateAndNormalizeUrl = validateAndNormalizeUrl;
46
- function configureCredentials(credentials, endpoint) {
47
- let insecure;
48
- if (credentials) {
49
- return credentials;
50
- }
51
- else if (endpoint.startsWith('https://')) {
52
- insecure = false;
53
- }
54
- else if (endpoint.startsWith('http://') ||
55
- endpoint === exports.DEFAULT_COLLECTOR_URL) {
56
- insecure = true;
57
- }
58
- else {
59
- insecure = getSecurityFromEnv();
60
- }
61
- if (insecure) {
62
- return (0, grpc_exporter_transport_1.createInsecureCredentials)();
63
- }
64
- else {
65
- return getCredentialsFromEnvironment();
66
- }
67
- }
68
- exports.configureCredentials = configureCredentials;
69
- function getSecurityFromEnv() {
70
- const definedInsecure = (0, core_1.getEnv)().OTEL_EXPORTER_OTLP_TRACES_INSECURE ||
71
- (0, core_1.getEnv)().OTEL_EXPORTER_OTLP_INSECURE;
72
- if (definedInsecure) {
73
- return definedInsecure.toLowerCase() === 'true';
74
- }
75
- else {
76
- return false;
77
- }
78
- }
79
- /**
80
- * Exported for testing
81
- */
82
- function getCredentialsFromEnvironment() {
83
- const rootCert = retrieveRootCert();
84
- const privateKey = retrievePrivateKey();
85
- const certChain = retrieveCertChain();
86
- return (0, grpc_exporter_transport_1.createSslCredentials)(rootCert, privateKey, certChain);
87
- }
88
- exports.getCredentialsFromEnvironment = getCredentialsFromEnvironment;
89
- function retrieveRootCert() {
90
- const rootCertificate = (0, core_1.getEnv)().OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE ||
91
- (0, core_1.getEnv)().OTEL_EXPORTER_OTLP_CERTIFICATE;
92
- if (rootCertificate) {
93
- try {
94
- return fs.readFileSync(path.resolve(process.cwd(), rootCertificate));
95
- }
96
- catch (_a) {
97
- api_1.diag.warn('Failed to read root certificate file');
98
- return undefined;
99
- }
100
- }
101
- else {
102
- return undefined;
103
- }
104
- }
105
- function retrievePrivateKey() {
106
- const clientKey = (0, core_1.getEnv)().OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY ||
107
- (0, core_1.getEnv)().OTEL_EXPORTER_OTLP_CLIENT_KEY;
108
- if (clientKey) {
109
- try {
110
- return fs.readFileSync(path.resolve(process.cwd(), clientKey));
111
- }
112
- catch (_a) {
113
- api_1.diag.warn('Failed to read client certificate private key file');
114
- return undefined;
115
- }
116
- }
117
- else {
118
- return undefined;
119
- }
120
- }
121
- function retrieveCertChain() {
122
- const clientChain = (0, core_1.getEnv)().OTEL_EXPORTER_OTLP_TRACES_CLIENT_CERTIFICATE ||
123
- (0, core_1.getEnv)().OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE;
124
- if (clientChain) {
125
- try {
126
- return fs.readFileSync(path.resolve(process.cwd(), clientChain));
127
- }
128
- catch (_a) {
129
- api_1.diag.warn('Failed to read client certificate chain file');
130
- return undefined;
131
- }
132
- }
133
- else {
134
- return undefined;
135
- }
136
- }
137
- function configureCompression(compression) {
138
- if (compression != null) {
139
- return compression;
140
- }
141
- const envCompression = (0, core_1.getEnv)().OTEL_EXPORTER_OTLP_TRACES_COMPRESSION ||
142
- (0, core_1.getEnv)().OTEL_EXPORTER_OTLP_COMPRESSION;
143
- if (envCompression === 'gzip') {
144
- return otlp_exporter_base_1.CompressionAlgorithm.GZIP;
145
- }
146
- else if (envCompression === 'none') {
147
- return otlp_exporter_base_1.CompressionAlgorithm.NONE;
148
- }
149
- api_1.diag.warn('Unknown compression "' + envCompression + '", falling back to "none"');
150
- return otlp_exporter_base_1.CompressionAlgorithm.NONE;
151
- }
152
- exports.configureCompression = configureCompression;
153
- //# sourceMappingURL=util.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"util.js","sourceRoot":"","sources":["../../src/util.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,4CAA0C;AAC1C,8CAA6C;AAC7C,6BAA6B;AAC7B,6BAA0B;AAC1B,yBAAyB;AACzB,0EAAyE;AACzE,uEAGmC;AAMtB,QAAA,qBAAqB,GAAG,uBAAuB,CAAC;AAE7D,SAAgB,uBAAuB,CAAC,GAAW;;IACjD,MAAM,WAAW,GAAG,GAAG,CAAC,KAAK,CAAC,mBAAmB,CAAC,CAAC;IACnD,IAAI,CAAC,WAAW,EAAE;QAChB,GAAG,GAAG,WAAW,GAAG,EAAE,CAAC;KACxB;IACD,MAAM,MAAM,GAAG,IAAI,SAAG,CAAC,GAAG,CAAC,CAAC;IAC5B,IAAI,MAAM,CAAC,QAAQ,KAAK,OAAO,EAAE;QAC/B,OAAO,GAAG,CAAC;KACZ;IACD,IAAI,MAAM,CAAC,QAAQ,IAAI,MAAM,CAAC,QAAQ,KAAK,GAAG,EAAE;QAC9C,UAAI,CAAC,IAAI,CACP,uFAAuF,CACxF,CAAC;KACH;IACD,IAAI,MAAM,CAAC,QAAQ,KAAK,EAAE,IAAI,CAAC,CAAA,MAAA,MAAM,CAAC,QAAQ,0CAAE,KAAK,CAAC,aAAa,CAAC,CAAA,EAAE;QACpE,UAAI,CAAC,IAAI,CAAC,mDAAmD,CAAC,CAAC;KAChE;IACD,OAAO,MAAM,CAAC,IAAI,CAAC;AACrB,CAAC;AAlBD,0DAkBC;AAED,SAAgB,o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aAAM,GAAE,CAAC,8BAA8B,CAAC;IAE1C,IAAI,cAAc,KAAK,MAAM,EAAE;QAC7B,OAAO,yCAAoB,CAAC,IAAI,CAAC;KAClC;SAAM,IAAI,cAAc,KAAK,MAAM,EAAE;QACpC,OAAO,yCAAoB,CAAC,IAAI,CAAC;KAClC;IAED,UAAI,CAAC,IAAI,CACP,uBAAuB,GAAG,cAAc,GAAG,2BAA2B,CACvE,CAAC;IACF,OAAO,yCAAoB,CAAC,IAAI,CAAC;AACnC,CAAC;AArBD,oDAqBC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { diag } from '@opentelemetry/api';\nimport { getEnv } from '@opentelemetry/core';\nimport * as path from 'path';\nimport { URL } from 'url';\nimport * as fs from 'fs';\nimport { CompressionAlgorithm } from '@opentelemetry/otlp-exporter-base';\nimport {\n createInsecureCredentials,\n createSslCredentials,\n} from './grpc-exporter-transport';\n\n// NOTE: do not change these type imports to actual imports. Doing so WILL break `@opentelemetry/instrumentation-http`,\n// as they'd be imported before the http/https modules can be wrapped.\nimport type { ChannelCredentials } from '@grpc/grpc-js';\n\nexport const DEFAULT_COLLECTOR_URL = 'http://localhost:4317';\n\nexport function validateAndNormalizeUrl(url: string): string {\n const hasProtocol = url.match(/^([\\w]{1,8}):\\/\\//);\n if (!hasProtocol) {\n url = `https://${url}`;\n }\n const target = new URL(url);\n if (target.protocol === 'unix:') {\n return url;\n }\n if (target.pathname && target.pathname !== '/') {\n diag.warn(\n 'URL path should not be set when using grpc, the path part of the URL will be ignored.'\n );\n }\n if (target.protocol !== '' && !target.protocol?.match(/^(http)s?:$/)) {\n diag.warn('URL protocol should be http(s)://. Using http://.');\n }\n return target.host;\n}\n\nexport function configureCredentials(\n credentials: ChannelCredentials | undefined,\n endpoint: string\n): ChannelCredentials {\n let insecure: boolean;\n\n if (credentials) {\n return credentials;\n } else if (endpoint.startsWith('https://')) {\n insecure = false;\n } else if (\n endpoint.startsWith('http://') ||\n endpoint === DEFAULT_COLLECTOR_URL\n ) {\n insecure = true;\n } else {\n insecure = getSecurityFromEnv();\n }\n\n if (insecure) {\n return createInsecureCredentials();\n } else {\n return getCredentialsFromEnvironment();\n }\n}\n\nfunction getSecurityFromEnv(): boolean {\n const definedInsecure =\n getEnv().OTEL_EXPORTER_OTLP_TRACES_INSECURE ||\n getEnv().OTEL_EXPORTER_OTLP_INSECURE;\n\n if (definedInsecure) {\n return definedInsecure.toLowerCase() === 'true';\n } else {\n return false;\n }\n}\n\n/**\n * Exported for testing\n */\nexport function getCredentialsFromEnvironment(): ChannelCredentials {\n const rootCert = retrieveRootCert();\n const privateKey = retrievePrivateKey();\n const certChain = retrieveCertChain();\n\n return createSslCredentials(rootCert, privateKey, certChain);\n}\n\nfunction retrieveRootCert(): Buffer | undefined {\n const rootCertificate =\n getEnv().OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE ||\n getEnv().OTEL_EXPORTER_OTLP_CERTIFICATE;\n\n if (rootCertificate) {\n try {\n return fs.readFileSync(path.resolve(process.cwd(), rootCertificate));\n } catch {\n diag.warn('Failed to read root certificate file');\n return undefined;\n }\n } else {\n return undefined;\n }\n}\n\nfunction retrievePrivateKey(): Buffer | undefined {\n const clientKey =\n getEnv().OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY ||\n getEnv().OTEL_EXPORTER_OTLP_CLIENT_KEY;\n\n if (clientKey) {\n try {\n return fs.readFileSync(path.resolve(process.cwd(), clientKey));\n } catch {\n diag.warn('Failed to read client certificate private key file');\n return undefined;\n }\n } else {\n return undefined;\n }\n}\n\nfunction retrieveCertChain(): Buffer | undefined {\n const clientChain =\n getEnv().OTEL_EXPORTER_OTLP_TRACES_CLIENT_CERTIFICATE ||\n getEnv().OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE;\n\n if (clientChain) {\n try {\n return fs.readFileSync(path.resolve(process.cwd(), clientChain));\n } catch {\n diag.warn('Failed to read client certificate chain file');\n return undefined;\n }\n } else {\n return undefined;\n }\n}\n\nexport function configureCompression(\n compression: CompressionAlgorithm | undefined\n): CompressionAlgorithm {\n if (compression != null) {\n return compression;\n }\n\n const envCompression =\n getEnv().OTEL_EXPORTER_OTLP_TRACES_COMPRESSION ||\n getEnv().OTEL_EXPORTER_OTLP_COMPRESSION;\n\n if (envCompression === 'gzip') {\n return CompressionAlgorithm.GZIP;\n } else if (envCompression === 'none') {\n return CompressionAlgorithm.NONE;\n }\n\n diag.warn(\n 'Unknown compression \"' + envCompression + '\", falling back to \"none\"'\n );\n return CompressionAlgorithm.NONE;\n}\n"]}