@opentelemetry/sdk-node 0.219.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");
@@ -21,33 +21,39 @@ const exporter_logs_otlp_grpc_1 = require("@opentelemetry/exporter-logs-otlp-grp
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
23
  const otlp_grpc_exporter_base_1 = require("@opentelemetry/otlp-grpc-exporter-base");
24
+ const configuration_1 = require("@opentelemetry/configuration");
24
25
  const sdk_metrics_1 = require("@opentelemetry/sdk-metrics");
25
26
  const exporter_metrics_otlp_grpc_1 = require("@opentelemetry/exporter-metrics-otlp-grpc");
26
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");
27
29
  const exporter_metrics_otlp_proto_1 = require("@opentelemetry/exporter-metrics-otlp-proto");
28
30
  const sdk_logs_1 = require("@opentelemetry/sdk-logs");
29
31
  const fs = require("fs");
32
+ const util_1 = require("util");
33
+ const create_from_env_1 = require("./create-from-env");
30
34
  const RESOURCE_DETECTOR_ENVIRONMENT = 'env';
31
35
  const RESOURCE_DETECTOR_HOST = 'host';
32
36
  const RESOURCE_DETECTOR_OS = 'os';
33
37
  const RESOURCE_DETECTOR_PROCESS = 'process';
34
38
  const RESOURCE_DETECTOR_SERVICE_INSTANCE_ID = 'serviceinstance';
35
39
  function getResourceFromConfiguration(config) {
36
- if (config.resource && config.resource.attributes) {
37
- const attrs = {};
38
- for (let i = 0; i < config.resource.attributes.length; i++) {
39
- const a = config.resource.attributes[i];
40
- // https://github.com/open-telemetry/opentelemetry-configuration/issues/613
41
- // will likely clarify that entries with a `null` value should be ignored.
42
- if (a.value !== null) {
43
- attrs[a.name] = a.value;
44
- }
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;
45
52
  }
46
- return (0, resources_1.resourceFromAttributes)(attrs, {
47
- schemaUrl: config.resource.schema_url ?? undefined,
48
- });
49
53
  }
50
- return undefined;
54
+ return (0, resources_1.resourceFromAttributes)(attrs, {
55
+ schemaUrl: config.resource.schema_url ?? undefined,
56
+ });
51
57
  }
52
58
  exports.getResourceFromConfiguration = getResourceFromConfiguration;
53
59
  function getResourceDetectorsFromEnv() {
@@ -113,11 +119,11 @@ function getOtlpExporterFromEnv() {
113
119
  return new exporter_trace_otlp_proto_1.OTLPTraceExporter();
114
120
  }
115
121
  }
116
- function getSpanProcessorsFromEnv() {
122
+ function getSpanProcessorsFromEnv(selfObsMeterProvider) {
117
123
  const exportersMap = new Map([
118
124
  ['otlp', () => getOtlpExporterFromEnv()],
119
125
  ['zipkin', () => new exporter_zipkin_1.ZipkinExporter()],
120
- ['console', () => new sdk_trace_base_1.ConsoleSpanExporter()],
126
+ ['console', () => new sdk_trace_1.ConsoleSpanExporter()],
121
127
  ]);
122
128
  const exporters = [];
123
129
  const processors = [];
@@ -145,11 +151,11 @@ function getSpanProcessorsFromEnv() {
145
151
  }
146
152
  }
147
153
  for (const exp of exporters) {
148
- if (exp instanceof sdk_trace_base_1.ConsoleSpanExporter) {
149
- 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 }));
150
156
  }
151
157
  else {
152
- processors.push(new sdk_trace_base_1.BatchSpanProcessor(exp));
158
+ processors.push((0, create_from_env_1.createBatchSpanProcessorFromEnv)(exp, selfObsMeterProvider));
153
159
  }
154
160
  }
155
161
  if (exporters.length === 0) {
@@ -212,13 +218,50 @@ exports.getPropagatorFromEnv = getPropagatorFromEnv;
212
218
  * Get a propagator as defined by configuration model from configuration
213
219
  */
214
220
  function getPropagatorFromConfiguration(config) {
215
- const propagatorsValue = getKeyListFromObjectArray(config.propagator?.composite);
216
- if (propagatorsValue == null) {
217
- // return undefined to fall back to default
221
+ if (!config.propagator) {
218
222
  return undefined;
219
223
  }
220
- if (propagatorsValue.includes('none')) {
221
- 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
+ }
222
265
  }
223
266
  // Implementation note: this only contains specification required propagators that are actually hosted in this repo.
224
267
  // Any other propagators (like aws, aws-lambda, should go into `@opentelemetry/auto-configuration-propagators` instead).
@@ -232,22 +275,19 @@ function getPropagatorFromConfiguration(config) {
232
275
  ],
233
276
  ['jaeger', () => new propagator_jaeger_1.JaegerPropagator()],
234
277
  ]);
235
- // Values MUST be deduplicated in order to register a Propagator only once.
236
- const uniquePropagatorNames = Array.from(new Set(propagatorsValue));
237
278
  const validPropagators = [];
238
- uniquePropagatorNames.forEach(name => {
279
+ for (const [name] of kvs) {
239
280
  const propagator = propagatorsFactory.get(name)?.();
240
281
  if (!propagator) {
241
282
  api_1.diag.warn(`Propagator "${name}" requested through configuration is unavailable.`);
242
- return;
283
+ continue;
243
284
  }
244
285
  validPropagators.push(propagator);
245
- });
286
+ }
246
287
  if (validPropagators.length === 0) {
247
- // null to signal that the default should **not** be used in its place.
248
- return null;
288
+ return undefined;
249
289
  }
250
- else if (uniquePropagatorNames.length === 1) {
290
+ else if (validPropagators.length === 1) {
251
291
  return validPropagators[0];
252
292
  }
253
293
  else {
@@ -369,73 +409,120 @@ function getMetricProducersFromConfiguration(producers) {
369
409
  }
370
410
  const result = [];
371
411
  for (const producer of producers) {
372
- if (producer.opencensus) {
373
- try {
374
- const { OpenCensusMetricProducer,
375
- // eslint-disable-next-line @typescript-eslint/no-require-imports
376
- } = require('@opentelemetry/shim-opencensus');
377
- result.push(new OpenCensusMetricProducer());
378
- }
379
- catch {
380
- api_1.diag.warn('OpenCensus metric producer configured but @opentelemetry/shim-opencensus is not installed.');
381
- }
382
- }
383
- else {
384
- api_1.diag.warn('Unsupported metric producer configured.');
385
- }
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.`);
386
415
  }
387
416
  return result.length > 0 ? result : undefined;
388
417
  }
389
- function getPeriodicMetricReaderFromConfiguration(periodic) {
390
- if (periodic.exporter) {
391
- let exporter;
392
- if (periodic.exporter.otlp_http !== undefined) {
393
- const encoding = periodic.exporter.otlp_http?.encoding ?? 'protobuf';
394
- if (encoding === 'json') {
395
- exporter = new exporter_metrics_otlp_http_1.OTLPMetricExporter({
396
- compression: periodic.exporter.otlp_http?.compression === 'gzip'
397
- ? otlp_exporter_base_1.CompressionAlgorithm.GZIP
398
- : otlp_exporter_base_1.CompressionAlgorithm.NONE,
399
- });
400
- }
401
- else if (encoding === 'protobuf') {
402
- exporter = new exporter_metrics_otlp_proto_1.OTLPMetricExporter({
403
- compression: periodic.exporter.otlp_http?.compression === 'gzip'
404
- ? otlp_exporter_base_1.CompressionAlgorithm.GZIP
405
- : otlp_exporter_base_1.CompressionAlgorithm.NONE,
406
- });
407
- }
408
- else {
409
- api_1.diag.warn(`Unsupported OTLP metrics encoding: ${encoding}.`);
410
- }
411
- }
412
- if (periodic.exporter.otlp_grpc !== undefined) {
413
- exporter = new exporter_metrics_otlp_grpc_1.OTLPMetricExporter({
414
- compression: periodic.exporter.otlp_grpc?.compression === 'gzip'
415
- ? otlp_exporter_base_1.CompressionAlgorithm.GZIP
416
- : otlp_exporter_base_1.CompressionAlgorithm.NONE,
417
- });
418
- }
419
- const metricProducers = getMetricProducersFromConfiguration(periodic.producers);
420
- if (exporter) {
421
- // TODO(6425): add cardinality_limits
422
- return new sdk_metrics_1.PeriodicExportingMetricReader({
423
- exportIntervalMillis: periodic.interval ?? 60000,
424
- exportTimeoutMillis: periodic.timeout ?? 30000,
425
- exporter,
426
- metricProducers,
427
- });
428
- }
429
- if (periodic.exporter.console !== undefined) {
430
- return new sdk_metrics_1.PeriodicExportingMetricReader({
431
- exporter: new sdk_metrics_1.ConsoleMetricExporter(),
432
- metricProducers,
433
- });
434
- }
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);
500
+ }
501
+ if (exporter.console !== undefined) {
502
+ return new sdk_metrics_1.ConsoleMetricExporter();
435
503
  }
436
504
  api_1.diag.warn('Unsupported Metric Exporter.');
437
505
  return undefined;
438
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
+ }
439
526
  exports.getPeriodicMetricReaderFromConfiguration = getPeriodicMetricReaderFromConfiguration;
440
527
  /**
441
528
  * Get LoggerProviderConfig from environment variables.
@@ -463,77 +550,103 @@ function getBatchLogRecordProcessorConfigFromEnv() {
463
550
  }
464
551
  exports.getBatchLogRecordProcessorConfigFromEnv = getBatchLogRecordProcessorConfigFromEnv;
465
552
  function getBatchLogRecordProcessorFromEnv(exporter) {
466
- return new sdk_logs_1.BatchLogRecordProcessor(exporter, getBatchLogRecordProcessorConfigFromEnv());
553
+ return new sdk_logs_1.BatchLogRecordProcessor({
554
+ exporter,
555
+ ...getBatchLogRecordProcessorConfigFromEnv(),
556
+ });
467
557
  }
468
558
  exports.getBatchLogRecordProcessorFromEnv = getBatchLogRecordProcessorFromEnv;
469
- function getLogRecordExporter(exporter) {
470
- if (exporter.otlp_http !== undefined) {
471
- const cfg = exporter.otlp_http;
472
- const commonOpts = {
473
- compression: cfg?.compression === 'gzip'
474
- ? otlp_exporter_base_1.CompressionAlgorithm.GZIP
475
- : otlp_exporter_base_1.CompressionAlgorithm.NONE,
476
- url: cfg?.endpoint ?? undefined,
477
- headers: getHeadersFromConfiguration(cfg?.headers),
478
- timeoutMillis: validateExporterTimeout(cfg?.timeout),
479
- httpAgentOptions: getHttpAgentOptionsFromTls(cfg?.tls),
480
- };
481
- const encoding = cfg?.encoding ?? 'protobuf';
482
- if (encoding === 'json') {
483
- return new exporter_logs_otlp_http_1.OTLPLogExporter(commonOpts);
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'
590
+ ? otlp_exporter_base_1.CompressionAlgorithm.GZIP
591
+ : otlp_exporter_base_1.CompressionAlgorithm.NONE,
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
+ }
484
606
  }
485
- if (encoding === 'protobuf') {
486
- return new exporter_logs_otlp_proto_1.OTLPLogExporter(commonOpts);
607
+ case 'otlp_grpc': {
608
+ const props = properties;
609
+ return new exporter_logs_otlp_grpc_1.OTLPLogExporter({
610
+ compression: props?.compression === 'gzip'
611
+ ? otlp_exporter_base_1.CompressionAlgorithm.GZIP
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),
617
+ });
487
618
  }
488
- api_1.diag.warn(`Unsupported OTLP logs encoding: ${encoding}. Using http/protobuf.`);
489
- return new exporter_logs_otlp_proto_1.OTLPLogExporter(commonOpts);
490
- }
491
- else if (exporter.otlp_grpc !== undefined) {
492
- const cfg = exporter.otlp_grpc;
493
- return new exporter_logs_otlp_grpc_1.OTLPLogExporter({
494
- compression: cfg?.compression === 'gzip'
495
- ? otlp_exporter_base_1.CompressionAlgorithm.GZIP
496
- : otlp_exporter_base_1.CompressionAlgorithm.NONE,
497
- url: cfg?.endpoint ?? undefined,
498
- timeoutMillis: validateExporterTimeout(cfg?.timeout),
499
- credentials: getGrpcCredentialsFromTls(cfg?.tls),
500
- metadata: getGrpcMetadataFromHeaders(cfg?.headers),
501
- });
502
- }
503
- else if (exporter.console !== undefined) {
504
- 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}"`);
505
623
  }
506
- api_1.diag.warn('Unsupported Exporter value. No Log Record Exporter registered');
507
- return undefined;
508
624
  }
509
- exports.getLogRecordExporter = getLogRecordExporter;
510
- function getLogRecordProcessorsFromConfiguration(config) {
511
- const logRecordProcessors = [];
512
- config.logger_provider?.processors?.forEach(processor => {
513
- if (processor.batch) {
514
- const exporter = getLogRecordExporter(processor.batch.exporter);
515
- if (exporter) {
516
- logRecordProcessors.push(new sdk_logs_1.BatchLogRecordProcessor(exporter, {
517
- maxQueueSize: processor.batch.max_queue_size ?? undefined,
518
- maxExportBatchSize: processor.batch.max_export_batch_size ?? undefined,
519
- scheduledDelayMillis: processor.batch.schedule_delay ?? undefined,
520
- exportTimeoutMillis: processor.batch.export_timeout ?? undefined,
521
- }));
522
- }
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
+ });
523
639
  }
524
- if (processor.simple) {
525
- const exporter = getLogRecordExporter(processor.simple.exporter);
526
- if (exporter) {
527
- logRecordProcessors.push(new sdk_logs_1.SimpleLogRecordProcessor(exporter));
528
- }
640
+ case 'simple': {
641
+ const props = properties;
642
+ const exporter = createLogRecordExporterFromConfig(props.exporter);
643
+ return new sdk_logs_1.SimpleLogRecordProcessor({ exporter });
529
644
  }
530
- });
531
- if (logRecordProcessors.length > 0) {
532
- return logRecordProcessors;
645
+ default:
646
+ throw new Error(`unknown LogRecordProcessor name: "${name}"`);
533
647
  }
534
- return undefined;
535
648
  }
536
- exports.getLogRecordProcessorsFromConfiguration = getLogRecordProcessorsFromConfiguration;
649
+ exports.createLogRecordProcessorFromConfig = createLogRecordProcessorFromConfig;
537
650
  function getHeadersFromConfiguration(headers) {
538
651
  if (!headers) {
539
652
  return undefined;
@@ -652,7 +765,7 @@ function getSpanExporter(exporter) {
652
765
  });
653
766
  }
654
767
  else if (exporter.console !== undefined) {
655
- return new sdk_trace_base_1.ConsoleSpanExporter();
768
+ return new sdk_trace_1.ConsoleSpanExporter();
656
769
  }
657
770
  api_1.diag.warn('Unsupported Exporter value. No Span Exporter registered');
658
771
  return undefined;
@@ -664,7 +777,8 @@ function getSpanProcessorsFromConfiguration(config) {
664
777
  if (processor.batch) {
665
778
  const exporter = getSpanExporter(processor.batch.exporter);
666
779
  if (exporter) {
667
- spanProcessors.push(new sdk_trace_base_1.BatchSpanProcessor(exporter, {
780
+ spanProcessors.push(new sdk_trace_1.BatchSpanProcessor({
781
+ exporter,
668
782
  maxQueueSize: processor.batch.max_queue_size ?? undefined,
669
783
  maxExportBatchSize: processor.batch.max_export_batch_size ?? undefined,
670
784
  scheduledDelayMillis: processor.batch.schedule_delay ?? undefined,
@@ -675,7 +789,7 @@ function getSpanProcessorsFromConfiguration(config) {
675
789
  if (processor.simple) {
676
790
  const exporter = getSpanExporter(processor.simple.exporter);
677
791
  if (exporter) {
678
- spanProcessors.push(new sdk_trace_base_1.SimpleSpanProcessor(exporter));
792
+ spanProcessors.push(new sdk_trace_1.SimpleSpanProcessor({ exporter }));
679
793
  }
680
794
  }
681
795
  });
@@ -685,26 +799,23 @@ function getSpanProcessorsFromConfiguration(config) {
685
799
  return undefined;
686
800
  }
687
801
  exports.getSpanProcessorsFromConfiguration = getSpanProcessorsFromConfiguration;
688
- function getSpanLimitsFromConfiguration(config) {
689
- if (config.tracer_provider?.limits) {
690
- const limitsConfig = config.tracer_provider.limits;
691
- const spanLimits = {};
692
- spanLimits.attributeCountLimit = limitsConfig.attribute_count_limit ?? 128;
693
- spanLimits.eventCountLimit = limitsConfig.event_count_limit ?? 128;
694
- spanLimits.linkCountLimit = limitsConfig.link_count_limit ?? 128;
695
- spanLimits.attributePerLinkCountLimit =
696
- limitsConfig.link_attribute_count_limit ?? 128;
697
- spanLimits.attributePerEventCountLimit =
698
- limitsConfig.event_attribute_count_limit ?? 128;
699
- if (limitsConfig.attribute_value_length_limit != null) {
700
- spanLimits.attributeValueLengthLimit =
701
- limitsConfig.attribute_value_length_limit;
702
- }
703
- 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.`);
704
815
  }
705
816
  return undefined;
706
817
  }
707
- exports.getSpanLimitsFromConfiguration = getSpanLimitsFromConfiguration;
818
+ exports.getIdGeneratorFromConfiguration = getIdGeneratorFromConfiguration;
708
819
  function getMeterReadersFromConfiguration(config) {
709
820
  const metricReaders = [];
710
821
  config.meter_provider?.readers?.forEach(reader => {
@@ -870,24 +981,37 @@ function getInstanceID(config) {
870
981
  }
871
982
  exports.getInstanceID = getInstanceID;
872
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;
873
997
  /**
874
998
  * Builds a {@link Sampler} from a {@link SamplerConfigModel} data model.
875
999
  * This allows sampler construction from declarative configuration.
876
1000
  */
877
1001
  function buildSamplerFromConfig(samplerConfig) {
878
1002
  if (samplerConfig.always_on !== undefined) {
879
- return new sdk_trace_base_1.AlwaysOnSampler();
1003
+ return new sdk_trace_1.AlwaysOnSampler();
880
1004
  }
881
1005
  if (samplerConfig.always_off !== undefined) {
882
- return new sdk_trace_base_1.AlwaysOffSampler();
1006
+ return new sdk_trace_1.AlwaysOffSampler();
883
1007
  }
884
1008
  if (samplerConfig.trace_id_ratio_based !== undefined) {
885
- return new sdk_trace_base_1.TraceIdRatioBasedSampler(samplerConfig.trace_id_ratio_based?.ratio ?? DEFAULT_RATIO);
1009
+ return new sdk_trace_1.TraceIdRatioBasedSampler(samplerConfig.trace_id_ratio_based?.ratio ?? DEFAULT_RATIO);
886
1010
  }
887
1011
  if (samplerConfig.parent_based !== undefined) {
888
1012
  const pb = samplerConfig.parent_based ?? {};
889
- return new sdk_trace_base_1.ParentBasedSampler({
890
- root: pb.root ? buildSamplerFromConfig(pb.root) : new sdk_trace_base_1.AlwaysOnSampler(),
1013
+ return new sdk_trace_1.ParentBasedSampler({
1014
+ root: pb.root ? buildSamplerFromConfig(pb.root) : new sdk_trace_1.AlwaysOnSampler(),
891
1015
  remoteParentSampled: pb.remote_parent_sampled
892
1016
  ? buildSamplerFromConfig(pb.remote_parent_sampled)
893
1017
  : undefined,
@@ -902,8 +1026,55 @@ function buildSamplerFromConfig(samplerConfig) {
902
1026
  : undefined,
903
1027
  });
904
1028
  }
905
- api_1.diag.error('Unknown sampler config, defaulting to ParentBased(AlwaysOn).');
906
- 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() });
907
1031
  }
908
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
+ }
909
1080
  //# sourceMappingURL=utils.js.map