@opentelemetry/sdk-node 0.218.0 → 0.220.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.buildSamplerFromConfig = exports.getInstanceID = exports.getMeterViewsFromConfiguration = exports.getAggregationType = exports.getInstrumentType = exports.getMeterReadersFromConfiguration = exports.getSpanLimitsFromConfiguration = exports.getSpanProcessorsFromConfiguration = exports.getSpanExporter = exports.getHttpAgentOptionsFromTls = exports.getHeadersFromConfiguration = exports.getLogRecordProcessorsFromConfiguration = exports.getLogRecordExporter = exports.getBatchLogRecordProcessorFromEnv = exports.getBatchLogRecordProcessorConfigFromEnv = exports.getLoggerProviderConfigFromEnv = exports.getPeriodicMetricReaderFromConfiguration = exports.getOtlpMetricExporterFromEnv = exports.getPeriodicExportingMetricReaderFromEnv = exports.getNonNegativeNumberFromEnv = exports.getKeyListFromObjectArray = exports.setupPropagator = exports.setupContextManager = exports.getPropagatorFromConfiguration = exports.getPropagatorFromEnv = exports.getSpanProcessorsFromEnv = exports.getOtlpProtocolFromEnv = exports.getResourceDetectorsFromConfiguration = exports.getResourceDetectorsFromEnv = exports.getResourceFromConfiguration = void 0;
7
+ exports.buildSamplerFromConfig = exports.getSamplerFromConfiguration = exports.getInstanceID = exports.getMeterViewsFromConfiguration = exports.getAggregationType = exports.getInstrumentType = exports.getMeterReadersFromConfiguration = exports.getIdGeneratorFromConfiguration = exports.getSpanProcessorsFromConfiguration = exports.getSpanExporter = exports.getHttpAgentOptionsFromTls = exports.getHeadersFromConfiguration = exports.createLogRecordProcessorFromConfig = exports.createLogRecordExporterFromConfig = exports.createLoggerProviderFromConfig = exports.getBatchLogRecordProcessorFromEnv = exports.getBatchLogRecordProcessorConfigFromEnv = exports.getLoggerProviderConfigFromEnv = exports.getPeriodicMetricReaderFromConfiguration = exports.getMetricExporter = exports.getOtlpMetricExporterFromEnv = exports.getPeriodicExportingMetricReaderFromEnv = exports.getNonNegativeNumberFromEnv = exports.getKeyListFromObjectArray = exports.setupPropagator = exports.setupContextManager = exports.getPropagatorFromConfiguration = exports.getPropagatorFromEnv = exports.getSpanProcessorsFromEnv = exports.getOtlpProtocolFromEnv = exports.getResourceDetectorsFromConfiguration = exports.getResourceDetectorsFromEnv = exports.getResourceFromConfiguration = void 0;
8
8
  const api_1 = require("@opentelemetry/api");
9
9
  const core_1 = require("@opentelemetry/core");
10
10
  const exporter_trace_otlp_proto_1 = require("@opentelemetry/exporter-trace-otlp-proto");
@@ -12,7 +12,7 @@ const exporter_trace_otlp_http_1 = require("@opentelemetry/exporter-trace-otlp-h
12
12
  const exporter_trace_otlp_grpc_1 = require("@opentelemetry/exporter-trace-otlp-grpc");
13
13
  const exporter_zipkin_1 = require("@opentelemetry/exporter-zipkin");
14
14
  const resources_1 = require("@opentelemetry/resources");
15
- const sdk_trace_base_1 = require("@opentelemetry/sdk-trace-base");
15
+ const sdk_trace_1 = require("@opentelemetry/sdk-trace");
16
16
  const propagator_b3_1 = require("@opentelemetry/propagator-b3");
17
17
  const propagator_jaeger_1 = require("@opentelemetry/propagator-jaeger");
18
18
  const context_async_hooks_1 = require("@opentelemetry/context-async-hooks");
@@ -20,29 +20,40 @@ const exporter_logs_otlp_http_1 = require("@opentelemetry/exporter-logs-otlp-htt
20
20
  const exporter_logs_otlp_grpc_1 = require("@opentelemetry/exporter-logs-otlp-grpc");
21
21
  const exporter_logs_otlp_proto_1 = require("@opentelemetry/exporter-logs-otlp-proto");
22
22
  const otlp_exporter_base_1 = require("@opentelemetry/otlp-exporter-base");
23
+ const otlp_grpc_exporter_base_1 = require("@opentelemetry/otlp-grpc-exporter-base");
24
+ const configuration_1 = require("@opentelemetry/configuration");
23
25
  const sdk_metrics_1 = require("@opentelemetry/sdk-metrics");
24
26
  const exporter_metrics_otlp_grpc_1 = require("@opentelemetry/exporter-metrics-otlp-grpc");
25
27
  const exporter_metrics_otlp_http_1 = require("@opentelemetry/exporter-metrics-otlp-http");
28
+ const exporter_metrics_otlp_http_2 = require("@opentelemetry/exporter-metrics-otlp-http");
26
29
  const exporter_metrics_otlp_proto_1 = require("@opentelemetry/exporter-metrics-otlp-proto");
27
30
  const sdk_logs_1 = require("@opentelemetry/sdk-logs");
28
31
  const fs = require("fs");
32
+ const util_1 = require("util");
33
+ const create_from_env_1 = require("./create-from-env");
29
34
  const RESOURCE_DETECTOR_ENVIRONMENT = 'env';
30
35
  const RESOURCE_DETECTOR_HOST = 'host';
31
36
  const RESOURCE_DETECTOR_OS = 'os';
32
37
  const RESOURCE_DETECTOR_PROCESS = 'process';
33
38
  const RESOURCE_DETECTOR_SERVICE_INSTANCE_ID = 'serviceinstance';
34
39
  function getResourceFromConfiguration(config) {
35
- if (config.resource && config.resource.attributes) {
36
- const attr = {};
37
- for (let i = 0; i < config.resource.attributes.length; i++) {
38
- const a = config.resource.attributes[i];
39
- attr[a.name] = a.value;
40
+ if (!config.resource) {
41
+ return undefined;
42
+ }
43
+ const configAttrs = (0, configuration_1.mergeResourceAttributesConfig)(config.resource.attributes, config.resource.attributes_list);
44
+ if (!configAttrs) {
45
+ return undefined;
46
+ }
47
+ const attrs = {};
48
+ for (let i = 0; i < configAttrs.length; i++) {
49
+ const a = configAttrs[i];
50
+ if (a.value !== null) {
51
+ attrs[a.name] = a.value;
40
52
  }
41
- return (0, resources_1.resourceFromAttributes)(attr, {
42
- schemaUrl: config.resource.schema_url,
43
- });
44
53
  }
45
- return undefined;
54
+ return (0, resources_1.resourceFromAttributes)(attrs, {
55
+ schemaUrl: config.resource.schema_url ?? undefined,
56
+ });
46
57
  }
47
58
  exports.getResourceFromConfiguration = getResourceFromConfiguration;
48
59
  function getResourceDetectorsFromEnv() {
@@ -74,15 +85,15 @@ function getResourceDetectorsFromConfiguration(config) {
74
85
  const detectors = config.resource?.['detection/development']?.detectors ?? [];
75
86
  return detectors.flatMap(detector => {
76
87
  const result = [];
77
- if (detector.host != null)
88
+ if (detector.host !== undefined)
78
89
  result.push(resources_1.hostDetector);
79
- if (detector.os != null)
90
+ if (detector.os !== undefined)
80
91
  result.push(resources_1.osDetector);
81
- if (detector.process != null)
92
+ if (detector.process !== undefined)
82
93
  result.push(resources_1.processDetector);
83
- if (detector.service != null)
94
+ if (detector.service !== undefined)
84
95
  result.push(resources_1.serviceInstanceIdDetector);
85
- if (detector.env != null)
96
+ if (detector.env !== undefined)
86
97
  result.push(resources_1.envDetector);
87
98
  return result;
88
99
  });
@@ -108,11 +119,11 @@ function getOtlpExporterFromEnv() {
108
119
  return new exporter_trace_otlp_proto_1.OTLPTraceExporter();
109
120
  }
110
121
  }
111
- function getSpanProcessorsFromEnv() {
122
+ function getSpanProcessorsFromEnv(selfObsMeterProvider) {
112
123
  const exportersMap = new Map([
113
124
  ['otlp', () => getOtlpExporterFromEnv()],
114
125
  ['zipkin', () => new exporter_zipkin_1.ZipkinExporter()],
115
- ['console', () => new sdk_trace_base_1.ConsoleSpanExporter()],
126
+ ['console', () => new sdk_trace_1.ConsoleSpanExporter()],
116
127
  ]);
117
128
  const exporters = [];
118
129
  const processors = [];
@@ -140,11 +151,11 @@ function getSpanProcessorsFromEnv() {
140
151
  }
141
152
  }
142
153
  for (const exp of exporters) {
143
- if (exp instanceof sdk_trace_base_1.ConsoleSpanExporter) {
144
- processors.push(new sdk_trace_base_1.SimpleSpanProcessor(exp));
154
+ if (exp instanceof sdk_trace_1.ConsoleSpanExporter) {
155
+ processors.push(new sdk_trace_1.SimpleSpanProcessor({ exporter: exp, selfObsMeterProvider }));
145
156
  }
146
157
  else {
147
- processors.push(new sdk_trace_base_1.BatchSpanProcessor(exp));
158
+ processors.push((0, create_from_env_1.createBatchSpanProcessorFromEnv)(exp, selfObsMeterProvider));
148
159
  }
149
160
  }
150
161
  if (exporters.length === 0) {
@@ -207,13 +218,50 @@ exports.getPropagatorFromEnv = getPropagatorFromEnv;
207
218
  * Get a propagator as defined by configuration model from configuration
208
219
  */
209
220
  function getPropagatorFromConfiguration(config) {
210
- const propagatorsValue = getKeyListFromObjectArray(config.propagator?.composite);
211
- if (propagatorsValue == null) {
212
- // return undefined to fall back to default
221
+ if (!config.propagator) {
213
222
  return undefined;
214
223
  }
215
- if (propagatorsValue.includes('none')) {
216
- return null;
224
+ const configComposite = (0, configuration_1.mergePropagatorCompositeConfig)(config.propagator.composite, config.propagator.composite_list);
225
+ if (!configComposite) {
226
+ return undefined;
227
+ }
228
+ // TextMapPropagator config items are objects with a single key (the name).
229
+ // Transform this into a more convenient `(name, value)` 2-tuple.
230
+ //
231
+ // As well, guard against two cases where the TypeScript type
232
+ // `TextMapPropagatorConfigModel` does not exactly represent the JSON schema:
233
+ // 1. `"minProperties": 1, "maxProperties": 1,`
234
+ // 2. The type allows keys with an `undefined` value, but the JSON schema
235
+ // does not.
236
+ const kvFromItem = (item) => {
237
+ const keys = [];
238
+ let value = undefined;
239
+ for (const key of Object.keys(item)) {
240
+ value = item[key];
241
+ if (value === undefined) {
242
+ continue;
243
+ }
244
+ keys.push(key);
245
+ }
246
+ if (keys.length !== 1) {
247
+ throw new Error(`invalid "propagator" entry in configuration, there must be exactly one key (with a non-undefined value): ${(0, util_1.inspect)(item)}`);
248
+ }
249
+ return [keys[0], value];
250
+ };
251
+ // First pass: handle 'none', remove dupes.
252
+ const names = new Set();
253
+ const kvs = [];
254
+ for (const item of configComposite) {
255
+ const kv = kvFromItem(item);
256
+ const k = kv[0];
257
+ if (names.has(k)) {
258
+ continue;
259
+ }
260
+ names.add(k);
261
+ kvs.push(kv);
262
+ if (k === 'none') {
263
+ return undefined;
264
+ }
217
265
  }
218
266
  // Implementation note: this only contains specification required propagators that are actually hosted in this repo.
219
267
  // Any other propagators (like aws, aws-lambda, should go into `@opentelemetry/auto-configuration-propagators` instead).
@@ -227,22 +275,19 @@ function getPropagatorFromConfiguration(config) {
227
275
  ],
228
276
  ['jaeger', () => new propagator_jaeger_1.JaegerPropagator()],
229
277
  ]);
230
- // Values MUST be deduplicated in order to register a Propagator only once.
231
- const uniquePropagatorNames = Array.from(new Set(propagatorsValue));
232
278
  const validPropagators = [];
233
- uniquePropagatorNames.forEach(name => {
279
+ for (const [name] of kvs) {
234
280
  const propagator = propagatorsFactory.get(name)?.();
235
281
  if (!propagator) {
236
282
  api_1.diag.warn(`Propagator "${name}" requested through configuration is unavailable.`);
237
- return;
283
+ continue;
238
284
  }
239
285
  validPropagators.push(propagator);
240
- });
286
+ }
241
287
  if (validPropagators.length === 0) {
242
- // null to signal that the default should **not** be used in its place.
243
- return null;
288
+ return undefined;
244
289
  }
245
- else if (uniquePropagatorNames.length === 1) {
290
+ else if (validPropagators.length === 1) {
246
291
  return validPropagators[0];
247
292
  }
248
293
  else {
@@ -358,53 +403,126 @@ function getOtlpMetricExporterFromEnv() {
358
403
  return new exporter_metrics_otlp_proto_1.OTLPMetricExporter();
359
404
  }
360
405
  exports.getOtlpMetricExporterFromEnv = getOtlpMetricExporterFromEnv;
361
- function getPeriodicMetricReaderFromConfiguration(periodic) {
362
- if (periodic.exporter) {
363
- let exporter;
364
- if (periodic.exporter.otlp_http) {
365
- const encoding = periodic.exporter.otlp_http.encoding;
366
- if (encoding === 'json') {
367
- exporter = new exporter_metrics_otlp_http_1.OTLPMetricExporter({
368
- compression: periodic.exporter.otlp_http.compression === 'gzip'
369
- ? otlp_exporter_base_1.CompressionAlgorithm.GZIP
370
- : otlp_exporter_base_1.CompressionAlgorithm.NONE,
371
- });
372
- }
373
- else if (encoding === 'protobuf') {
374
- exporter = new exporter_metrics_otlp_proto_1.OTLPMetricExporter({
375
- compression: periodic.exporter.otlp_http.compression === 'gzip'
376
- ? otlp_exporter_base_1.CompressionAlgorithm.GZIP
377
- : otlp_exporter_base_1.CompressionAlgorithm.NONE,
378
- });
379
- }
380
- else {
381
- api_1.diag.warn(`Unsupported OTLP metrics encoding: ${encoding}.`);
382
- }
383
- }
384
- if (periodic.exporter.otlp_grpc) {
385
- exporter = new exporter_metrics_otlp_grpc_1.OTLPMetricExporter({
386
- compression: periodic.exporter.otlp_grpc.compression === 'gzip'
387
- ? otlp_exporter_base_1.CompressionAlgorithm.GZIP
388
- : otlp_exporter_base_1.CompressionAlgorithm.NONE,
389
- });
390
- }
391
- if (exporter) {
392
- // TODO(6425): add cardinality_limits
393
- return new sdk_metrics_1.PeriodicExportingMetricReader({
394
- exportIntervalMillis: periodic.interval ?? 60000,
395
- exportTimeoutMillis: periodic.timeout ?? 30000,
396
- exporter,
397
- });
398
- }
399
- if (periodic.exporter.console) {
400
- return new sdk_metrics_1.PeriodicExportingMetricReader({
401
- exporter: new sdk_metrics_1.ConsoleMetricExporter(),
402
- });
403
- }
406
+ function getMetricProducersFromConfiguration(producers) {
407
+ if (!producers || producers.length === 0) {
408
+ return undefined;
409
+ }
410
+ const result = [];
411
+ for (const producer of producers) {
412
+ // Note: The "opencensus" MetricProducer is intentionally not supported.
413
+ // It is deprecated in OpenTelemetry Configuration v1.2.0.
414
+ api_1.diag.warn(`Unsupported metric producer in configuration: "${producer}". Skipping.`);
415
+ }
416
+ return result.length > 0 ? result : undefined;
417
+ }
418
+ /**
419
+ * Map a declarative-config `temporality_preference` value to the enum the OTLP
420
+ * metric exporters expect. Returns undefined for an unspecified preference so
421
+ * the exporter falls back to its own default (cumulative).
422
+ */
423
+ function getMetricTemporalityPreference(preference) {
424
+ switch (preference) {
425
+ case 'delta':
426
+ return exporter_metrics_otlp_http_2.AggregationTemporalityPreference.DELTA;
427
+ case 'low_memory':
428
+ return exporter_metrics_otlp_http_2.AggregationTemporalityPreference.LOWMEMORY;
429
+ case 'cumulative':
430
+ return exporter_metrics_otlp_http_2.AggregationTemporalityPreference.CUMULATIVE;
431
+ default:
432
+ return undefined;
433
+ }
434
+ }
435
+ /**
436
+ * Map a declarative-config `default_histogram_aggregation` value to an
437
+ * AggregationSelector that applies the requested aggregation to histogram
438
+ * instruments and leaves all other instrument types at their default. Returns
439
+ * undefined for an unspecified value so the exporter uses its own default.
440
+ */
441
+ function getMetricAggregationPreference(aggregation) {
442
+ let histogramAggregation;
443
+ switch (aggregation) {
444
+ case 'base2_exponential_bucket_histogram':
445
+ histogramAggregation = { type: sdk_metrics_1.AggregationType.EXPONENTIAL_HISTOGRAM };
446
+ break;
447
+ case 'explicit_bucket_histogram':
448
+ histogramAggregation = {
449
+ type: sdk_metrics_1.AggregationType.EXPLICIT_BUCKET_HISTOGRAM,
450
+ };
451
+ break;
452
+ default:
453
+ return undefined;
454
+ }
455
+ return (instrumentType) => instrumentType === sdk_metrics_1.InstrumentType.HISTOGRAM
456
+ ? histogramAggregation
457
+ : { type: sdk_metrics_1.AggregationType.DEFAULT };
458
+ }
459
+ function getOtlpHttpMetricExporter(otlpHttp) {
460
+ const encoding = otlpHttp?.encoding ?? 'protobuf';
461
+ const options = {
462
+ compression: otlpHttp?.compression === 'gzip'
463
+ ? otlp_exporter_base_1.CompressionAlgorithm.GZIP
464
+ : otlp_exporter_base_1.CompressionAlgorithm.NONE,
465
+ url: otlpHttp?.endpoint ?? undefined,
466
+ headers: getHeadersFromConfiguration(otlpHttp?.headers),
467
+ timeoutMillis: validateExporterTimeout(otlpHttp?.timeout),
468
+ httpAgentOptions: getHttpAgentOptionsFromTls(otlpHttp?.tls),
469
+ temporalityPreference: getMetricTemporalityPreference(otlpHttp?.temporality_preference),
470
+ aggregationPreference: getMetricAggregationPreference(otlpHttp?.default_histogram_aggregation),
471
+ };
472
+ if (encoding === 'json') {
473
+ return new exporter_metrics_otlp_http_1.OTLPMetricExporter(options);
474
+ }
475
+ else if (encoding === 'protobuf') {
476
+ return new exporter_metrics_otlp_proto_1.OTLPMetricExporter(options);
477
+ }
478
+ api_1.diag.warn(`Unsupported OTLP metrics encoding: ${encoding}.`);
479
+ return undefined;
480
+ }
481
+ function getOtlpGrpcMetricExporter(otlpGrpc) {
482
+ return new exporter_metrics_otlp_grpc_1.OTLPMetricExporter({
483
+ compression: otlpGrpc?.compression === 'gzip'
484
+ ? otlp_exporter_base_1.CompressionAlgorithm.GZIP
485
+ : otlp_exporter_base_1.CompressionAlgorithm.NONE,
486
+ url: otlpGrpc?.endpoint ?? undefined,
487
+ timeoutMillis: validateExporterTimeout(otlpGrpc?.timeout),
488
+ credentials: getGrpcCredentialsFromTls(otlpGrpc?.tls),
489
+ metadata: getGrpcMetadataFromHeaders(otlpGrpc?.headers),
490
+ temporalityPreference: getMetricTemporalityPreference(otlpGrpc?.temporality_preference),
491
+ aggregationPreference: getMetricAggregationPreference(otlpGrpc?.default_histogram_aggregation),
492
+ });
493
+ }
494
+ function getMetricExporter(exporter) {
495
+ if (exporter.otlp_http !== undefined) {
496
+ return getOtlpHttpMetricExporter(exporter.otlp_http);
497
+ }
498
+ if (exporter.otlp_grpc !== undefined) {
499
+ return getOtlpGrpcMetricExporter(exporter.otlp_grpc);
404
500
  }
405
- api_1.diag.warn(`Unsupported Metric Exporter.`);
501
+ if (exporter.console !== undefined) {
502
+ return new sdk_metrics_1.ConsoleMetricExporter();
503
+ }
504
+ api_1.diag.warn('Unsupported Metric Exporter.');
406
505
  return undefined;
407
506
  }
507
+ exports.getMetricExporter = getMetricExporter;
508
+ function getPeriodicMetricReaderFromConfiguration(periodic) {
509
+ if (!periodic.exporter) {
510
+ api_1.diag.warn('Unsupported Metric Exporter.');
511
+ return undefined;
512
+ }
513
+ const exporter = getMetricExporter(periodic.exporter);
514
+ if (!exporter) {
515
+ return undefined;
516
+ }
517
+ const metricProducers = getMetricProducersFromConfiguration(periodic.producers);
518
+ // TODO(6425): add cardinality_limits
519
+ return new sdk_metrics_1.PeriodicExportingMetricReader({
520
+ exportIntervalMillis: periodic.interval ?? 60000,
521
+ exportTimeoutMillis: periodic.timeout ?? 30000,
522
+ exporter,
523
+ metricProducers,
524
+ });
525
+ }
408
526
  exports.getPeriodicMetricReaderFromConfiguration = getPeriodicMetricReaderFromConfiguration;
409
527
  /**
410
528
  * Get LoggerProviderConfig from environment variables.
@@ -432,158 +550,224 @@ function getBatchLogRecordProcessorConfigFromEnv() {
432
550
  }
433
551
  exports.getBatchLogRecordProcessorConfigFromEnv = getBatchLogRecordProcessorConfigFromEnv;
434
552
  function getBatchLogRecordProcessorFromEnv(exporter) {
435
- return new sdk_logs_1.BatchLogRecordProcessor(exporter, getBatchLogRecordProcessorConfigFromEnv());
553
+ return new sdk_logs_1.BatchLogRecordProcessor({
554
+ exporter,
555
+ ...getBatchLogRecordProcessorConfigFromEnv(),
556
+ });
436
557
  }
437
558
  exports.getBatchLogRecordProcessorFromEnv = getBatchLogRecordProcessorFromEnv;
438
- function getLogRecordExporter(exporter) {
439
- if (exporter.otlp_http) {
440
- const encoding = exporter.otlp_http.encoding;
441
- if (encoding === 'json') {
442
- return new exporter_logs_otlp_http_1.OTLPLogExporter({
443
- compression: exporter.otlp_http.compression === 'gzip'
559
+ function createLogRecordLimitsFromConfig(limits, attribute_limits) {
560
+ return {
561
+ attributeValueLengthLimit: limits?.attribute_value_length_limit ??
562
+ attribute_limits?.attribute_value_length_limit ??
563
+ undefined,
564
+ attributeCountLimit: limits?.attribute_count_limit ??
565
+ attribute_limits?.attribute_count_limit ??
566
+ undefined,
567
+ };
568
+ }
569
+ function createLoggerProviderFromConfig(resource, logger_provider, attribute_limits) {
570
+ const processors = logger_provider.processors.map(p => createLogRecordProcessorFromConfig(p));
571
+ const logRecordLimits = createLogRecordLimitsFromConfig(logger_provider.limits, attribute_limits);
572
+ checkConfigUse('LoggerProvider', logger_provider, ['processors', 'limits']);
573
+ return new sdk_logs_1.LoggerProvider({
574
+ resource,
575
+ processors,
576
+ logRecordLimits,
577
+ // TODO: loggerConfigurator
578
+ // TODO: meterProvider
579
+ // Note: forceFlushTimeoutMillis not configurable via decl conf.
580
+ });
581
+ }
582
+ exports.createLoggerProviderFromConfig = createLoggerProviderFromConfig;
583
+ function createLogRecordExporterFromConfig(exporter) {
584
+ const [name, properties] = mustSingleEntry(exporter, 'LogRecordExporter');
585
+ switch (name) {
586
+ case 'otlp_http': {
587
+ const props = properties;
588
+ const commonOpts = {
589
+ compression: props?.compression === 'gzip'
444
590
  ? otlp_exporter_base_1.CompressionAlgorithm.GZIP
445
591
  : otlp_exporter_base_1.CompressionAlgorithm.NONE,
446
- });
592
+ url: props?.endpoint ?? undefined,
593
+ headers: getHeadersFromConfiguration(props?.headers),
594
+ timeoutMillis: validateExporterTimeout(props?.timeout),
595
+ httpAgentOptions: getHttpAgentOptionsFromTls(props?.tls),
596
+ };
597
+ const encoding = props?.encoding ?? 'protobuf';
598
+ switch (encoding) {
599
+ case 'json':
600
+ return new exporter_logs_otlp_http_1.OTLPLogExporter(commonOpts);
601
+ case 'protobuf':
602
+ return new exporter_logs_otlp_proto_1.OTLPLogExporter(commonOpts);
603
+ default:
604
+ throw new Error(`unknown OtlpHttpExporter encoding in configuration: "${encoding}"`);
605
+ }
447
606
  }
448
- if (encoding === 'protobuf') {
449
- return new exporter_logs_otlp_proto_1.OTLPLogExporter({
450
- compression: exporter.otlp_http.compression === 'gzip'
607
+ case 'otlp_grpc': {
608
+ const props = properties;
609
+ return new exporter_logs_otlp_grpc_1.OTLPLogExporter({
610
+ compression: props?.compression === 'gzip'
451
611
  ? otlp_exporter_base_1.CompressionAlgorithm.GZIP
452
612
  : otlp_exporter_base_1.CompressionAlgorithm.NONE,
613
+ url: props?.endpoint ?? undefined,
614
+ timeoutMillis: validateExporterTimeout(props?.timeout),
615
+ credentials: getGrpcCredentialsFromTls(props?.tls),
616
+ metadata: getGrpcMetadataFromHeaders(props?.headers),
453
617
  });
454
618
  }
455
- api_1.diag.warn(`Unsupported OTLP logs encoding: ${encoding}. Using http/protobuf.`);
456
- return new exporter_logs_otlp_proto_1.OTLPLogExporter({
457
- compression: exporter.otlp_http.compression === 'gzip'
458
- ? otlp_exporter_base_1.CompressionAlgorithm.GZIP
459
- : otlp_exporter_base_1.CompressionAlgorithm.NONE,
460
- });
461
- }
462
- else if (exporter.otlp_grpc) {
463
- return new exporter_logs_otlp_grpc_1.OTLPLogExporter({
464
- compression: exporter.otlp_grpc.compression === 'gzip'
465
- ? otlp_exporter_base_1.CompressionAlgorithm.GZIP
466
- : otlp_exporter_base_1.CompressionAlgorithm.NONE,
467
- });
468
- }
469
- else if (exporter.console) {
470
- return new sdk_logs_1.ConsoleLogRecordExporter();
619
+ case 'console':
620
+ return new sdk_logs_1.ConsoleLogRecordExporter();
621
+ default:
622
+ throw new Error(`unknown LogRecordExporter name in configuration: "${name}"`);
471
623
  }
472
- api_1.diag.warn(`Unsupported Exporter value. No Log Record Exporter registered`);
473
- return undefined;
474
624
  }
475
- exports.getLogRecordExporter = getLogRecordExporter;
476
- function getLogRecordProcessorsFromConfiguration(config) {
477
- const logRecordProcessors = [];
478
- config.logger_provider?.processors?.forEach(processor => {
479
- if (processor.batch) {
480
- const exporter = getLogRecordExporter(processor.batch.exporter);
481
- if (exporter) {
482
- logRecordProcessors.push(new sdk_logs_1.BatchLogRecordProcessor(exporter, {
483
- maxQueueSize: processor.batch.max_queue_size,
484
- maxExportBatchSize: processor.batch.max_export_batch_size,
485
- scheduledDelayMillis: processor.batch.schedule_delay,
486
- exportTimeoutMillis: processor.batch.export_timeout,
487
- }));
488
- }
625
+ exports.createLogRecordExporterFromConfig = createLogRecordExporterFromConfig;
626
+ function createLogRecordProcessorFromConfig(processor) {
627
+ const [name, properties] = mustSingleEntry(processor, 'LogRecordProcessor');
628
+ switch (name) {
629
+ case 'batch': {
630
+ const props = properties;
631
+ const exporter = createLogRecordExporterFromConfig(props.exporter);
632
+ return new sdk_logs_1.BatchLogRecordProcessor({
633
+ exporter,
634
+ maxQueueSize: props.max_queue_size ?? undefined,
635
+ maxExportBatchSize: props.max_export_batch_size ?? undefined,
636
+ scheduledDelayMillis: props.schedule_delay ?? undefined,
637
+ exportTimeoutMillis: props.export_timeout ?? undefined,
638
+ });
489
639
  }
490
- if (processor.simple) {
491
- const exporter = getLogRecordExporter(processor.simple.exporter);
492
- if (exporter) {
493
- logRecordProcessors.push(new sdk_logs_1.SimpleLogRecordProcessor(exporter));
494
- }
640
+ case 'simple': {
641
+ const props = properties;
642
+ const exporter = createLogRecordExporterFromConfig(props.exporter);
643
+ return new sdk_logs_1.SimpleLogRecordProcessor({ exporter });
495
644
  }
496
- });
497
- if (logRecordProcessors.length > 0) {
498
- return logRecordProcessors;
645
+ default:
646
+ throw new Error(`unknown LogRecordProcessor name: "${name}"`);
499
647
  }
500
- return undefined;
501
648
  }
502
- exports.getLogRecordProcessorsFromConfiguration = getLogRecordProcessorsFromConfiguration;
649
+ exports.createLogRecordProcessorFromConfig = createLogRecordProcessorFromConfig;
503
650
  function getHeadersFromConfiguration(headers) {
504
651
  if (!headers) {
505
652
  return undefined;
506
653
  }
507
654
  const result = {};
508
655
  headers.forEach(header => {
509
- result[header.name] = header.value;
656
+ if (header.value !== null) {
657
+ result[header.name] = header.value;
658
+ }
510
659
  });
511
660
  return result;
512
661
  }
513
662
  exports.getHeadersFromConfiguration = getHeadersFromConfiguration;
663
+ /**
664
+ * Validate an exporter timeout value. The spec says 0 means "no limit
665
+ * (infinity)" but the JS exporters don't support that yet (see #6617).
666
+ * Warn and return undefined so the exporter falls back to its default.
667
+ */
668
+ function validateExporterTimeout(timeout) {
669
+ if (timeout === null) {
670
+ return undefined;
671
+ }
672
+ else if (timeout === 0) {
673
+ api_1.diag.warn('Exporter timeout of 0 (infinite) is not supported. Using default timeout.');
674
+ return undefined;
675
+ }
676
+ return timeout;
677
+ }
514
678
  function getHttpAgentOptionsFromTls(tls) {
515
679
  if (tls && (tls.ca_file || tls.cert_file || tls.key_file)) {
516
- const httpsAgentOptions = {};
517
- if (tls.ca_file) {
518
- try {
519
- httpsAgentOptions.ca = fs.readFileSync(tls.ca_file);
520
- }
521
- catch (e) {
522
- api_1.diag.warn(`Failed to read TLS CA file at ${tls.ca_file}: ${e}`);
523
- }
524
- }
525
- if (tls.cert_file) {
526
- try {
527
- httpsAgentOptions.cert = fs.readFileSync(tls.cert_file);
528
- }
529
- catch (e) {
530
- api_1.diag.warn(`Failed to read TLS cert file at ${tls.cert_file}: ${e}`);
531
- }
680
+ return {
681
+ ca: readFileOrWarn(tls.ca_file, 'TLS CA'),
682
+ cert: readFileOrWarn(tls.cert_file, 'TLS cert'),
683
+ key: readFileOrWarn(tls.key_file, 'TLS key'),
684
+ };
685
+ }
686
+ return undefined;
687
+ }
688
+ exports.getHttpAgentOptionsFromTls = getHttpAgentOptionsFromTls;
689
+ function getGrpcCredentialsFromTls(tls) {
690
+ if (tls?.insecure) {
691
+ return (0, otlp_grpc_exporter_base_1.createInsecureCredentials)();
692
+ }
693
+ const rootCert = readFileOrWarn(tls?.ca_file, 'TLS CA');
694
+ const privateKey = readFileOrWarn(tls?.key_file, 'TLS key');
695
+ const certChain = readFileOrWarn(tls?.cert_file, 'TLS cert');
696
+ if (rootCert || privateKey || certChain) {
697
+ try {
698
+ return (0, otlp_grpc_exporter_base_1.createSslCredentials)(rootCert, privateKey, certChain);
532
699
  }
533
- if (tls.key_file) {
534
- try {
535
- httpsAgentOptions.key = fs.readFileSync(tls.key_file);
536
- }
537
- catch (e) {
538
- api_1.diag.warn(`Failed to read TLS key file at ${tls.key_file}: ${e}`);
539
- }
700
+ catch (e) {
701
+ api_1.diag.warn(`Failed to create gRPC SSL credentials: ${e}`);
702
+ return undefined;
540
703
  }
541
- return httpsAgentOptions;
542
704
  }
543
705
  return undefined;
544
706
  }
545
- exports.getHttpAgentOptionsFromTls = getHttpAgentOptionsFromTls;
707
+ function getGrpcMetadataFromHeaders(headers) {
708
+ if (!headers || headers.length === 0) {
709
+ return undefined;
710
+ }
711
+ const metadata = (0, otlp_grpc_exporter_base_1.createEmptyMetadata)();
712
+ for (const header of headers) {
713
+ if (header.value !== null) {
714
+ metadata.set(header.name, header.value);
715
+ }
716
+ }
717
+ return metadata;
718
+ }
719
+ function readFileOrWarn(filePath, label) {
720
+ if (!filePath)
721
+ return undefined;
722
+ try {
723
+ return fs.readFileSync(filePath);
724
+ }
725
+ catch (e) {
726
+ api_1.diag.warn(`Failed to read ${label} file at ${filePath}: ${e}`);
727
+ return undefined;
728
+ }
729
+ }
546
730
  function getSpanExporter(exporter) {
547
- if (exporter.otlp_http) {
548
- const encoding = exporter.otlp_http.encoding;
731
+ if (exporter.otlp_http !== undefined) {
732
+ const encoding = exporter.otlp_http?.encoding ?? 'protobuf';
549
733
  if (encoding === 'json') {
550
734
  return new exporter_trace_otlp_http_1.OTLPTraceExporter({
551
- compression: exporter.otlp_http.compression === 'gzip'
735
+ compression: exporter.otlp_http?.compression === 'gzip'
552
736
  ? otlp_exporter_base_1.CompressionAlgorithm.GZIP
553
737
  : otlp_exporter_base_1.CompressionAlgorithm.NONE,
554
- url: exporter.otlp_http.endpoint,
555
- headers: getHeadersFromConfiguration(exporter.otlp_http.headers),
556
- timeoutMillis: exporter.otlp_http.timeout,
557
- httpAgentOptions: getHttpAgentOptionsFromTls(exporter.otlp_http.tls),
738
+ url: exporter.otlp_http?.endpoint ?? undefined,
739
+ headers: getHeadersFromConfiguration(exporter.otlp_http?.headers),
740
+ timeoutMillis: validateExporterTimeout(exporter.otlp_http?.timeout),
741
+ httpAgentOptions: getHttpAgentOptionsFromTls(exporter.otlp_http?.tls),
558
742
  });
559
743
  }
560
744
  else {
561
745
  return new exporter_trace_otlp_proto_1.OTLPTraceExporter({
562
- compression: exporter.otlp_http.compression === 'gzip'
746
+ compression: exporter.otlp_http?.compression === 'gzip'
563
747
  ? otlp_exporter_base_1.CompressionAlgorithm.GZIP
564
748
  : otlp_exporter_base_1.CompressionAlgorithm.NONE,
565
- url: exporter.otlp_http.endpoint,
566
- headers: getHeadersFromConfiguration(exporter.otlp_http.headers),
567
- timeoutMillis: exporter.otlp_http.timeout,
568
- httpAgentOptions: getHttpAgentOptionsFromTls(exporter.otlp_http.tls),
749
+ url: exporter.otlp_http?.endpoint ?? undefined,
750
+ headers: getHeadersFromConfiguration(exporter.otlp_http?.headers),
751
+ timeoutMillis: validateExporterTimeout(exporter.otlp_http?.timeout),
752
+ httpAgentOptions: getHttpAgentOptionsFromTls(exporter.otlp_http?.tls),
569
753
  });
570
754
  }
571
755
  }
572
- else if (exporter.otlp_grpc) {
756
+ else if (exporter.otlp_grpc !== undefined) {
573
757
  return new exporter_trace_otlp_grpc_1.OTLPTraceExporter({
574
- compression: exporter.otlp_grpc.compression === 'gzip'
758
+ compression: exporter.otlp_grpc?.compression === 'gzip'
575
759
  ? otlp_exporter_base_1.CompressionAlgorithm.GZIP
576
760
  : otlp_exporter_base_1.CompressionAlgorithm.NONE,
577
- url: exporter.otlp_grpc.endpoint,
578
- timeoutMillis: exporter.otlp_grpc.timeout,
579
- // TODO (6614): add support for credentials
580
- // TODO (6615): add metadata (headers) support
761
+ url: exporter.otlp_grpc?.endpoint ?? undefined,
762
+ timeoutMillis: validateExporterTimeout(exporter.otlp_grpc?.timeout),
763
+ credentials: getGrpcCredentialsFromTls(exporter.otlp_grpc?.tls),
764
+ metadata: getGrpcMetadataFromHeaders(exporter.otlp_grpc?.headers),
581
765
  });
582
766
  }
583
- else if (exporter.console) {
584
- return new sdk_trace_base_1.ConsoleSpanExporter();
767
+ else if (exporter.console !== undefined) {
768
+ return new sdk_trace_1.ConsoleSpanExporter();
585
769
  }
586
- api_1.diag.warn(`Unsupported Exporter value. No Span Exporter registered`);
770
+ api_1.diag.warn('Unsupported Exporter value. No Span Exporter registered');
587
771
  return undefined;
588
772
  }
589
773
  exports.getSpanExporter = getSpanExporter;
@@ -593,18 +777,19 @@ function getSpanProcessorsFromConfiguration(config) {
593
777
  if (processor.batch) {
594
778
  const exporter = getSpanExporter(processor.batch.exporter);
595
779
  if (exporter) {
596
- spanProcessors.push(new sdk_trace_base_1.BatchSpanProcessor(exporter, {
597
- maxQueueSize: processor.batch.max_queue_size,
598
- maxExportBatchSize: processor.batch.max_export_batch_size,
599
- scheduledDelayMillis: processor.batch.schedule_delay,
600
- exportTimeoutMillis: processor.batch.export_timeout,
780
+ spanProcessors.push(new sdk_trace_1.BatchSpanProcessor({
781
+ exporter,
782
+ maxQueueSize: processor.batch.max_queue_size ?? undefined,
783
+ maxExportBatchSize: processor.batch.max_export_batch_size ?? undefined,
784
+ scheduledDelayMillis: processor.batch.schedule_delay ?? undefined,
785
+ exportTimeoutMillis: processor.batch.export_timeout ?? undefined,
601
786
  }));
602
787
  }
603
788
  }
604
789
  if (processor.simple) {
605
790
  const exporter = getSpanExporter(processor.simple.exporter);
606
791
  if (exporter) {
607
- spanProcessors.push(new sdk_trace_base_1.SimpleSpanProcessor(exporter));
792
+ spanProcessors.push(new sdk_trace_1.SimpleSpanProcessor({ exporter }));
608
793
  }
609
794
  }
610
795
  });
@@ -614,26 +799,23 @@ function getSpanProcessorsFromConfiguration(config) {
614
799
  return undefined;
615
800
  }
616
801
  exports.getSpanProcessorsFromConfiguration = getSpanProcessorsFromConfiguration;
617
- function getSpanLimitsFromConfiguration(config) {
618
- if (config.tracer_provider?.limits) {
619
- const limitsConfig = config.tracer_provider.limits;
620
- const spanLimits = {};
621
- spanLimits.attributeCountLimit = limitsConfig.attribute_count_limit ?? 128;
622
- spanLimits.eventCountLimit = limitsConfig.event_count_limit ?? 128;
623
- spanLimits.linkCountLimit = limitsConfig.link_count_limit ?? 128;
624
- spanLimits.attributePerLinkCountLimit =
625
- limitsConfig.link_attribute_count_limit ?? 128;
626
- spanLimits.attributePerEventCountLimit =
627
- limitsConfig.event_attribute_count_limit ?? 128;
628
- if (limitsConfig.attribute_value_length_limit != null) {
629
- spanLimits.attributeValueLengthLimit =
630
- limitsConfig.attribute_value_length_limit;
631
- }
632
- return spanLimits;
802
+ function getIdGeneratorFromConfiguration(config) {
803
+ const idGenerator = config.tracer_provider?.id_generator;
804
+ if (!idGenerator) {
805
+ return undefined;
806
+ }
807
+ if (idGenerator.random !== undefined) {
808
+ return new sdk_trace_1.RandomIdGenerator();
809
+ }
810
+ // Any other key is a third-party / custom id_generator type which we
811
+ // don't currently support. Warn and fall back to SDK default.
812
+ const unknownKeys = Object.keys(idGenerator).filter(k => k !== 'random');
813
+ if (unknownKeys.length > 0) {
814
+ api_1.diag.warn(`Unsupported id_generator type(s): ${unknownKeys.join(', ')}. Using default.`);
633
815
  }
634
816
  return undefined;
635
817
  }
636
- exports.getSpanLimitsFromConfiguration = getSpanLimitsFromConfiguration;
818
+ exports.getIdGeneratorFromConfiguration = getIdGeneratorFromConfiguration;
637
819
  function getMeterReadersFromConfiguration(config) {
638
820
  const metricReaders = [];
639
821
  config.meter_provider?.readers?.forEach(reader => {
@@ -699,8 +881,9 @@ function getAggregationType(aggregation) {
699
881
  return {
700
882
  type: sdk_metrics_1.AggregationType.EXPONENTIAL_HISTOGRAM,
701
883
  options: {
702
- recordMinMax: aggregation.base2_exponential_bucket_histogram.record_min_max ?? true,
703
- maxSize: aggregation.base2_exponential_bucket_histogram.max_size,
884
+ recordMinMax: aggregation.base2_exponential_bucket_histogram.record_min_max ??
885
+ undefined,
886
+ maxSize: aggregation.base2_exponential_bucket_histogram.max_size ?? undefined,
704
887
  },
705
888
  };
706
889
  }
@@ -714,7 +897,7 @@ function getAggregationType(aggregation) {
714
897
  type: sdk_metrics_1.AggregationType.SUM,
715
898
  };
716
899
  }
717
- api_1.diag.warn(`Unsupported aggregation type`);
900
+ api_1.diag.warn('Unsupported aggregation type');
718
901
  return undefined;
719
902
  }
720
903
  exports.getAggregationType = getAggregationType;
@@ -798,24 +981,37 @@ function getInstanceID(config) {
798
981
  }
799
982
  exports.getInstanceID = getInstanceID;
800
983
  const DEFAULT_RATIO = 1;
984
+ /**
985
+ * Returns the {@link Sampler} configured under `tracer_provider.sampler` in
986
+ * the declarative configuration, or `undefined` if none is set (in which case
987
+ * the SDK applies its default sampler).
988
+ */
989
+ function getSamplerFromConfiguration(config) {
990
+ const samplerConfig = config.tracer_provider?.sampler;
991
+ if (!samplerConfig) {
992
+ return undefined;
993
+ }
994
+ return buildSamplerFromConfig(samplerConfig);
995
+ }
996
+ exports.getSamplerFromConfiguration = getSamplerFromConfiguration;
801
997
  /**
802
998
  * Builds a {@link Sampler} from a {@link SamplerConfigModel} data model.
803
999
  * This allows sampler construction from declarative configuration.
804
1000
  */
805
- function buildSamplerFromConfig(config) {
806
- if (config.always_on !== undefined) {
807
- return new sdk_trace_base_1.AlwaysOnSampler();
1001
+ function buildSamplerFromConfig(samplerConfig) {
1002
+ if (samplerConfig.always_on !== undefined) {
1003
+ return new sdk_trace_1.AlwaysOnSampler();
808
1004
  }
809
- if (config.always_off !== undefined) {
810
- return new sdk_trace_base_1.AlwaysOffSampler();
1005
+ if (samplerConfig.always_off !== undefined) {
1006
+ return new sdk_trace_1.AlwaysOffSampler();
811
1007
  }
812
- if (config.trace_id_ratio_based !== undefined) {
813
- return new sdk_trace_base_1.TraceIdRatioBasedSampler(config.trace_id_ratio_based.ratio ?? DEFAULT_RATIO);
1008
+ if (samplerConfig.trace_id_ratio_based !== undefined) {
1009
+ return new sdk_trace_1.TraceIdRatioBasedSampler(samplerConfig.trace_id_ratio_based?.ratio ?? DEFAULT_RATIO);
814
1010
  }
815
- if (config.parent_based !== undefined) {
816
- const pb = config.parent_based;
817
- return new sdk_trace_base_1.ParentBasedSampler({
818
- root: pb.root ? buildSamplerFromConfig(pb.root) : new sdk_trace_base_1.AlwaysOnSampler(),
1011
+ if (samplerConfig.parent_based !== undefined) {
1012
+ const pb = samplerConfig.parent_based ?? {};
1013
+ return new sdk_trace_1.ParentBasedSampler({
1014
+ root: pb.root ? buildSamplerFromConfig(pb.root) : new sdk_trace_1.AlwaysOnSampler(),
819
1015
  remoteParentSampled: pb.remote_parent_sampled
820
1016
  ? buildSamplerFromConfig(pb.remote_parent_sampled)
821
1017
  : undefined,
@@ -830,8 +1026,55 @@ function buildSamplerFromConfig(config) {
830
1026
  : undefined,
831
1027
  });
832
1028
  }
833
- api_1.diag.error('Unknown sampler config, defaulting to ParentBased(AlwaysOn).');
834
- return new sdk_trace_base_1.ParentBasedSampler({ root: new sdk_trace_base_1.AlwaysOnSampler() });
1029
+ api_1.diag.warn('Unknown sampler config, defaulting to ParentBased(AlwaysOn).');
1030
+ return new sdk_trace_1.ParentBasedSampler({ root: new sdk_trace_1.AlwaysOnSampler() });
835
1031
  }
836
1032
  exports.buildSamplerFromConfig = buildSamplerFromConfig;
1033
+ /**
1034
+ * Warn if some props from a declarative config object have not been handled.
1035
+ *
1036
+ * This is intended to be used by `create*FromConfig()` functions. It is a low
1037
+ * tech mechanism to add awareness when a given valid config is not being
1038
+ * completely handled. This could help when properties are added to the
1039
+ * configuration schema. (A higher tech mechanism that wraps the parsed
1040
+ * configuration during `create()` and watches for untouched properties
1041
+ * might be nice.)
1042
+ */
1043
+ function checkConfigUse(name, props, handledProps) {
1044
+ if (!props)
1045
+ return;
1046
+ // Dev note: I'd use Set#difference, but that requires Node.js v22.
1047
+ const unhandledProps = Object.keys(props).filter(k => !handledProps.includes(k));
1048
+ if (unhandledProps.length > 0) {
1049
+ api_1.diag.warn(`Config warning: some specified ${name} configuration properties were not handled by SDK setup: ${JSON.stringify(unhandledProps)}`);
1050
+ }
1051
+ }
1052
+ /**
1053
+ * Return the single non-undefined entry in the given config object, or throw.
1054
+ *
1055
+ * It is common for Declarative Configuration to have config objects with
1056
+ * a single entry, e.g.
1057
+ *
1058
+ * "LogRecordProcessor": {
1059
+ * "type": "object",
1060
+ * "additionalProperties": {
1061
+ * "type": [
1062
+ * "object",
1063
+ * "null"
1064
+ * ]
1065
+ * },
1066
+ * "minProperties": 1,
1067
+ * "maxProperties": 1,
1068
+ *
1069
+ * The TypeScript types cannot express the minProperties/maxProperties from the
1070
+ * JSON schema. We guard against that here.
1071
+ */
1072
+ function mustSingleEntry(configObj, configTypeName) {
1073
+ const entries = Object.entries(configObj).filter(([_name, properties]) => properties !== undefined);
1074
+ if (entries.length !== 1) {
1075
+ const entryNames = entries.map(e => e[0]);
1076
+ throw Error(`invalid ${configTypeName} in configuration: must have exactly one entry: entries=${JSON.stringify(entryNames)}`);
1077
+ }
1078
+ return entries[0];
1079
+ }
837
1080
  //# sourceMappingURL=utils.js.map