Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(scope-manager): implements AsyncHooks Scope Manager #103

Merged
merged 7 commits into from
Jul 25, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/opentelemetry-node-tracer/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@
},
"dependencies": {
"@opentelemetry/core": "^0.0.1",
"@opentelemetry/context-async-hooks": "^0.0.1",
"@opentelemetry/scope-async-hooks": "^0.0.1",
"@opentelemetry/scope-base": "^0.0.1",
"@opentelemetry/types": "^0.0.1"
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
{
"name": "@opentelemetry/context-async-hooks",
"name": "@opentelemetry/scope-async-hooks",
"version": "0.0.1",
"description": "OpenTelemetry AsyncHooks-based Context Manager",
"description": "OpenTelemetry AsyncHooks-based Scope Manager",
"main": "build/src/index.js",
"types": "build/src/index.d.ts",
"repository": "open-telemetry/opentelemetry-js",
"scripts": {
"test": "c8 ts-mocha -p tsconfig.json test/**/*.ts",
"tdd": "yarn test -- --watch-extensions ts --watch",
"codecov": "c8 report --reporter=json && codecov -f coverage/*.json -p ../../",
"clean": "rimraf build/*",
"check": "gts check",
"compile": "tsc -p .",
Expand Down Expand Up @@ -40,6 +41,7 @@
"devDependencies": {
"@types/mocha": "^5.2.5",
"@types/node": "^12.0.10",
"@types/shimmer": "^1.0.1",
"c8": "^5.0.1",
"codecov": "^3.1.0",
"gts": "^1.0.0",
Expand All @@ -48,5 +50,7 @@
"ts-node": "^8.0.0",
"typescript": "^3.4.5"
},
"dependencies": {}
"dependencies": {
"@opentelemetry/scope-base": "^0.0.1"
}
}
114 changes: 114 additions & 0 deletions packages/opentelemetry-scope-async-hooks/src/AsyncHooksScopeManager.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
/**
* Copyright 2019, OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { ScopeManager } from '@opentelemetry/scope-base';
import * as asyncHooks from 'async_hooks';

export class AsyncHooksScopeManager implements ScopeManager {
private _asyncHook: asyncHooks.AsyncHook;
private _scopes: { [uid: number]: unknown } = Object.create(null);

constructor() {
this._asyncHook = asyncHooks.createHook({
init: this._init.bind(this),
destroy: this._destroy.bind(this),
promiseResolve: this._destroy.bind(this),
});
}

active(): unknown {
vmarchaud marked this conversation as resolved.
Show resolved Hide resolved
return this._scopes[asyncHooks.executionAsyncId()] || null;
}

with<T extends (...args: unknown[]) => ReturnType<T>>(
vmarchaud marked this conversation as resolved.
Show resolved Hide resolved
scope: unknown,
fn: T
): ReturnType<T> {
const uid = asyncHooks.executionAsyncId();
const oldScope = this._scopes[uid];
this._scopes[uid] = scope;
try {
return fn();
} catch (err) {
throw err;
} finally {
if (oldScope === undefined) {
this._destroy(uid);
} else {
this._scopes[uid] = oldScope;
}
}
}

bind<T>(target: T, scope?: unknown): T {
vmarchaud marked this conversation as resolved.
Show resolved Hide resolved
// if no specific scope to propagate is given, we use the current one
if (scope === undefined) {
scope = this.active();
}
if (typeof target === 'function') {
return this._bindFunction(target, scope);
}
return target;
}

enable(): this {
this._asyncHook.enable();
return this;
}

disable(): this {
this._asyncHook.disable();
this._scopes = {};
return this;
}

private _bindFunction<T extends Function>(target: T, scope?: unknown): T {
const manager = this;
const contextWrapper = function(this: {}) {
vmarchaud marked this conversation as resolved.
Show resolved Hide resolved
return manager.with(scope, () => target.apply(this, arguments));
};
Object.defineProperty(contextWrapper, 'length', {
vmarchaud marked this conversation as resolved.
Show resolved Hide resolved
enumerable: false,
configurable: true,
writable: false,
value: target.length,
});
/**
* It isnt possible to tell Typescript that contextWrapper is the same as T
* so we forced to cast as any here.
*/
// tslint:disable-next-line:no-any
return contextWrapper as any;
}

/**
* Init hook will be called when userland create a async scope, setting the
* scope as the current one if it exist.
* @param uid id of the async scope
*/
private _init(uid: number) {
this._scopes[uid] = this._scopes[asyncHooks.executionAsyncId()];
}

/**
* Destroy hook will be called when a given scope is no longer used so we can
* remove its attached scope.
* @param uid uid of the async scope
*/
private _destroy(uid: number) {
delete this._scopes[uid];
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,5 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/

export * from './AsyncHooksScopeManager';
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
/**
* Copyright 2019, OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import * as assert from 'assert';
import { AsyncHooksScopeManager } from '../../src';

describe('AsyncHooksScopeManager', () => {
let scopeManager: AsyncHooksScopeManager;

afterEach(() => {
scopeManager.disable();
scopeManager.enable();
});

describe('.enable()', () => {
it('should work', () => {
assert.doesNotThrow(() => {
scopeManager = new AsyncHooksScopeManager();
assert(scopeManager.enable() === scopeManager, 'should return this');
});
});
});

describe('.disable()', () => {
it('should work', () => {
assert.doesNotThrow(() => {
assert(scopeManager.disable() === scopeManager, 'should return this');
});
scopeManager.enable();
});
});

describe('.with()', () => {
it('should run the callback (null as target)', done => {
scopeManager.with(null, done);
});

it('should run the callback (object as target)', done => {
const test = { a: 1 };
scopeManager.with(test, () => {
assert.strictEqual(scopeManager.active(), test, 'should have scope');
return done();
});
});

it('should run the callback (when disabled)', done => {
scopeManager.disable();
scopeManager.with(null, () => {
scopeManager.enable();
return done();
});
});
});

describe('.bind(function)', () => {
it('should return the same target (when enabled)', () => {
const test = { a: 1 };
assert.deepStrictEqual(scopeManager.bind(test), test);
});

it('should return the same target (when disabled)', () => {
scopeManager.disable();
const test = { a: 1 };
assert.deepStrictEqual(scopeManager.bind(test), test);
scopeManager.enable();
});

it('should return current scope (when enabled)', done => {
const scope = { a: 1 };
const fn = scopeManager.bind(() => {
assert.strictEqual(scopeManager.active(), scope, 'should have scope');
return done();
}, scope);
fn();
});

/**
* Even if asynchooks is disabled, the scope propagation will
* still works but it might be lost after any async op.
*/
it('should return current scope (when disabled)', done => {
scopeManager.disable();
const scope = { a: 1 };
const fn = scopeManager.bind(() => {
assert.strictEqual(scopeManager.active(), scope, 'should have scope');
return done();
}, scope);
fn();
});

it('should fail to return current scope (when disabled + async op)', done => {
scopeManager.disable();
const scope = { a: 1 };
const fn = scopeManager.bind(() => {
setTimeout(() => {
assert.strictEqual(
scopeManager.active(),
null,
'should have no scope'
);
return done();
}, 100);
}, scope);
fn();
});

it('should return current scope (when re-enabled + async op)', done => {
scopeManager.enable();
const scope = { a: 1 };
const fn = scopeManager.bind(() => {
setTimeout(() => {
assert.strictEqual(scopeManager.active(), scope, 'should have scope');
return done();
}, 100);
}, scope);
fn();
});
});
});