Skip to content

Commit

Permalink
chore: indent the code with eslint (open-telemetry#2923)
Browse files Browse the repository at this point in the history
* chore: indent the code with eslint

* chore: update changelog

* chore: add lint switch case indent

Co-authored-by: legendecas <legendecas@gmail.com>
  • Loading branch information
2 people authored and aabmass committed Apr 28, 2022
1 parent ce7e98f commit 788e9af
Show file tree
Hide file tree
Showing 5 changed files with 115 additions and 25 deletions.
10 changes: 5 additions & 5 deletions experimental/packages/opentelemetry-sdk-node/src/sdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import { NodeTracerConfig, NodeTracerProvider } from '@opentelemetry/sdk-trace-n
import { awsEc2Detector } from '@opentelemetry/resource-detector-aws';
import { gcpDetector } from '@opentelemetry/resource-detector-gcp';
import {
detectResources,
detectResourcesSync,
envDetector,
processDetector,
Resource,
Expand Down Expand Up @@ -115,13 +115,13 @@ export class NodeSDK {
}

/** Detect resource attributes */
public async detectResources(config?: ResourceDetectionConfig): Promise<void> {
public detectResources(config?: ResourceDetectionConfig): void {
const internalConfig: ResourceDetectionConfig = {
detectors: [awsEc2Detector, gcpDetector, envDetector, processDetector],
...config,
};

this.addResource(await detectResources(internalConfig));
this.addResource(detectResourcesSync(internalConfig));
}

/** Manually add a resource */
Expand All @@ -132,9 +132,9 @@ export class NodeSDK {
/**
* Once the SDK has been configured, call this method to construct SDK components and register them with the OpenTelemetry API.
*/
public async start(): Promise<void> {
public start(): void {
if (this._autoDetectResources) {
await this.detectResources();
this.detectResources();
}

if (this._tracerProviderConfig) {
Expand Down
25 changes: 15 additions & 10 deletions experimental/packages/opentelemetry-sdk-node/test/sdk.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ describe('Node SDK', () => {
autoDetectResources: false,
});

await sdk.start();
sdk.start();

assert.strictEqual(context['_getContextManager'](), ctxManager, 'context manager should not change');
assert.strictEqual(propagation['_getGlobalPropagator'](), propagator, 'propagator should not change');
Expand All @@ -126,7 +126,7 @@ describe('Node SDK', () => {
autoDetectResources: false,
});

await sdk.start();
sdk.start();

assert.ok(metrics.getMeterProvider() instanceof NoopMeterProvider);

Expand All @@ -149,7 +149,7 @@ describe('Node SDK', () => {
autoDetectResources: false,
});

await sdk.start();
sdk.start();

assert.ok(metrics.getMeterProvider() instanceof NoopMeterProvider);

Expand All @@ -176,7 +176,7 @@ describe('Node SDK', () => {
autoDetectResources: false,
});

await sdk.start();
sdk.start();

assert.strictEqual(context['_getContextManager'](), ctxManager, 'context manager should not change');
assert.strictEqual(propagation['_getGlobalPropagator'](), propagator, 'propagator should not change');
Expand Down Expand Up @@ -232,8 +232,9 @@ describe('Node SDK', () => {
.put(AWS_TOKEN_PATH)
.matchHeader(AWS_METADATA_TTL_HEADER, '60')
.replyWithError({ code: 'ENOTFOUND' });
await sdk.detectResources();
sdk.detectResources();
const resource = sdk['_resource'];
await resource.waitForAsyncAttributes();

awsScope.done();
gcpSecondaryScope.done();
Expand Down Expand Up @@ -271,8 +272,9 @@ describe('Node SDK', () => {
.get(AWS_HOST_PATH)
.matchHeader(AWS_METADATA_TOKEN_HEADER, mockedTokenResponse)
.reply(200, () => mockedHostResponse);
await sdk.detectResources();
sdk.detectResources();
const resource: Resource = sdk['_resource'];
await resource.waitForAsyncAttributes().catch(() => {});
awsScope.done();

assertCloudResource(resource, {
Expand Down Expand Up @@ -304,10 +306,11 @@ describe('Node SDK', () => {
const sdk = new NodeSDK({
autoDetectResources: true,
});
await sdk.detectResources({
sdk.detectResources({
detectors: [awsEc2Detector],
});
const resource: Resource = sdk['_resource'];
await resource.waitForAsyncAttributes().catch(() => {});
assert.ok(resource);
assert.deepStrictEqual(resource, Resource.empty());

Expand All @@ -321,8 +324,9 @@ describe('Node SDK', () => {
autoDetectResources: true,
});
const stub = Sinon.stub(awsEc2Detector, 'detect').throws();
await sdk.detectResources();
sdk.detectResources();
const resource = sdk['_resource'];
await resource.waitForAsyncAttributes().catch(() => {});

assertServiceResource(resource, {
instanceId: '627cc493',
Expand Down Expand Up @@ -371,7 +375,8 @@ describe('Node SDK', () => {
DiagLogLevel.VERBOSE
);

await sdk.detectResources();
sdk.detectResources();
await sdk['_resource'].waitForAsyncAttributes().catch(() => {});

// Test for AWS and GCP Detector failure
assert.ok(
Expand Down Expand Up @@ -416,7 +421,7 @@ describe('Node SDK', () => {
DiagLogLevel.DEBUG
);

await sdk.detectResources();
sdk.detectResources();

assert.ok(
callArgsContains(
Expand Down
40 changes: 35 additions & 5 deletions packages/opentelemetry-resources/src/Resource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ import { defaultServiceName } from './platform';
*/
export class Resource {
static readonly EMPTY = new Resource({});
private _attributes: ResourceAttributes;
private asyncAttributesPromise: Promise<ResourceAttributes>;

/**
* Returns an empty Resource
Expand All @@ -34,7 +36,8 @@ export class Resource {
}

/**
* Returns a Resource that indentifies the SDK in use.
*
* Returns a Resource that indentifies the SDK in use.
*/
static default(): Resource {
return new Resource({
Expand All @@ -54,8 +57,28 @@ export class Resource {
* information about the entity as numbers, strings or booleans
* TODO: Consider to add check/validation on attributes.
*/
readonly attributes: ResourceAttributes
) {}
attributes: ResourceAttributes,
asyncAttributesPromise: Promise<ResourceAttributes> = Promise.resolve({}),
) {
this._attributes = attributes;
this.asyncAttributesPromise = asyncAttributesPromise.then(asyncAttributes => {
this._attributes = Object.assign({}, this._attributes, asyncAttributes);
return asyncAttributes;
});
}

get attributes(): ResourceAttributes {
return this._attributes;
}

/**
* Returns a promise that resolves when all async attributes have finished being added to
* this Resource's attributes. This is useful in exporters to block until resource detection
* has finished.
*/
async waitForAsyncAttributes(): Promise<void> {
await this.asyncAttributesPromise;
}

/**
* Returns a new, merged {@link Resource} by merging the current Resource
Expand All @@ -66,14 +89,21 @@ export class Resource {
* @returns the newly merged Resource.
*/
merge(other: Resource | null): Resource {
if (!other || !Object.keys(other.attributes).length) return this;
if (!other) return this;

// SpanAttributes from resource overwrite attributes from other resource.
const mergedAttributes = Object.assign(
{},
this.attributes,
other.attributes
);
return new Resource(mergedAttributes);
return new Resource(
mergedAttributes,
Promise.all([this.asyncAttributesPromise.catch(() => ({})), other.asyncAttributesPromise.catch(() => ({}))]).then(
([thisAttributes, otherAttributes]) => {
return Object.assign({}, thisAttributes, otherAttributes);
}
),
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,11 @@ import { diag } from '@opentelemetry/api';
import * as util from 'util';

/**
* Runs all resource detectors and returns the results merged into a single
* Resource.
* Runs all resource detectors and returns the results merged into a single Resource. Promise
* does not resolve until all of the underlying detectors have resolved, unlike
* detectResourcesSync.
*
* @deprecated use detectResourceSync() instead.
* @param config Configuration for resource detection
*/
export const detectResources = async (
Expand Down Expand Up @@ -53,6 +55,58 @@ export const detectResources = async (
};


/**
* Runs all resource detectors synchronously, merging their results. Any asynchronous
* attributes will be merged together in-order after they resolve.
*
* @param config Configuration for resource detection
*/
export const detectResourcesSync = (
config: ResourceDetectionConfig = {}
): Resource => {
const internalConfig: ResourceDetectionConfig = Object.assign(config);

const resources: Resource[] = (internalConfig.detectors ?? []).map(d => {
try {
const resourceOrPromise = d.detect(internalConfig);
let resource: Resource;
if (resourceOrPromise instanceof Promise) {
diag.info('Resource detector %s should return a Resource directly instead of a promise.', d.constructor.name);
const createPromise = async () => {
const resolved = await resourceOrPromise;
await resolved.waitForAsyncAttributes();
return resolved.attributes;
};
resource = new Resource({}, createPromise());
} else {
resource = resourceOrPromise;
}

resource.waitForAsyncAttributes().then(() => {
diag.debug(`${d.constructor.name} found resource.`, resource);
}).catch(e => {
diag.debug(`${d.constructor.name} failed: ${e.message}`);
});

return resource;
} catch (e) {
diag.debug(`${d.constructor.name} failed: ${e.message}`);
return Resource.empty();
}
});


const mergedResources = resources.reduce(
(acc, resource) => acc.merge(resource),
Resource.empty()
);
void mergedResources.waitForAsyncAttributes().then(() => {
// Future check if verbose logging is enabled issue #1903
logResources(resources);
});
return mergedResources;
};

/**
* Writes debug information about the detected resources to the logger defined in the resource detection config, if one is provided.
*
Expand Down
7 changes: 4 additions & 3 deletions packages/opentelemetry-resources/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,10 @@ export interface ResourceAttributes {
}

/**
* Interface for a Resource Detector. In order to detect resources in parallel
* a detector returns a Promise containing a Resource.
* Interface for a Resource Detector. In order to detect resources asynchronously, a detector
* can pass a Promise as the second parameter to the Resource constructor. Returning a
* Promise<Resource> is deprecated in favor of this approach.
*/
export interface Detector {
detect(config?: ResourceDetectionConfig): Promise<Resource>;
detect(config?: ResourceDetectionConfig): Promise<Resource> | Resource;
}

0 comments on commit 788e9af

Please sign in to comment.