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(restify): add requestHook support #1312

Merged
merged 11 commits into from
Dec 13, 2022
21 changes: 21 additions & 0 deletions plugins/node/opentelemetry-instrumentation-restify/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,27 @@ registerInstrumentations({

See [examples/restify](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/examples/restify) for a short example.

## Restify Instrumentation Options

| Options | Type | Example | Description |
| `requestHook` | `RestifyCustomAttributeFunction` | `(span, requestInfo) => {}` | Function for adding custom attributes to restify requests. Receives params: `Span, RestifyRequestInfo`. |

### Using `requestHook`

Instrumentation configuration accepts a custom "hook" function which will be called for every instrumented restify request. Custom attributes can be set on the span or run any custom logic per request.

```javascript
import { RestifyInstrumentation } from "@opentelemetry/instrumentation-restify"
const restifyInstrumentation = new RestifyInstrumentation({
requestHook: function (span: Span, info: RestifyRequestInfo) {
span.setAttribute(
'http.method',
info.request.method,
)
}
});
```

## Useful links

- For more information on OpenTelemetry, visit: <https://opentelemetry.io/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,4 @@ export * from './instrumentation';
export default RestifyInstrumentation;

export * from './enums/AttributeNames';
export * from './types';
Original file line number Diff line number Diff line change
Expand Up @@ -19,31 +19,44 @@ import type * as restify from 'restify';

import * as api from '@opentelemetry/api';
import type { Server } from 'restify';
import { LayerType } from './internal-types';
import { LayerType } from './types';
import * as AttributeNames from './enums/AttributeNames';
import { VERSION } from './version';
import * as constants from './constants';
import {
InstrumentationBase,
InstrumentationConfig,
InstrumentationNodeModuleDefinition,
InstrumentationNodeModuleFile,
isWrapped,
safeExecuteInTheMiddle,
} from '@opentelemetry/instrumentation';
import { SemanticAttributes } from '@opentelemetry/semantic-conventions';
import { isPromise, isAsyncFunction } from './utils';
import { getRPCMetadata, RPCType, setRPCMetadata } from '@opentelemetry/core';
import type { RestifyInstrumentationConfig } from './types';

const { diag } = api;

export class RestifyInstrumentation extends InstrumentationBase<any> {
constructor(config: InstrumentationConfig = {}) {
super(`@opentelemetry/instrumentation-${constants.MODULE_NAME}`, VERSION);
constructor(config: RestifyInstrumentationConfig = {}) {
super(
`@opentelemetry/instrumentation-${constants.MODULE_NAME}`,
VERSION,
Object.assign({}, config)
);
}

private _moduleVersion?: string;
private _isDisabled = false;

override setConfig(config: RestifyInstrumentationConfig = {}) {
this._config = Object.assign({}, config);
}

override getConfig(): RestifyInstrumentationConfig {
return this._config as RestifyInstrumentationConfig;
}

init() {
const module = new InstrumentationNodeModuleDefinition<any>(
constants.MODULE_NAME,
Expand Down Expand Up @@ -185,6 +198,26 @@ export class RestifyInstrumentation extends InstrumentationBase<any> {
},
api.context.active()
);

const instrumentation = this;
const requestHook = instrumentation.getConfig().requestHook;
if (requestHook) {
safeExecuteInTheMiddle(
() => {
return requestHook!(span, {
request: req,
layerType: metadata.type,
});
},
e => {
if (e) {
instrumentation._diag.error('request hook failed', e);
}
},
true
);
}

const patchedNext = (err?: any) => {
span.end();
next(err);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,7 @@
*/
import { Span } from '@opentelemetry/api';
import type * as restify from 'restify';

export enum LayerType {
MIDDLEWARE = 'middleware',
REQUEST_HANDLER = 'request_handler',
}
import { LayerType } from './types';

declare interface RequestWithRoute extends restify.Request {
route: { path: string };
Expand Down
45 changes: 45 additions & 0 deletions plugins/node/opentelemetry-instrumentation-restify/src/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/*
* Copyright The 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
*
* https://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 { Span } from '@opentelemetry/api';
import { InstrumentationConfig } from '@opentelemetry/instrumentation';

export enum LayerType {
MIDDLEWARE = 'middleware',
REQUEST_HANDLER = 'request_handler',
}

export interface RestifyRequestInfo {
request: any; // Request type from @types/restify package
layerType: LayerType;
}

/**
* Function that can be used to add custom attributes to the current span
* @param span - The restify handler span.
* @param info - The restify request info object.
*/
export interface RestifyCustomAttributeFunction {
(span: Span, info: RestifyRequestInfo): void;
}

/**
* Options available for the restify Instrumentation
*/
export interface RestifyInstrumentationConfig extends InstrumentationConfig {
/** Function for adding custom attributes to each handler span */
requestHook?: RestifyCustomAttributeFunction;
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@
* limitations under the License.
*/

import { context, trace } from '@opentelemetry/api';
import { context, trace, Span } from '@opentelemetry/api';
import { SemanticAttributes } from '@opentelemetry/semantic-conventions';
import { RPCType, setRPCMetadata } from '@opentelemetry/core';
import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node';
import { AsyncHooksContextManager } from '@opentelemetry/context-async-hooks';
Expand All @@ -25,6 +26,7 @@ import {

import RestifyInstrumentation from '../src';
import * as types from '../src/internal-types';
import { RestifyRequestInfo } from '../src/types';
const plugin = new RestifyInstrumentation();

import * as semver from 'semver';
Expand Down Expand Up @@ -487,6 +489,85 @@ describe('Restify Instrumentation', () => {
assert.strictEqual(memoryExporter.getFinishedSpans().length, 3);
assert.strictEqual(res, '{"route":"bar"}');
});

describe('using requestHook in config', () => {
it('calls requestHook provided function when set in config', async () => {
const requestHook = (span: Span, info: RestifyRequestInfo) => {
span.setAttribute(
SemanticAttributes.HTTP_METHOD,
info.request.method
);
span.setAttribute('restify.layer', info.layerType);
};

plugin.setConfig({
...plugin.getConfig(),
requestHook,
});

const rootSpan = tracer.startSpan('clientSpan');

await context.with(
trace.setSpan(context.active(), rootSpan),
async () => {
await httpRequest.get(`http://localhost:${port}/route/foo`);
rootSpan.end();
assert.strictEqual(memoryExporter.getFinishedSpans().length, 4);

{
// span from get
const span = memoryExporter.getFinishedSpans()[2];
assert.notStrictEqual(span, undefined);
assert.strictEqual(
span.attributes[SemanticAttributes.HTTP_METHOD],
'GET'
);
assert.strictEqual(
span.attributes['restify.layer'],
'request_handler'
);
}
}
);
});

it('does not propagate an error from a requestHook that throws exception', async () => {
const requestHook = (span: Span, info: RestifyRequestInfo) => {
span.setAttribute(
SemanticAttributes.HTTP_METHOD,
info.request.method
);

throw Error('error thrown in requestHook');
};

plugin.setConfig({
...plugin.getConfig(),
requestHook,
});

const rootSpan = tracer.startSpan('clientSpan');

await context.with(
trace.setSpan(context.active(), rootSpan),
async () => {
await httpRequest.get(`http://localhost:${port}/route/foo`);
rootSpan.end();
assert.strictEqual(memoryExporter.getFinishedSpans().length, 4);

{
// span from get
const span = memoryExporter.getFinishedSpans()[2];
assert.notStrictEqual(span, undefined);
assert.strictEqual(
span.attributes[SemanticAttributes.HTTP_METHOD],
'GET'
);
}
}
);
});
});
});

describe('Disabling restify instrumentation', () => {
Expand Down