Skip to content

Commit

Permalink
feat(resources): use functions over constants for default and empty r…
Browse files Browse the repository at this point in the history
…esources (#5467)
  • Loading branch information
pichlermarc authored Feb 19, 2025
1 parent faeae98 commit 5ccf380
Show file tree
Hide file tree
Showing 32 changed files with 123 additions and 125 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,8 @@ For semantic convention package changes, see the [semconv CHANGELOG](packages/se
* Renames `Resource` class to `ResourceImpl` and makes it package-private
* Renames `IResource` interface to `Resource`
* Export function `resourceFromAttributes` to create a `Resource` from a `DetectedAttributes` object
* Export function `defaultResource` to create a default resource [#5467](/~https://github.com/open-telemetry/opentelemetry-js/pull/5467) @pichlermarc
* Export function `emptyResource` to create an empty resource [#5467](/~https://github.com/open-telemetry/opentelemetry-js/pull/5467) @pichlermarc
* Only export types and functions. This aids in cross-version compatibility and makes it more easily extensible in the future.
* feat(resources)!: do not read environment variables from window in browsers [#5466](/~https://github.com/open-telemetry/opentelemetry-js/pull/5466) @pichlermarc
* (user-facing): all configuration previously possible via `window.OTEL_*` is now not supported anymore
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import {
DetectedResource,
ResourceDetector,
ResourceDetectionConfig,
EMPTY_RESOURCE,
emptyResource,
} from '@opentelemetry/resources';
import { BROWSER_ATTRIBUTES, UserAgentData } from './types';

Expand All @@ -30,7 +30,7 @@ class BrowserDetector implements ResourceDetector {
detect(config?: ResourceDetectionConfig): DetectedResource {
const isBrowser = typeof navigator !== 'undefined';
if (!isBrowser) {
return EMPTY_RESOURCE;
return emptyResource();
}
const browserResource: Attributes = getBrowserAttributes();
return this._getResourceAttributes(browserResource, config);
Expand All @@ -53,7 +53,7 @@ class BrowserDetector implements ResourceDetector {
diag.debug(
'BrowserDetector failed: Unable to find required browser resources. '
);
return EMPTY_RESOURCE;
return emptyResource();
} else {
return { attributes: browserResource };
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
*/

import * as sinon from 'sinon';
import { DEFAULT_RESOURCE } from '@opentelemetry/resources';
import { defaultResource } from '@opentelemetry/resources';
import {
SEMRESATTRS_SERVICE_NAME,
SEMRESATTRS_TELEMETRY_SDK_LANGUAGE,
Expand All @@ -29,23 +29,19 @@ export function mockHrTime() {
sinon.useFakeTimers(mockedHrTimeMs);
}

export const serviceName = DEFAULT_RESOURCE.attributes[
SEMRESATTRS_SERVICE_NAME
]?.toString()
export const serviceName = defaultResource()
.attributes[SEMRESATTRS_SERVICE_NAME]?.toString()
.replace(/\\/g, '\\\\')
.replace(/\n/g, '\\n');
export const sdkLanguage = DEFAULT_RESOURCE.attributes[
SEMRESATTRS_TELEMETRY_SDK_LANGUAGE
]?.toString()
export const sdkLanguage = defaultResource()
.attributes[SEMRESATTRS_TELEMETRY_SDK_LANGUAGE]?.toString()
.replace(/\\/g, '\\\\')
.replace(/\n/g, '\\n');
export const sdkName = DEFAULT_RESOURCE.attributes[
SEMRESATTRS_TELEMETRY_SDK_NAME
]?.toString()
export const sdkName = defaultResource()
.attributes[SEMRESATTRS_TELEMETRY_SDK_NAME]?.toString()
.replace(/\\/g, '\\\\')
.replace(/\n/g, '\\n');
export const sdkVersion = DEFAULT_RESOURCE.attributes[
SEMRESATTRS_TELEMETRY_SDK_VERSION
]?.toString()
export const sdkVersion = defaultResource()
.attributes[SEMRESATTRS_TELEMETRY_SDK_VERSION]?.toString()
.replace(/\\/g, '\\\\')
.replace(/\n/g, '\\n');
4 changes: 2 additions & 2 deletions experimental/packages/opentelemetry-sdk-node/src/sdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import {
registerInstrumentations,
} from '@opentelemetry/instrumentation';
import {
DEFAULT_RESOURCE,
defaultResource,
detectResources,
envDetector,
hostDetector,
Expand Down Expand Up @@ -245,7 +245,7 @@ export class NodeSDK {

this._configuration = configuration;

this._resource = configuration.resource ?? DEFAULT_RESOURCE;
this._resource = configuration.resource ?? defaultResource();
this._autoDetectResources = configuration.autoDetectResources ?? true;
if (!this._autoDetectResources) {
this._resourceDetectors = [];
Expand Down
4 changes: 2 additions & 2 deletions experimental/packages/opentelemetry-sdk-node/test/sdk.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ import {
hostDetector,
serviceInstanceIdDetector,
DetectedResource,
DEFAULT_RESOURCE,
defaultResource,
} from '@opentelemetry/resources';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
import { logs, ProxyLoggerProvider } from '@opentelemetry/api-logs';
Expand Down Expand Up @@ -956,7 +956,7 @@ describe('Node SDK', () => {
const resource = sdk['_resource'];
await resource.waitForAsyncAttributes?.();

assert.deepStrictEqual(resource, DEFAULT_RESOURCE);
assert.deepStrictEqual(resource, defaultResource());
await sdk.shutdown();
});
});
Expand Down
4 changes: 2 additions & 2 deletions experimental/packages/sampler-jaeger-remote/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ To integrate the Jaeger Remote Sampler with your application, configure it with

```javascript
const { JaegerRemoteSampler } = require('@opentelemetry/sampler-jaeger-remote');
const { DEFAULT_RESOURCE, resourceFromAttributes } = require('@opentelemetry/resources');
const { defaultResource, resourceFromAttributes } = require('@opentelemetry/resources');
const { NodeTracerProvider } = require('@opentelemetry/node');

// Jaeger agent endpoint
Expand All @@ -30,7 +30,7 @@ const sampler = new JaegerRemoteSampler({
poolingInterval: 60000 // 60 seconds
});
const provider = new NodeTracerProvider({
resource: DEFAULT_RESOURCE.merge(resourceFromAttributes({
resource: defaultResource().merge(resourceFromAttributes({
'service.name': 'your-service-name'
})),
sampler
Expand Down
4 changes: 2 additions & 2 deletions experimental/packages/sdk-logs/src/LoggerProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
import { diag } from '@opentelemetry/api';
import type * as logsAPI from '@opentelemetry/api-logs';
import { NOOP_LOGGER } from '@opentelemetry/api-logs';
import { DEFAULT_RESOURCE } from '@opentelemetry/resources';
import { defaultResource } from '@opentelemetry/resources';
import { BindOnceFuture, merge } from '@opentelemetry/core';

import type { LoggerProviderConfig } from './types';
Expand All @@ -34,7 +34,7 @@ export class LoggerProvider implements logsAPI.LoggerProvider {

constructor(config: LoggerProviderConfig = {}) {
const mergedConfig = merge({}, loadDefaultConfig(), config);
const resource = config.resource ?? DEFAULT_RESOURCE;
const resource = config.resource ?? defaultResource();
this._sharedState = new LoggerProviderSharedState(
resource,
mergedConfig.forceFlushTimeoutMillis,
Expand Down
4 changes: 2 additions & 2 deletions experimental/packages/sdk-logs/test/common/LogRecord.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import {
import * as logsAPI from '@opentelemetry/api-logs';
import type { HrTime } from '@opentelemetry/api';
import { hrTimeToMilliseconds, timeInputToHrTime } from '@opentelemetry/core';
import { DEFAULT_RESOURCE } from '@opentelemetry/resources';
import { defaultResource } from '@opentelemetry/resources';

import {
LogRecordLimits,
Expand All @@ -47,7 +47,7 @@ const setup = (logRecordLimits?: LogRecordLimits, data?: logsAPI.LogRecord) => {
version: 'test version',
schemaUrl: 'test schema url',
};
const resource = DEFAULT_RESOURCE;
const resource = defaultResource();
const sharedState = new LoggerProviderSharedState(
resource,
Infinity,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
import { logs, NoopLogger } from '@opentelemetry/api-logs';
import { diag } from '@opentelemetry/api';
import {
DEFAULT_RESOURCE,
defaultResource,
resourceFromAttributes,
} from '@opentelemetry/resources';
import * as assert from 'assert';
Expand Down Expand Up @@ -55,7 +55,7 @@ describe('LoggerProvider', () => {
it('should have default resource if not pass', () => {
const provider = new LoggerProvider();
const { resource } = provider['_sharedState'];
assert.deepStrictEqual(resource, DEFAULT_RESOURCE);
assert.deepStrictEqual(resource, defaultResource());
});

it('should not have default resource if passed', function () {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ import { BatchLogRecordProcessorBase } from '../../../src/export/BatchLogRecordP
import { reconfigureLimits } from '../../../src/config';
import { LoggerProviderSharedState } from '../../../src/internal/LoggerProviderSharedState';
import {
DEFAULT_RESOURCE,
defaultResource,
Resource,
resourceFromAttributes,
} from '@opentelemetry/resources';
Expand All @@ -47,7 +47,7 @@ const createLogRecord = (
resource?: Resource
): LogRecord => {
const sharedState = new LoggerProviderSharedState(
resource || DEFAULT_RESOURCE,
resource || defaultResource(),
Infinity,
reconfigureLimits(limits ?? {})
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import {
setGlobalErrorHandler,
} from '@opentelemetry/core';
import {
DEFAULT_RESOURCE,
defaultResource,
Resource,
resourceFromAttributes,
} from '@opentelemetry/resources';
Expand All @@ -39,7 +39,7 @@ import { TestExporterWithDelay } from './TestExporterWithDelay';

const setup = (exporter: LogRecordExporter, resource?: Resource) => {
const sharedState = new LoggerProviderSharedState(
resource || DEFAULT_RESOURCE,
resource || defaultResource(),
Infinity,
reconfigureLimits({})
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
*/

import * as oc from '@opencensus/core';
import { EMPTY_RESOURCE } from '@opentelemetry/resources';
import { emptyResource } from '@opentelemetry/resources';
import {
CollectionResult,
MetricData,
Expand Down Expand Up @@ -80,7 +80,7 @@ export class OpenCensusMetricProducer implements MetricProducer {
errors: [],
resourceMetrics: {
// Resource is ignored by the SDK, it just uses the SDK's resource
resource: EMPTY_RESOURCE,
resource: emptyResource(),
scopeMetrics,
},
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

import * as oc from '@opencensus/core';
import { ValueType } from '@opentelemetry/api';
import { EMPTY_RESOURCE } from '@opentelemetry/resources';
import { emptyResource } from '@opentelemetry/resources';
import {
AggregationTemporality,
DataPointType,
Expand All @@ -43,7 +43,7 @@ describe('OpenCensusMetricProducer', () => {

assert.deepStrictEqual(
resourceMetrics.resourceMetrics.resource,
EMPTY_RESOURCE
emptyResource()
);
});

Expand Down
8 changes: 4 additions & 4 deletions packages/opentelemetry-exporter-jaeger/test/transform.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import * as assert from 'assert';
import { spanToThrift } from '../src/transform';
import { ReadableSpan } from '@opentelemetry/sdk-trace-base';
import {
EMPTY_RESOURCE,
emptyResource,
resourceFromAttributes,
} from '@opentelemetry/resources';
import * as api from '@opentelemetry/api';
Expand Down Expand Up @@ -180,7 +180,7 @@ describe('transform', () => {
links: [],
events: [],
duration: [32, 800000000],
resource: EMPTY_RESOURCE,
resource: emptyResource(),
instrumentationScope: {
name: 'default',
version: '0.0.1',
Expand Down Expand Up @@ -254,7 +254,7 @@ describe('transform', () => {
],
events: [],
duration: [32, 800000000],
resource: EMPTY_RESOURCE,
resource: emptyResource(),
instrumentationScope: {
name: 'default',
version: '0.0.1',
Expand Down Expand Up @@ -302,7 +302,7 @@ describe('transform', () => {
links: [],
events: [],
duration: [32, 800000000],
resource: EMPTY_RESOURCE,
resource: emptyResource(),
instrumentationScope: {
name: 'default',
version: '0.0.1',
Expand Down
12 changes: 6 additions & 6 deletions packages/opentelemetry-exporter-zipkin/test/node/zipkin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import {
} from '@opentelemetry/core';
import * as api from '@opentelemetry/api';
import {
EMPTY_RESOURCE,
emptyResource,
resourceFromAttributes,
} from '@opentelemetry/resources';
import { ZipkinExporter } from '../../src';
Expand Down Expand Up @@ -57,7 +57,7 @@ function getReadableSpan() {
attributes: {},
links: [],
events: [],
resource: EMPTY_RESOURCE,
resource: emptyResource(),
instrumentationScope: { name: 'default', version: '0.0.1' },
droppedAttributesCount: 0,
droppedEventsCount: 0,
Expand Down Expand Up @@ -172,7 +172,7 @@ describe('Zipkin Exporter - node', () => {
attributes: { key3: 'value3' },
},
],
resource: EMPTY_RESOURCE,
resource: emptyResource(),
instrumentationScope: { name: 'default', version: '0.0.1' },
droppedAttributesCount: 0,
droppedEventsCount: 0,
Expand All @@ -198,7 +198,7 @@ describe('Zipkin Exporter - node', () => {
attributes: {},
links: [],
events: [],
resource: EMPTY_RESOURCE,
resource: emptyResource(),
instrumentationScope: { name: 'default', version: '0.0.1' },
droppedAttributesCount: 0,
droppedEventsCount: 0,
Expand Down Expand Up @@ -495,7 +495,7 @@ describe('Zipkin Exporter - node', () => {
attributes: { key3: 'value3' },
},
],
resource: EMPTY_RESOURCE,
resource: emptyResource(),
instrumentationScope: { name: 'default', version: '0.0.1' },
droppedAttributesCount: 0,
droppedEventsCount: 0,
Expand All @@ -521,7 +521,7 @@ describe('Zipkin Exporter - node', () => {
},
links: [],
events: [],
resource: EMPTY_RESOURCE,
resource: emptyResource(),
instrumentationScope: { name: 'default', version: '0.0.1' },
droppedAttributesCount: 0,
droppedEventsCount: 0,
Expand Down
19 changes: 12 additions & 7 deletions packages/opentelemetry-resources/src/ResourceImpl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,10 +147,15 @@ export function resourceFromDetectedResource(
return new ResourceImpl(detectedResource);
}

export const EMPTY_RESOURCE = resourceFromAttributes({});
export const DEFAULT_RESOURCE = resourceFromAttributes({
[ATTR_SERVICE_NAME]: defaultServiceName(),
[ATTR_TELEMETRY_SDK_LANGUAGE]: SDK_INFO[ATTR_TELEMETRY_SDK_LANGUAGE],
[ATTR_TELEMETRY_SDK_NAME]: SDK_INFO[ATTR_TELEMETRY_SDK_NAME],
[ATTR_TELEMETRY_SDK_VERSION]: SDK_INFO[ATTR_TELEMETRY_SDK_VERSION],
});
export function emptyResource(): Resource {
return resourceFromAttributes({});
}

export function defaultResource(): Resource {
return resourceFromAttributes({
[ATTR_SERVICE_NAME]: defaultServiceName(),
[ATTR_TELEMETRY_SDK_LANGUAGE]: SDK_INFO[ATTR_TELEMETRY_SDK_LANGUAGE],
[ATTR_TELEMETRY_SDK_NAME]: SDK_INFO[ATTR_TELEMETRY_SDK_NAME],
[ATTR_TELEMETRY_SDK_VERSION]: SDK_INFO[ATTR_TELEMETRY_SDK_VERSION],
});
}
6 changes: 3 additions & 3 deletions packages/opentelemetry-resources/src/detect-resources.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

import { diag } from '@opentelemetry/api';
import { Resource } from './Resource';
import { EMPTY_RESOURCE, resourceFromDetectedResource } from './ResourceImpl';
import { emptyResource, resourceFromDetectedResource } from './ResourceImpl';
import { ResourceDetectionConfig } from './config';

/**
Expand All @@ -34,7 +34,7 @@ export const detectResources = (
return resource;
} catch (e) {
diag.debug(`${d.constructor.name} failed: ${e.message}`);
return EMPTY_RESOURCE;
return emptyResource();
}
});

Expand All @@ -43,7 +43,7 @@ export const detectResources = (

return resources.reduce(
(acc, resource) => acc.merge(resource),
EMPTY_RESOURCE
emptyResource()
);
};

Expand Down
Loading

0 comments on commit 5ccf380

Please sign in to comment.