@opentelemetry/sdk-node 0.221.0 → 0.222.0-development.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.
@@ -4,7 +4,7 @@
4
4
  * SPDX-License-Identifier: Apache-2.0
5
5
  */
6
6
  Object.defineProperty(exports, "__esModule", { value: true });
7
- exports.createSpanLimitsFromConfig = exports.createLoggerProviderFromConfig = exports.createLogRecordProcessorFromConfig = exports.createLogRecordExporterFromConfig = exports.createLogRecordLimitsFromConfig = void 0;
7
+ exports.createTracerProviderFromConfig = exports.createIdGeneratorFromConfig = exports.createSamplerFromConfig = exports.createMeterProviderFromConfig = exports.createPushMetricExporterFromConfig = exports.createSpanLimitsFromConfig = exports.createLoggerProviderFromConfig = exports.createLogRecordProcessorFromConfig = exports.createLogRecordExporterFromConfig = exports.createLogRecordLimitsFromConfig = exports.createResourceFromConfig = exports.createPropagatorFromConfig = void 0;
8
8
  /**
9
9
  * Create SDK components from parsed declarative config.
10
10
  * https://opentelemetry.io/docs/specs/otel/configuration/sdk/#create
@@ -13,14 +13,44 @@ exports.createSpanLimitsFromConfig = exports.createLoggerProviderFromConfig = ex
13
13
  * This file exports `create<SDK Thing>FromConfig(...)` functions intended to
14
14
  * be used by the "create" step of `startNodeSDK()`.
15
15
  */
16
+ const util_1 = require("util");
17
+ const fs_1 = require("fs");
18
+ const path = require("path");
16
19
  const api_1 = require("@opentelemetry/api");
20
+ const sdk_trace_1 = require("@opentelemetry/sdk-trace");
21
+ const resources_1 = require("@opentelemetry/resources");
17
22
  const exporter_logs_otlp_http_1 = require("@opentelemetry/exporter-logs-otlp-http");
18
23
  const exporter_logs_otlp_grpc_1 = require("@opentelemetry/exporter-logs-otlp-grpc");
19
24
  const exporter_logs_otlp_proto_1 = require("@opentelemetry/exporter-logs-otlp-proto");
25
+ const exporter_metrics_otlp_grpc_1 = require("@opentelemetry/exporter-metrics-otlp-grpc");
26
+ const exporter_metrics_otlp_http_1 = require("@opentelemetry/exporter-metrics-otlp-http");
27
+ const exporter_metrics_otlp_proto_1 = require("@opentelemetry/exporter-metrics-otlp-proto");
28
+ const exporter_trace_otlp_proto_1 = require("@opentelemetry/exporter-trace-otlp-proto");
29
+ const exporter_trace_otlp_http_1 = require("@opentelemetry/exporter-trace-otlp-http");
30
+ const exporter_trace_otlp_grpc_1 = require("@opentelemetry/exporter-trace-otlp-grpc");
20
31
  const otlp_exporter_base_1 = require("@opentelemetry/otlp-exporter-base");
32
+ const otlp_grpc_exporter_base_1 = require("@opentelemetry/otlp-grpc-exporter-base");
33
+ const exporter_metrics_otlp_http_2 = require("@opentelemetry/exporter-metrics-otlp-http");
34
+ const configuration_1 = require("@opentelemetry/configuration");
21
35
  const sdk_logs_1 = require("@opentelemetry/sdk-logs");
22
- const utils_1 = require("./utils");
36
+ const propagator_jaeger_1 = require("@opentelemetry/propagator-jaeger");
37
+ const propagator_b3_1 = require("@opentelemetry/propagator-b3");
38
+ const core_1 = require("@opentelemetry/core");
39
+ const sdk_metrics_1 = require("@opentelemetry/sdk-metrics");
40
+ const exporter_prometheus_1 = require("@opentelemetry/exporter-prometheus");
41
+ const semantic_conventions_1 = require("@opentelemetry/semantic-conventions");
23
42
  // ---- internal utilities
43
+ function getGrpcMetadataFromHeaders(headers, headersList) {
44
+ const headerValues = (0, configuration_1.mergeHeadersConfig)(headers, headersList);
45
+ if (!headerValues || Object.keys(headerValues).length === 0) {
46
+ return undefined;
47
+ }
48
+ const metadata = (0, otlp_grpc_exporter_base_1.createEmptyMetadata)();
49
+ for (const [name, value] of Object.entries(headerValues)) {
50
+ metadata.set(name, value);
51
+ }
52
+ return metadata;
53
+ }
24
54
  /**
25
55
  * Warn if some props from a declarative config object have not been handled.
26
56
  *
@@ -64,11 +94,261 @@ function mustSingleEntry(configObj, configTypeName) {
64
94
  const entries = Object.entries(configObj).filter(([_name, properties]) => properties !== undefined);
65
95
  if (entries.length !== 1) {
66
96
  const entryNames = entries.map(e => e[0]);
67
- throw Error(`invalid ${configTypeName} in configuration: must have exactly one entry: entries=${JSON.stringify(entryNames)}`);
97
+ throw new Error(`invalid ${configTypeName} in configuration: must have exactly one entry: entries=${JSON.stringify(entryNames)}`);
68
98
  }
69
99
  return entries[0];
70
100
  }
101
+ function loadTlsConfigFile(absPath, propName) {
102
+ try {
103
+ if (!path.isAbsolute(absPath)) {
104
+ throw new Error(`TLS config file "${absPath}" must be an absolute path`);
105
+ }
106
+ return (0, fs_1.readFileSync)(absPath);
107
+ }
108
+ catch (err) {
109
+ throw new Error(`could not load "tls.${propName}" from config: ${err.message}`, { cause: err });
110
+ }
111
+ }
112
+ /**
113
+ * Get TLS-related HTTP client options from declarative configuration.
114
+ * https://opentelemetry.io/docs/specs/otel-config/types/#type-httptls
115
+ * https://nodejs.org/api/tls.html#tlscreatesecurecontextoptions
116
+ */
117
+ function httpTlsOptionsFromConfig(tls) {
118
+ if (!tls) {
119
+ return undefined;
120
+ }
121
+ checkConfigUse('HttpTls', tls, ['ca_file', 'cert_file', 'key_file']);
122
+ const httpTlsOptions = {};
123
+ if (tls.ca_file) {
124
+ httpTlsOptions.ca = loadTlsConfigFile(tls.ca_file, 'ca_file');
125
+ }
126
+ if (tls.cert_file) {
127
+ httpTlsOptions.cert = loadTlsConfigFile(tls.cert_file, 'cert_file');
128
+ }
129
+ if (tls.key_file) {
130
+ httpTlsOptions.key = loadTlsConfigFile(tls.key_file, 'key_file');
131
+ }
132
+ return httpTlsOptions;
133
+ }
134
+ function grpcCredentialsFromConfig(tls) {
135
+ if (!tls) {
136
+ return undefined;
137
+ }
138
+ checkConfigUse('GrpcTls', tls, [
139
+ 'insecure',
140
+ 'ca_file',
141
+ 'cert_file',
142
+ 'key_file',
143
+ ]);
144
+ if (tls?.insecure) {
145
+ return (0, otlp_grpc_exporter_base_1.createInsecureCredentials)();
146
+ }
147
+ const rootCert = tls.ca_file
148
+ ? loadTlsConfigFile(tls.ca_file, 'ca_file')
149
+ : undefined;
150
+ const privateKey = tls.key_file
151
+ ? loadTlsConfigFile(tls.key_file, 'key_file')
152
+ : undefined;
153
+ const certChain = tls.cert_file
154
+ ? loadTlsConfigFile(tls.cert_file, 'cert_file')
155
+ : undefined;
156
+ if (rootCert || privateKey || certChain) {
157
+ return (0, otlp_grpc_exporter_base_1.createSslCredentials)(rootCert, privateKey, certChain);
158
+ }
159
+ return undefined;
160
+ }
161
+ /**
162
+ * Validate an export(er) timeout value.
163
+ * "timeout" properties in the declarative config schema are typically
164
+ * described with:
165
+ *
166
+ * 1. Value must be non-negative.
167
+ * 2. A value of 0 indicates no limit (infinity).
168
+ *
169
+ * Search "timeout" at https://opentelemetry.io/docs/specs/otel-config/types/
170
+ *
171
+ * This function enforces (1), and guards against (2) because current OTel
172
+ * JS SDK components do *not* handle a `0` timeout value.
173
+ * See https://github.com/open-telemetry/opentelemetry-js/issues/6617
174
+ */
175
+ function validateExportTimeoutConfig(timeout, errLabel) {
176
+ if (timeout == null) {
177
+ return undefined;
178
+ }
179
+ else if (timeout < 0) {
180
+ throw new Error(`${errLabel} value must be non-negative: ${timeout}`);
181
+ }
182
+ else if (timeout === 0) {
183
+ throw new Error(`${errLabel} of 0 (infinite) is not supported`);
184
+ }
185
+ return timeout;
186
+ }
71
187
  // ---- create<SDKThing>FromConfig functions
188
+ function createPropagatorFromConfig(propagatorConfig) {
189
+ const configComposite = (0, configuration_1.mergePropagatorCompositeConfig)(propagatorConfig.composite, propagatorConfig.composite_list);
190
+ if (!configComposite) {
191
+ return undefined;
192
+ }
193
+ // TextMapPropagator config items are objects with a single key (the name).
194
+ // Transform this into a more convenient `(name, value)` 2-tuple.
195
+ //
196
+ // As well, guard against two cases where the TypeScript type
197
+ // `TextMapPropagatorConfigModel` does not exactly represent the JSON schema:
198
+ // 1. `"minProperties": 1, "maxProperties": 1,`
199
+ // 2. The type allows keys with an `undefined` value, but the JSON schema
200
+ // does not.
201
+ const kvFromItem = (item) => {
202
+ const keys = [];
203
+ let value = undefined;
204
+ for (const key of Object.keys(item)) {
205
+ value = item[key];
206
+ if (value === undefined) {
207
+ continue;
208
+ }
209
+ keys.push(key);
210
+ }
211
+ if (keys.length !== 1) {
212
+ throw new Error(`invalid "propagator" entry in configuration, there must be exactly one key (with a non-undefined value): ${(0, util_1.inspect)(item)}`);
213
+ }
214
+ return [keys[0], value];
215
+ };
216
+ // First pass: handle 'none', remove dupes.
217
+ const names = new Set();
218
+ const kvs = [];
219
+ for (const item of configComposite) {
220
+ const kv = kvFromItem(item);
221
+ const k = kv[0];
222
+ if (names.has(k)) {
223
+ continue;
224
+ }
225
+ names.add(k);
226
+ kvs.push(kv);
227
+ if (k === 'none') {
228
+ return undefined;
229
+ }
230
+ }
231
+ // Implementation note: this only contains specification required propagators that are actually hosted in this repo.
232
+ // Any other propagators (like aws, aws-lambda, should go into `@opentelemetry/auto-configuration-propagators` instead).
233
+ const propagatorsFactory = new Map([
234
+ ['tracecontext', () => new core_1.W3CTraceContextPropagator()],
235
+ ['baggage', () => new core_1.W3CBaggagePropagator()],
236
+ ['b3', () => new propagator_b3_1.B3Propagator()],
237
+ [
238
+ 'b3multi',
239
+ () => new propagator_b3_1.B3Propagator({ injectEncoding: propagator_b3_1.B3InjectEncoding.MULTI_HEADER }),
240
+ ],
241
+ [
242
+ 'jaeger',
243
+ () => {
244
+ api_1.diag.warn('The Jaeger propagator is deprecated and will be removed in a future release. Use the W3C TraceContext propagator ("tracecontext") instead.');
245
+ return new propagator_jaeger_1.JaegerPropagator();
246
+ },
247
+ ],
248
+ ]);
249
+ const propagators = [];
250
+ for (const [name] of kvs) {
251
+ const propagator = propagatorsFactory.get(name)?.();
252
+ if (!propagator) {
253
+ throw new Error(`unknown TextMapPropagator in configuration: "${name}"`);
254
+ }
255
+ propagators.push(propagator);
256
+ }
257
+ if (propagators.length === 0) {
258
+ return undefined;
259
+ }
260
+ else {
261
+ // Always wrap in a composite propagator, even for the rare case of a single
262
+ // propagator, because `/propagator/composite` in the configuration schema
263
+ // says "Configure the propagators in the composite text map propagator".
264
+ return new core_1.CompositePropagator({ propagators });
265
+ }
266
+ }
267
+ exports.createPropagatorFromConfig = createPropagatorFromConfig;
268
+ class ServiceNameDetector {
269
+ detect() {
270
+ const attributes = {};
271
+ const serviceName = (0, core_1.getStringFromEnv)('OTEL_SERVICE_NAME');
272
+ if (serviceName) {
273
+ attributes[semantic_conventions_1.ATTR_SERVICE_NAME] = serviceName;
274
+ }
275
+ return { attributes };
276
+ }
277
+ }
278
+ const serviceNameDetector = new ServiceNameDetector();
279
+ function createResourceFromConfig(resourceConfig) {
280
+ // Limitation: Resource#merge() is the only exported mechanism from the
281
+ // resources package that supports *async* attributes, so we must use it.
282
+ // However, if `schemaUrl` is being used by detectors and in the config, then
283
+ // `.merge()` will potentially warn and drop the schema URL if there is a
284
+ // conflict. (See `mergeSchemaUrl` behaviour.) This is likely not the
285
+ // intended behavior when a user specifies a `schema_url` in the declarative
286
+ // config file.
287
+ checkConfigUse('Resource', resourceConfig, [
288
+ 'attributes',
289
+ 'attributes_list',
290
+ 'schema_url',
291
+ 'detection/development',
292
+ ]);
293
+ let resource = (0, resources_1.defaultResource)();
294
+ if (!resourceConfig) {
295
+ return resource;
296
+ }
297
+ if (resourceConfig['detection/development']) {
298
+ // TODO(6986): support attributes.{include,exclude}; `resources` package doesn't currently support this
299
+ checkConfigUse('ExperimentalResourceDetection', resourceConfig['detection/development'], ['detectors']);
300
+ if (resourceConfig['detection/development'].detectors) {
301
+ const detectors = [];
302
+ for (const d of resourceConfig['detection/development'].detectors) {
303
+ const [name] = mustSingleEntry(d, 'ExperimentalResourceDetector');
304
+ // https://opentelemetry.io/docs/specs/otel-config/types/#type-experimentalresourcedetector
305
+ switch (name) {
306
+ // Note: The 'container' detector defined in the schema cannot yet
307
+ // be supported because a container resource detector lives in the
308
+ // separate opentelemetry-js-contrib.git repo. Supporting 'container'
309
+ // will come as part of supporting PluginComponentProvider.
310
+ case 'host':
311
+ detectors.push(resources_1.hostDetector);
312
+ detectors.push(resources_1.osDetector);
313
+ break;
314
+ case 'process':
315
+ detectors.push(resources_1.processDetector);
316
+ break;
317
+ case 'service':
318
+ // Note: The declarative schema defines the 'service' detector to
319
+ // handle `service.instance.id` and the `OTEL_SERVICE_NAME` envvar.
320
+ // https://opentelemetry.io/docs/specs/otel-config/types/#type-experimentalresourcedetector
321
+ // This is equivalent to the `serviceInstanceIdDetector` and
322
+ // *part* of the `envDetector`. Using this `envDetector` would
323
+ // incorrectly read the `OTEL_RESOURCE_ATTRIBUTES` envvar.
324
+ detectors.push(serviceNameDetector);
325
+ detectors.push(resources_1.serviceInstanceIdDetector);
326
+ break;
327
+ default:
328
+ throw new Error(`unknown ExperimentalResourceDetector name in configuration: "${name}"`);
329
+ }
330
+ }
331
+ if (detectors.length > 0) {
332
+ resource = resource.merge((0, resources_1.detectResources)({ detectors }));
333
+ }
334
+ }
335
+ }
336
+ const configAttrs = (0, configuration_1.mergeResourceAttributesConfig)(resourceConfig.attributes, resourceConfig.attributes_list);
337
+ if (configAttrs && configAttrs.length > 0) {
338
+ const attrs = {};
339
+ for (const a of configAttrs) {
340
+ if (a.value !== null) {
341
+ attrs[a.name] = a.value;
342
+ }
343
+ }
344
+ resource = resource.merge((0, resources_1.resourceFromAttributes)(attrs));
345
+ }
346
+ if (resourceConfig.schema_url) {
347
+ resource = resource.merge((0, resources_1.resourceFromAttributes)({}, { schemaUrl: resourceConfig.schema_url }));
348
+ }
349
+ return resource;
350
+ }
351
+ exports.createResourceFromConfig = createResourceFromConfig;
72
352
  function createLogRecordLimitsFromConfig(limits, attribute_limits) {
73
353
  if (!limits && !attribute_limits) {
74
354
  return undefined;
@@ -87,10 +367,11 @@ function createLogRecordExporterFromConfig(exporter) {
87
367
  const [name, properties] = mustSingleEntry(exporter, 'LogRecordExporter');
88
368
  switch (name) {
89
369
  case 'otlp_http': {
90
- checkConfigUse('LogRecordExporter', properties, [
370
+ checkConfigUse('OtlpHttpExporter', properties, [
91
371
  'compression',
92
372
  'endpoint',
93
373
  'headers',
374
+ 'headers_list',
94
375
  'timeout',
95
376
  'tls',
96
377
  'encoding',
@@ -101,9 +382,9 @@ function createLogRecordExporterFromConfig(exporter) {
101
382
  ? otlp_exporter_base_1.CompressionAlgorithm.GZIP
102
383
  : otlp_exporter_base_1.CompressionAlgorithm.NONE,
103
384
  url: props?.endpoint ?? undefined,
104
- headers: (0, utils_1.getHeadersFromConfiguration)(props?.headers),
105
- timeoutMillis: (0, utils_1.validateExporterTimeout)(props?.timeout),
106
- httpAgentOptions: (0, utils_1.getHttpAgentOptionsFromTls)(props?.tls),
385
+ headers: (0, configuration_1.mergeHeadersConfig)(props?.headers, props?.headers_list),
386
+ timeoutMillis: validateExportTimeoutConfig(props?.timeout, 'OtlpHttpExporter.timeout'),
387
+ httpAgentOptions: httpTlsOptionsFromConfig(props?.tls),
107
388
  };
108
389
  const encoding = props?.encoding ?? 'protobuf';
109
390
  switch (encoding) {
@@ -116,12 +397,13 @@ function createLogRecordExporterFromConfig(exporter) {
116
397
  }
117
398
  }
118
399
  case 'otlp_grpc': {
119
- checkConfigUse('LogRecordExporter', properties, [
400
+ checkConfigUse('OtlpGrpcExporter', properties, [
120
401
  'compression',
121
402
  'endpoint',
122
403
  'timeout',
123
404
  'tls',
124
405
  'headers',
406
+ 'headers_list',
125
407
  ]);
126
408
  const props = properties;
127
409
  return new exporter_logs_otlp_grpc_1.OTLPLogExporter({
@@ -129,9 +411,9 @@ function createLogRecordExporterFromConfig(exporter) {
129
411
  ? otlp_exporter_base_1.CompressionAlgorithm.GZIP
130
412
  : otlp_exporter_base_1.CompressionAlgorithm.NONE,
131
413
  url: props?.endpoint ?? undefined,
132
- timeoutMillis: (0, utils_1.validateExporterTimeout)(props?.timeout),
133
- credentials: (0, utils_1.getGrpcCredentialsFromTls)(props?.tls),
134
- metadata: (0, utils_1.getGrpcMetadataFromHeaders)(props?.headers),
414
+ timeoutMillis: validateExportTimeoutConfig(props?.timeout, 'OtlpGrpcExporter.timeout'),
415
+ credentials: grpcCredentialsFromConfig(props?.tls),
416
+ metadata: getGrpcMetadataFromHeaders(props?.headers, props?.headers_list),
135
417
  });
136
418
  }
137
419
  case 'console':
@@ -159,7 +441,7 @@ function createLogRecordProcessorFromConfig(processor) {
159
441
  maxQueueSize: props.max_queue_size ?? undefined,
160
442
  maxExportBatchSize: props.max_export_batch_size ?? undefined,
161
443
  scheduledDelayMillis: props.schedule_delay ?? undefined,
162
- exportTimeoutMillis: props.export_timeout ?? undefined,
444
+ exportTimeoutMillis: validateExportTimeoutConfig(props.export_timeout, 'BatchLogRecordProcessor.export_timeout'),
163
445
  });
164
446
  }
165
447
  case 'simple': {
@@ -186,6 +468,7 @@ function createLoggerProviderFromConfig(resource, logger_provider, attribute_lim
186
468
  });
187
469
  }
188
470
  exports.createLoggerProviderFromConfig = createLoggerProviderFromConfig;
471
+ // Exported for testing.
189
472
  function createSpanLimitsFromConfig(limits, attribute_limits) {
190
473
  if (!limits && !attribute_limits) {
191
474
  return undefined;
@@ -204,4 +487,550 @@ function createSpanLimitsFromConfig(limits, attribute_limits) {
204
487
  };
205
488
  }
206
489
  exports.createSpanLimitsFromConfig = createSpanLimitsFromConfig;
490
+ /**
491
+ * Map a declarative-config `temporality_preference` value to the enum the OTLP
492
+ * metric exporters expect. Returns undefined for an unspecified preference so
493
+ * the exporter falls back to its own default (cumulative).
494
+ */
495
+ function aggregationTemporalityPreferenceFromConfig(temporality_preference) {
496
+ if (temporality_preference == null) {
497
+ return undefined;
498
+ }
499
+ switch (temporality_preference) {
500
+ case 'delta':
501
+ return exporter_metrics_otlp_http_2.AggregationTemporalityPreference.DELTA;
502
+ case 'low_memory':
503
+ return exporter_metrics_otlp_http_2.AggregationTemporalityPreference.LOWMEMORY;
504
+ case 'cumulative':
505
+ return exporter_metrics_otlp_http_2.AggregationTemporalityPreference.CUMULATIVE;
506
+ default:
507
+ throw new Error(`unknown temporality_preference value in configuration: ${temporality_preference}`);
508
+ }
509
+ }
510
+ /**
511
+ * Map a declarative-config `default_histogram_aggregation` value to an
512
+ * AggregationSelector that applies the requested aggregation to histogram
513
+ * instruments and leaves all other instrument types at their default. Returns
514
+ * undefined for an unspecified value so the exporter uses its own default.
515
+ */
516
+ function aggregationSelectorFromConfig(default_histogram_aggregation) {
517
+ if (default_histogram_aggregation == null) {
518
+ return undefined;
519
+ }
520
+ let histoAggOpt;
521
+ switch (default_histogram_aggregation) {
522
+ case 'base2_exponential_bucket_histogram':
523
+ histoAggOpt = { type: sdk_metrics_1.AggregationType.EXPONENTIAL_HISTOGRAM };
524
+ break;
525
+ case 'explicit_bucket_histogram':
526
+ histoAggOpt = { type: sdk_metrics_1.AggregationType.EXPLICIT_BUCKET_HISTOGRAM };
527
+ break;
528
+ default:
529
+ throw new Error(`unknown default_histogram_aggregation value in configuration: ${default_histogram_aggregation}`);
530
+ }
531
+ return (instrumentType) => instrumentType === sdk_metrics_1.InstrumentType.HISTOGRAM
532
+ ? histoAggOpt
533
+ : { type: sdk_metrics_1.AggregationType.DEFAULT };
534
+ }
535
+ /** exported for testing */
536
+ function createPushMetricExporterFromConfig(exporter) {
537
+ const [name, properties] = mustSingleEntry(exporter, 'PushMetricExporter');
538
+ // TODO(6959): use non-envvar reading mechanism to create OTLP exporters, so an `undefined` option does NOT fallback to an envvar
539
+ switch (name) {
540
+ case 'otlp_http': {
541
+ checkConfigUse('PushMetricExporter', properties, [
542
+ 'compression',
543
+ 'endpoint',
544
+ 'headers',
545
+ 'headers_list',
546
+ 'timeout',
547
+ 'tls',
548
+ 'temporality_preference',
549
+ 'default_histogram_aggregation',
550
+ 'encoding',
551
+ ]);
552
+ const props = properties;
553
+ const commonOpts = {
554
+ compression: props?.compression === 'gzip'
555
+ ? otlp_exporter_base_1.CompressionAlgorithm.GZIP
556
+ : otlp_exporter_base_1.CompressionAlgorithm.NONE,
557
+ url: props?.endpoint ?? undefined,
558
+ headers: (0, configuration_1.mergeHeadersConfig)(props?.headers, props?.headers_list),
559
+ timeoutMillis: validateExportTimeoutConfig(props?.timeout, 'PushMetricExporter.timeout'),
560
+ httpAgentOptions: httpTlsOptionsFromConfig(props?.tls),
561
+ temporalityPreference: aggregationTemporalityPreferenceFromConfig(props?.temporality_preference),
562
+ aggregationPreference: aggregationSelectorFromConfig(props?.default_histogram_aggregation),
563
+ };
564
+ const encoding = props?.encoding ?? 'protobuf';
565
+ switch (encoding) {
566
+ case 'json':
567
+ return new exporter_metrics_otlp_http_1.OTLPMetricExporter(commonOpts);
568
+ case 'protobuf':
569
+ return new exporter_metrics_otlp_proto_1.OTLPMetricExporter(commonOpts);
570
+ default:
571
+ throw new Error(`unknown OtlpHttpMetricExporter encoding in configuration: "${encoding}"`);
572
+ }
573
+ }
574
+ case 'otlp_grpc': {
575
+ checkConfigUse('PushMetricExporter', properties, [
576
+ 'compression',
577
+ 'endpoint',
578
+ 'timeout',
579
+ 'tls',
580
+ 'headers',
581
+ 'headers_list',
582
+ 'temporality_preference',
583
+ 'default_histogram_aggregation',
584
+ ]);
585
+ const props = properties;
586
+ return new exporter_metrics_otlp_grpc_1.OTLPMetricExporter({
587
+ compression: props?.compression === 'gzip'
588
+ ? otlp_exporter_base_1.CompressionAlgorithm.GZIP
589
+ : otlp_exporter_base_1.CompressionAlgorithm.NONE,
590
+ url: props?.endpoint ?? undefined,
591
+ timeoutMillis: validateExportTimeoutConfig(props?.timeout, 'PushMetricExporter.timeout'),
592
+ credentials: grpcCredentialsFromConfig(props?.tls),
593
+ metadata: getGrpcMetadataFromHeaders(props?.headers, props?.headers_list),
594
+ temporalityPreference: aggregationTemporalityPreferenceFromConfig(props?.temporality_preference),
595
+ aggregationPreference: aggregationSelectorFromConfig(props?.default_histogram_aggregation),
596
+ });
597
+ }
598
+ case 'console': {
599
+ // TODO(6957): temporality_preference
600
+ // TODO(6957): default_histogram_aggregation
601
+ checkConfigUse('PushMetricExporter', properties, []);
602
+ return new sdk_metrics_1.ConsoleMetricExporter();
603
+ }
604
+ default:
605
+ throw new Error(`unknown PushMetricExporter name in configuration: "${name}"`);
606
+ }
607
+ }
608
+ exports.createPushMetricExporterFromConfig = createPushMetricExporterFromConfig;
609
+ function createMetricProducerFromConfig(producer) {
610
+ const [name] = mustSingleEntry(producer, 'MetricProducer');
611
+ switch (name) {
612
+ case 'opencensus': {
613
+ // Note: The "opencensus" MetricProducer is intentionally not supported.
614
+ // It is deprecated in OpenTelemetry Configuration v1.2.0.
615
+ throw new Error('the "opencensus" MetricProducer is deprecated and not supported');
616
+ }
617
+ default:
618
+ throw new Error(`unknown MetricProducer name: "${name}"`);
619
+ }
620
+ }
621
+ function createPeriodicMetricReaderFromConfig(periodic) {
622
+ const exporter = createPushMetricExporterFromConfig(periodic.exporter);
623
+ const metricProducers = periodic.producers?.map(createMetricProducerFromConfig);
624
+ checkConfigUse('PeriodicMetricReader', periodic, [
625
+ 'exporter',
626
+ 'producers',
627
+ 'interval',
628
+ 'timeout',
629
+ 'max_export_batch_size/development',
630
+ ]);
631
+ // TODO(6425): add cardinality_limits
632
+ return new sdk_metrics_1.PeriodicExportingMetricReader({
633
+ exportIntervalMillis: periodic.interval ?? 60000,
634
+ exportTimeoutMillis: validateExportTimeoutConfig(periodic?.timeout, 'PeriodicExportingMetricReader.timeout') ?? 30000,
635
+ exporter,
636
+ metricProducers,
637
+ maxExportBatchSize: periodic['max_export_batch_size/development'] ?? undefined,
638
+ });
639
+ }
640
+ function createPullMetricReaderFromConfig(pull) {
641
+ // TODO(6425): add cardinality_limits
642
+ checkConfigUse('PullMetricReader', pull, ['exporter', 'producers']);
643
+ const metricProducers = pull.producers?.map(createMetricProducerFromConfig);
644
+ // The declarative config models a `pull` MetricReader as an object that takes
645
+ // an exporter, e.g.:
646
+ // meter_provider:
647
+ // readers:
648
+ // - pull:
649
+ // exporter:
650
+ // prometheus/development: ... # (A)
651
+ // # (B)
652
+ // producers: ...
653
+ // cardinality_limits: ...
654
+ // but the exporter (or at least the only current one, PrometheusExporter)
655
+ // *is* a MetricReader, and takes configuration from (A) and (B).
656
+ // export class PrometheusExporter extends MetricReader { ... }
657
+ const [name, properties] = mustSingleEntry(pull.exporter, 'PullMetricExporter');
658
+ switch (name) {
659
+ case 'prometheus/development': {
660
+ // TODO(6653): 'translation_strategy' with #6653 or separately
661
+ // TODO(6605): 'resource_constant_labels' map to `withResourceConstantLabels` regex
662
+ checkConfigUse('ExperimentalPrometheusMetricExporterConfigModel', properties, [
663
+ 'host',
664
+ 'port',
665
+ 'scope_info_enabled',
666
+ 'target_info_enabled/development',
667
+ ]);
668
+ const props = properties;
669
+ return new exporter_prometheus_1.PrometheusExporter({
670
+ // TODO(6605): default host to `undefined` when PrometheusExporter defaults to 'localhost'
671
+ host: props?.host ?? 'localhost',
672
+ // TODO(6958): default port and host to `undefined` when PrometheusExporter constructor no longer reads envvars for config
673
+ port: props?.port ?? 9464,
674
+ withoutScopeInfo: props?.scope_info_enabled != null
675
+ ? !props.scope_info_enabled
676
+ : undefined,
677
+ withoutTargetInfo: props?.['target_info_enabled/development'] != null
678
+ ? !props['target_info_enabled/development']
679
+ : undefined,
680
+ metricProducers,
681
+ // Note: The following are not configurable via declarative config.
682
+ // This isn't necessarily an issue.
683
+ // - prefix
684
+ // - appendTimestamp
685
+ // - endpoint
686
+ // - preventServerStart
687
+ // - callback (second arg)
688
+ });
689
+ }
690
+ default:
691
+ throw new Error(`unknown PullMetricReader name in configuration: "${name}"`);
692
+ }
693
+ }
694
+ function createMetricReaderFromConfig(reader) {
695
+ const [name, properties] = mustSingleEntry(reader, 'MetricReader');
696
+ switch (name) {
697
+ case 'periodic':
698
+ return createPeriodicMetricReaderFromConfig(properties);
699
+ case 'pull':
700
+ return createPullMetricReaderFromConfig(properties);
701
+ default:
702
+ throw new Error(`unknown MetricReader type in configuration: "${Object.keys(reader)[0]}"`);
703
+ }
704
+ }
705
+ function instrumentTypeFromConfig(instrument_type) {
706
+ switch (instrument_type) {
707
+ case 'counter':
708
+ return sdk_metrics_1.InstrumentType.COUNTER;
709
+ case 'gauge':
710
+ return sdk_metrics_1.InstrumentType.GAUGE;
711
+ case 'histogram':
712
+ return sdk_metrics_1.InstrumentType.HISTOGRAM;
713
+ case 'observable_counter':
714
+ return sdk_metrics_1.InstrumentType.OBSERVABLE_COUNTER;
715
+ case 'observable_gauge':
716
+ return sdk_metrics_1.InstrumentType.OBSERVABLE_GAUGE;
717
+ case 'observable_up_down_counter':
718
+ return sdk_metrics_1.InstrumentType.OBSERVABLE_UP_DOWN_COUNTER;
719
+ case 'up_down_counter':
720
+ return sdk_metrics_1.InstrumentType.UP_DOWN_COUNTER;
721
+ default:
722
+ throw new Error(`unknown InstrumentType: ${instrument_type}`);
723
+ }
724
+ }
725
+ function createAggregationOptionFromConfig(aggregation) {
726
+ const [name, properties] = mustSingleEntry(aggregation, 'Aggregation');
727
+ switch (name) {
728
+ case 'default':
729
+ return {
730
+ type: sdk_metrics_1.AggregationType.DEFAULT,
731
+ };
732
+ case 'drop':
733
+ return {
734
+ type: sdk_metrics_1.AggregationType.DROP,
735
+ };
736
+ case 'explicit_bucket_histogram': {
737
+ checkConfigUse('ExplicitBucketHistogramAggregation', properties, [
738
+ 'record_min_max',
739
+ 'boundaries',
740
+ ]);
741
+ const props = properties;
742
+ return {
743
+ type: sdk_metrics_1.AggregationType.EXPLICIT_BUCKET_HISTOGRAM,
744
+ options: {
745
+ recordMinMax: props?.record_min_max ?? true,
746
+ boundaries: props?.boundaries ?? [
747
+ 0, 5, 10, 25, 50, 75, 100, 250, 500, 750, 1000, 2500, 5000, 7500,
748
+ 10000,
749
+ ],
750
+ },
751
+ };
752
+ }
753
+ case 'base2_exponential_bucket_histogram': {
754
+ // TODO(3841): max_scale property
755
+ checkConfigUse('Base2ExponentialBucketHistogramAggregation', properties, ['record_min_max', 'max_size']);
756
+ const props = properties;
757
+ return {
758
+ type: sdk_metrics_1.AggregationType.EXPONENTIAL_HISTOGRAM,
759
+ options: {
760
+ recordMinMax: props?.record_min_max ?? undefined,
761
+ maxSize: props?.max_size ?? undefined,
762
+ },
763
+ };
764
+ }
765
+ case 'last_value':
766
+ return {
767
+ type: sdk_metrics_1.AggregationType.LAST_VALUE,
768
+ };
769
+ case 'sum':
770
+ return {
771
+ type: sdk_metrics_1.AggregationType.SUM,
772
+ };
773
+ default:
774
+ throw new Error(`unknown Aggregation name in configuration: "${name}"`);
775
+ }
776
+ }
777
+ function createViewOptionsFromConfig(view) {
778
+ const viewOptions = {};
779
+ checkConfigUse('View', view, ['selector', 'stream']);
780
+ checkConfigUse('ViewSelector', view.selector, [
781
+ 'instrument_name',
782
+ 'instrument_type',
783
+ 'unit',
784
+ 'meter_name',
785
+ 'meter_version',
786
+ 'meter_schema_url',
787
+ ]);
788
+ if (view.selector.instrument_name) {
789
+ viewOptions.instrumentName = view.selector.instrument_name;
790
+ }
791
+ if (view.selector.instrument_type) {
792
+ viewOptions.instrumentType = instrumentTypeFromConfig(view.selector.instrument_type);
793
+ }
794
+ if (view.selector.unit) {
795
+ viewOptions.instrumentUnit = view.selector.unit;
796
+ }
797
+ if (view.selector.meter_name) {
798
+ viewOptions.meterName = view.selector.meter_name;
799
+ }
800
+ if (view.selector.meter_version) {
801
+ viewOptions.meterVersion = view.selector.meter_version;
802
+ }
803
+ if (view.selector.meter_schema_url) {
804
+ viewOptions.meterSchemaUrl = view.selector.meter_schema_url;
805
+ }
806
+ checkConfigUse('ViewStream', view.stream, [
807
+ 'name',
808
+ 'description',
809
+ 'aggregation',
810
+ 'aggregation_cardinality_limit',
811
+ 'attribute_keys',
812
+ ]);
813
+ if (view.stream.name) {
814
+ viewOptions.name = view.stream.name;
815
+ }
816
+ if (view.stream.description) {
817
+ viewOptions.description = view.stream.description;
818
+ }
819
+ if (view.stream.aggregation) {
820
+ viewOptions.aggregation = createAggregationOptionFromConfig(view.stream.aggregation);
821
+ }
822
+ viewOptions.aggregationCardinalityLimit =
823
+ view.stream.aggregation_cardinality_limit ?? undefined;
824
+ if (view.stream.attribute_keys) {
825
+ const processors = [];
826
+ if (view.stream.attribute_keys.included &&
827
+ view.stream.attribute_keys.included.length > 0) {
828
+ // TODO(6951): support wildcards
829
+ // Current sdk-metrics does not support *patterns* via '*' and '?'
830
+ // as defined by IncludeExclude type in declarative config.
831
+ const unsupportedKeys = view.stream.attribute_keys.included.filter(k => k.includes('*') || k.includes('?'));
832
+ if (unsupportedKeys.length > 0) {
833
+ throw new Error(`invalid /meter_provider/views/?/stream/attribute_keys/included in configuration: do not support wildcards: "${unsupportedKeys.join('", "')}"`);
834
+ }
835
+ processors.push((0, sdk_metrics_1.createAllowListAttributesProcessor)(view.stream.attribute_keys.included));
836
+ }
837
+ if (view.stream.attribute_keys.excluded &&
838
+ view.stream.attribute_keys.excluded.length > 0) {
839
+ // TODO(6951): support wildcards
840
+ // Current sdk-metrics does not support *patterns* via '*' and '?'
841
+ // as defined by IncludeExclude type in declarative config.
842
+ const unsupportedKeys = view.stream.attribute_keys.excluded.filter(k => k.includes('*') || k.includes('?'));
843
+ if (unsupportedKeys.length > 0) {
844
+ throw new Error(`invalid /meter_provider/views/?/stream/attribute_keys/excluded in configuration: do not support wildcards: "${unsupportedKeys.join('", "')}"`);
845
+ }
846
+ processors.push((0, sdk_metrics_1.createDenyListAttributesProcessor)(view.stream.attribute_keys.excluded));
847
+ }
848
+ if (processors.length > 0) {
849
+ viewOptions.attributesProcessors = processors;
850
+ }
851
+ }
852
+ return viewOptions;
853
+ }
854
+ function createMeterProviderFromConfig(resource, meter_provider) {
855
+ const readers = meter_provider.readers.map(createMetricReaderFromConfig);
856
+ const views = meter_provider.views?.map(createViewOptionsFromConfig);
857
+ // TODO(5147): exemplar_filter when sdk-metrics package supports it
858
+ // TODO(6952): meter_configurator/development when sdk-metrics package supports it
859
+ checkConfigUse('MeterProvider', meter_provider, ['readers', 'views']);
860
+ return new sdk_metrics_1.MeterProvider({
861
+ resource,
862
+ readers,
863
+ views,
864
+ // Note: sdkMetricsEnabled not configurable via decl conf. Once SDK health metrics are stabilized, they will be on by default.
865
+ });
866
+ }
867
+ exports.createMeterProviderFromConfig = createMeterProviderFromConfig;
868
+ function createSpanExporterFromConfig(exporter) {
869
+ const [name, properties] = mustSingleEntry(exporter, 'SpanExporter');
870
+ switch (name) {
871
+ case 'otlp_http': {
872
+ checkConfigUse('OtlpHttpExporter', properties, [
873
+ 'compression',
874
+ 'endpoint',
875
+ 'headers',
876
+ 'headers_list',
877
+ 'timeout',
878
+ 'tls',
879
+ 'encoding',
880
+ ]);
881
+ const props = properties;
882
+ const commonOpts = {
883
+ compression: props?.compression === 'gzip'
884
+ ? otlp_exporter_base_1.CompressionAlgorithm.GZIP
885
+ : otlp_exporter_base_1.CompressionAlgorithm.NONE,
886
+ url: props?.endpoint ?? undefined,
887
+ headers: (0, configuration_1.mergeHeadersConfig)(props?.headers, props?.headers_list),
888
+ timeoutMillis: validateExportTimeoutConfig(props?.timeout, 'OtlpHttpExporter.timeout'),
889
+ httpAgentOptions: httpTlsOptionsFromConfig(props?.tls),
890
+ };
891
+ const encoding = props?.encoding ?? 'protobuf';
892
+ switch (encoding) {
893
+ case 'json':
894
+ return new exporter_trace_otlp_http_1.OTLPTraceExporter(commonOpts);
895
+ case 'protobuf':
896
+ return new exporter_trace_otlp_proto_1.OTLPTraceExporter(commonOpts);
897
+ default:
898
+ throw new Error(`unknown OtlpHttpExporter encoding in configuration: "${encoding}"`);
899
+ }
900
+ }
901
+ case 'otlp_grpc': {
902
+ checkConfigUse('OtlpGrpcExporter', properties, [
903
+ 'compression',
904
+ 'endpoint',
905
+ 'timeout',
906
+ 'tls',
907
+ 'headers',
908
+ 'headers_list',
909
+ ]);
910
+ const props = properties;
911
+ return new exporter_trace_otlp_grpc_1.OTLPTraceExporter({
912
+ compression: props?.compression === 'gzip'
913
+ ? otlp_exporter_base_1.CompressionAlgorithm.GZIP
914
+ : otlp_exporter_base_1.CompressionAlgorithm.NONE,
915
+ url: props?.endpoint ?? undefined,
916
+ timeoutMillis: validateExportTimeoutConfig(props?.timeout, 'OtlpGrpcExporter.timeout'),
917
+ credentials: grpcCredentialsFromConfig(props?.tls),
918
+ metadata: getGrpcMetadataFromHeaders(props?.headers, props?.headers_list),
919
+ });
920
+ }
921
+ case 'console':
922
+ return new sdk_trace_1.ConsoleSpanExporter();
923
+ default:
924
+ throw new Error(`unknown SpanExporter name in configuration: "${name}"`);
925
+ }
926
+ }
927
+ function createSpanProcessorFromConfig(processor) {
928
+ const [name, properties] = mustSingleEntry(processor, 'SpanProcessor');
929
+ switch (name) {
930
+ case 'batch': {
931
+ checkConfigUse('BatchSpanProcessor', properties, [
932
+ 'exporter',
933
+ 'max_queue_size',
934
+ 'max_export_batch_size',
935
+ 'schedule_delay',
936
+ 'export_timeout',
937
+ ]);
938
+ const props = properties;
939
+ const exporter = createSpanExporterFromConfig(props.exporter);
940
+ return new sdk_trace_1.BatchSpanProcessor({
941
+ exporter,
942
+ maxQueueSize: props.max_queue_size ?? undefined,
943
+ maxExportBatchSize: props.max_export_batch_size ?? undefined,
944
+ scheduledDelayMillis: props.schedule_delay ?? undefined,
945
+ exportTimeoutMillis: validateExportTimeoutConfig(props.export_timeout, 'BatchSpanProcessor.export_timeout'),
946
+ });
947
+ }
948
+ case 'simple': {
949
+ const props = properties;
950
+ const exporter = createSpanExporterFromConfig(props.exporter);
951
+ return new sdk_trace_1.SimpleSpanProcessor({ exporter });
952
+ }
953
+ default:
954
+ throw new Error(`unknown SpanProcessor name: "${name}"`);
955
+ }
956
+ }
957
+ /**
958
+ * Returns a Sampler for the `tracer_provider.sampler` in configuration,
959
+ * or `undefined` if not set.
960
+ *
961
+ * Exported for testing.
962
+ */
963
+ function createSamplerFromConfig(samplerConfig) {
964
+ if (!samplerConfig) {
965
+ return undefined;
966
+ }
967
+ const [name, properties] = mustSingleEntry(samplerConfig, 'Sampler');
968
+ switch (name) {
969
+ case 'always_off':
970
+ return new sdk_trace_1.AlwaysOffSampler();
971
+ case 'always_on':
972
+ return new sdk_trace_1.AlwaysOnSampler();
973
+ case 'trace_id_ratio_based': {
974
+ const DEFAULT_RATIO = 1.0;
975
+ const props = properties;
976
+ return new sdk_trace_1.TraceIdRatioBasedSampler(props?.ratio ?? DEFAULT_RATIO);
977
+ }
978
+ case 'parent_based': {
979
+ const props = properties;
980
+ return new sdk_trace_1.ParentBasedSampler({
981
+ root: createSamplerFromConfig(props?.root) ?? new sdk_trace_1.AlwaysOnSampler(),
982
+ remoteParentSampled: createSamplerFromConfig(props?.remote_parent_sampled),
983
+ remoteParentNotSampled: createSamplerFromConfig(props?.remote_parent_not_sampled),
984
+ localParentSampled: createSamplerFromConfig(props?.local_parent_sampled),
985
+ localParentNotSampled: createSamplerFromConfig(props?.local_parent_not_sampled),
986
+ });
987
+ }
988
+ // TODO: always_record, once there is a release of opentelemetry-configuration with https://github.com/open-telemetry/opentelemetry-configuration/pull/698
989
+ // case 'always_record': {
990
+ // const props = properties as AlwaysRecordConfigModel;
991
+ // return createAlwaysRecordSampler(createSamplerFromConfig(props.root));
992
+ // }
993
+ // TODO(6961): composite/development
994
+ // TODO(6541): probability/development (via composite support for?)
995
+ // TODO(later): Consider supporting jaeger_remote/development if requested by a user. Only consider `sampler-jaeger-remote` package after axios dep is dropped in #6963.
996
+ default:
997
+ throw new Error(`unknown Sampler name: "${name}"`);
998
+ }
999
+ }
1000
+ exports.createSamplerFromConfig = createSamplerFromConfig;
1001
+ function createIdGeneratorFromConfig(id_generator) {
1002
+ if (!id_generator) {
1003
+ return undefined;
1004
+ }
1005
+ const [name] = mustSingleEntry(id_generator, 'IdGenerator');
1006
+ switch (name) {
1007
+ case 'random':
1008
+ return new sdk_trace_1.RandomIdGenerator();
1009
+ default:
1010
+ throw new Error(`unknown IdGenerator name: "${name}"`);
1011
+ }
1012
+ }
1013
+ exports.createIdGeneratorFromConfig = createIdGeneratorFromConfig;
1014
+ function createTracerProviderFromConfig(resource, tracer_provider, attribute_limits) {
1015
+ const spanProcessors = tracer_provider.processors.map(p => createSpanProcessorFromConfig(p));
1016
+ const spanLimits = createSpanLimitsFromConfig(tracer_provider.limits, attribute_limits);
1017
+ const sampler = createSamplerFromConfig(tracer_provider.sampler);
1018
+ const idGenerator = createIdGeneratorFromConfig(tracer_provider.id_generator);
1019
+ checkConfigUse('TracerProvider', tracer_provider, [
1020
+ 'processors',
1021
+ 'limits',
1022
+ 'sampler',
1023
+ 'id_generator',
1024
+ ]);
1025
+ // TODO(6960): 'tracer_configurator/development', TracerProvider doesn't currently support this
1026
+ // TODO(6624): meterProvider, if SDK health metrics enabled
1027
+ return new sdk_trace_1.TracerProvider({
1028
+ resource,
1029
+ spanProcessors,
1030
+ spanLimits,
1031
+ sampler,
1032
+ idGenerator,
1033
+ });
1034
+ }
1035
+ exports.createTracerProviderFromConfig = createTracerProviderFromConfig;
207
1036
  //# sourceMappingURL=create-from-config.js.map