Skip to content

Commit

Permalink
chore(instrumentation-grpc): cleanup imported types
Browse files Browse the repository at this point in the history
  • Loading branch information
llc1123 committed Jun 7, 2023
1 parent 5750d9a commit 88252d9
Show file tree
Hide file tree
Showing 7 changed files with 105 additions and 116 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import {
propagation,
context,
} from '@opentelemetry/api';
import type * as grpcJs from '@grpc/grpc-js';
import { Client, Metadata, ServiceError } from '@grpc/grpc-js';
import {
_grpcStatusCodeToSpanStatus,
_grpcStatusCodeToOpenTelemetryStatusCode,
Expand All @@ -42,7 +42,7 @@ import { GRPC_STATUS_CODE_OK } from '../status-code';
*/
export function getMethodsToWrap(
this: GrpcJsInstrumentation,
client: typeof grpcJs.Client,
client: typeof Client,
methods: { [key: string]: { originalName?: string } }
): string[] {
const methodList: string[] = [];
Expand Down Expand Up @@ -74,8 +74,8 @@ export function makeGrpcClientRemoteCall(
metadataCapture: metadataCaptureType,
original: GrpcClientFunc,
args: unknown[],
metadata: grpcJs.Metadata,
self: grpcJs.Client
metadata: Metadata,
self: Client
): (span: Span) => EventEmitter {
/**
* Patches a callback so that the current span for this trace is also ended
Expand All @@ -86,7 +86,7 @@ export function makeGrpcClientRemoteCall(
callback: SendUnaryDataCallback<ResponseType>
) {
const wrappedFn: SendUnaryDataCallback<ResponseType> = (
err: grpcJs.ServiceError | null,
err: ServiceError | null,
res?: ResponseType
) => {
if (err) {
Expand Down Expand Up @@ -145,7 +145,7 @@ export function makeGrpcClientRemoteCall(
}
};
context.bind(context.active(), call);
call.on('error', (err: grpcJs.ServiceError) => {
call.on('error', (err: ServiceError) => {
if (call[CALL_SPAN_ENDED]) {
return;
}
Expand Down Expand Up @@ -185,26 +185,25 @@ export function makeGrpcClientRemoteCall(
*/
export function getMetadata(
this: GrpcJsInstrumentation,
grpcClient: typeof grpcJs,
original: GrpcClientFunc,
args: Array<unknown | grpcJs.Metadata>
): grpcJs.Metadata {
let metadata: grpcJs.Metadata;
args: Array<unknown | Metadata>
): Metadata {
let metadata: Metadata;

// This finds an instance of Metadata among the arguments.
// A possible issue that could occur is if the 'options' parameter from
// the user contains an '_internal_repr' as well as a 'getMap' function,
// but this is an extremely rare case.
let metadataIndex = args.findIndex((arg: unknown | grpcJs.Metadata) => {
let metadataIndex = args.findIndex((arg: unknown | Metadata) => {
return (
arg &&
typeof arg === 'object' &&
(arg as grpcJs.Metadata)['internalRepr'] && // changed from _internal_repr in grpc --> @grpc/grpc-js https://github.com/grpc/grpc-node/blob/95289edcaf36979cccf12797cc27335da8d01f03/packages/grpc-js/src/metadata.ts#L88
typeof (arg as grpcJs.Metadata).getMap === 'function'
(arg as Metadata)['internalRepr'] && // changed from _internal_repr in grpc --> @grpc/grpc-js https://github.com/grpc/grpc-node/blob/95289edcaf36979cccf12797cc27335da8d01f03/packages/grpc-js/src/metadata.ts#L88
typeof (arg as Metadata).getMap === 'function'
);
});
if (metadataIndex === -1) {
metadata = new grpcClient.Metadata();
metadata = new Metadata();
if (!original.requestStream) {
// unary or server stream
metadataIndex = 1;
Expand All @@ -214,7 +213,7 @@ export function getMetadata(
}
args.splice(metadataIndex, 0, metadata);
} else {
metadata = args[metadataIndex] as grpcJs.Metadata;
metadata = args[metadataIndex] as Metadata;
}
return metadata;
}
Expand All @@ -224,7 +223,7 @@ export function getMetadata(
* grpc receiver
* @param metadata
*/
export function setSpanContext(metadata: grpcJs.Metadata): void {
export function setSpanContext(metadata: Metadata): void {
propagation.inject(context.active(), metadata, {
set: (meta, k, v) => meta.set(k, v),
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
* limitations under the License.
*/

import type * as grpcJs from '@grpc/grpc-js';
import {
InstrumentationNodeModuleDefinition,
isWrapped,
Expand Down Expand Up @@ -53,6 +52,17 @@ import { EventEmitter } from 'events';
import { _extractMethodAndService, metadataCapture, URI_REGEX } from '../utils';
import { AttributeValues } from '../enums/AttributeValues';
import { SemanticAttributes } from '@opentelemetry/semantic-conventions';
import {
Server,
serialize as Serialize,
deserialize as Deserialize,
Metadata,
Client,
ServiceDefinition,
loadPackageDefinition,
GrpcObject,
} from '@grpc/grpc-js';
import * as grpcJs from '@grpc/grpc-js';

export class GrpcJsInstrumentation extends InstrumentationBase {
private _metadataCapture: metadataCaptureType;
Expand Down Expand Up @@ -89,23 +99,23 @@ export class GrpcJsInstrumentation extends InstrumentationBase {
this._wrap(
moduleExports,
'makeGenericClientConstructor',
this._patchClient(moduleExports)
this._patchClient()
);
if (isWrapped(moduleExports.makeClientConstructor)) {
this._unwrap(moduleExports, 'makeClientConstructor');
}
this._wrap(
moduleExports,
'makeClientConstructor',
this._patchClient(moduleExports)
this._patchClient()
);
if (isWrapped(moduleExports.loadPackageDefinition)) {
this._unwrap(moduleExports, 'loadPackageDefinition');
}
this._wrap(
moduleExports,
'loadPackageDefinition',
this._patchLoadPackageDefinition(moduleExports)
this._patchLoadPackageDefinition()
);
return moduleExports;
},
Expand Down Expand Up @@ -143,11 +153,11 @@ export class GrpcJsInstrumentation extends InstrumentationBase {
const config = this.getConfig();
instrumentation._diag.debug('patched gRPC server');
return function register<RequestType, ResponseType>(
this: grpcJs.Server,
this: Server,
name: string,
handler: HandleCall<unknown, unknown>,
serialize: grpcJs.serialize<unknown>,
deserialize: grpcJs.deserialize<unknown>,
serialize: Serialize<unknown>,
deserialize: Deserialize<unknown>,
type: string
): boolean {
const originalRegisterResult = originalRegister.call(
Expand All @@ -171,13 +181,7 @@ export class GrpcJsInstrumentation extends InstrumentationBase {
) {
const self = this;

if (
shouldNotTraceServerCall(
call.metadata,
name,
config.ignoreGrpcMethods
)
) {
if (shouldNotTraceServerCall(name, config.ignoreGrpcMethods)) {
return handleUntracedServerFunction(
type,
originalFunc,
Expand Down Expand Up @@ -220,14 +224,13 @@ export class GrpcJsInstrumentation extends InstrumentationBase {
instrumentation._wrap(
call,
'sendMetadata',
originalSendMetadata =>
(responseMetadata: grpcJs.Metadata) => {
instrumentation._metadataCapture.server.captureResponseMetadata(
span,
responseMetadata
);
originalSendMetadata.call(call, responseMetadata);
}
originalSendMetadata => (responseMetadata: Metadata) => {
instrumentation._metadataCapture.server.captureResponseMetadata(
span,
responseMetadata
);
originalSendMetadata.call(call, responseMetadata);
}
);

context.with(trace.setSpan(context.active(), span), () => {
Expand All @@ -246,33 +249,31 @@ export class GrpcJsInstrumentation extends InstrumentationBase {
}
);
return originalRegisterResult;
} as typeof grpcJs.Server.prototype.register;
} as typeof Server.prototype.register;
};
}

/**
* Entry point for applying client patches to `grpc.makeClientConstructor(...)` equivalents
* @param this GrpcJsPlugin
*/
private _patchClient(
grpcClient: typeof grpcJs
): (
private _patchClient(): (
original: MakeClientConstructorFunction
) => MakeClientConstructorFunction {
const instrumentation = this;
return (original: MakeClientConstructorFunction) => {
instrumentation._diag.debug('patching client');
return function makeClientConstructor(
this: typeof grpcJs.Client,
methods: grpcJs.ServiceDefinition,
this: typeof Client,
methods: ServiceDefinition,
serviceName: string,
options?: object
) {
const client = original.call(this, methods, serviceName, options);
instrumentation._massWrap<typeof client.prototype, string>(
client.prototype,
getMethodsToWrap.call(instrumentation, client, methods),
instrumentation._getPatchedClientMethods(grpcClient)
instrumentation._getPatchedClientMethods()
);
return client;
};
Expand All @@ -283,42 +284,37 @@ export class GrpcJsInstrumentation extends InstrumentationBase {
* Entry point for client patching for grpc.loadPackageDefinition(...)
* @param this - GrpcJsPlugin
*/
private _patchLoadPackageDefinition(grpcClient: typeof grpcJs) {
private _patchLoadPackageDefinition() {
const instrumentation = this;
instrumentation._diag.debug('patching loadPackageDefinition');
return (original: typeof grpcJs.loadPackageDefinition) => {
return (original: typeof loadPackageDefinition) => {
return function patchedLoadPackageDefinition(
this: null,
packageDef: PackageDefinition
) {
const result: grpcJs.GrpcObject = original.call(
const result: GrpcObject = original.call(
this,
packageDef
) as grpcJs.GrpcObject;
instrumentation._patchLoadedPackage(grpcClient, result);
) as GrpcObject;
instrumentation._patchLoadedPackage(result);
return result;
} as typeof grpcJs.loadPackageDefinition;
} as typeof loadPackageDefinition;
};
}

/**
* Parse initial client call properties and start a span to trace its execution
*/
private _getPatchedClientMethods(
grpcClient: typeof grpcJs
): (original: GrpcClientFunc) => () => EventEmitter {
private _getPatchedClientMethods(): (
original: GrpcClientFunc
) => () => EventEmitter {
const instrumentation = this;
return (original: GrpcClientFunc) => {
instrumentation._diag.debug('patch all client methods');
function clientMethodTrace(this: grpcJs.Client) {
function clientMethodTrace(this: Client) {
const name = `grpc.${original.path.replace('/', '')}`;
const args = [...arguments];
const metadata = getMetadata.call(
instrumentation,
grpcClient,
original,
args
);
const metadata = getMetadata.call(instrumentation, original, args);
const { service, method } = _extractMethodAndService(original.path);

const span = instrumentation.tracer
Expand Down Expand Up @@ -367,24 +363,17 @@ export class GrpcJsInstrumentation extends InstrumentationBase {
* parsing done by grpc.loadPackageDefinition
* https://github.com/grpc/grpc-node/blob/1d14203c382509c3f36132bd0244c99792cb6601/packages/grpc-js/src/make-client.ts#L200-L217
*/
private _patchLoadedPackage(
grpcClient: typeof grpcJs,
result: grpcJs.GrpcObject
): void {
private _patchLoadedPackage(result: GrpcObject): void {
Object.values(result).forEach(service => {
if (typeof service === 'function') {
this._massWrap<typeof service.prototype, string>(
service.prototype,
getMethodsToWrap.call(this, service, service.service),
this._getPatchedClientMethods.call(this, grpcClient)
this._getPatchedClientMethods.call(this)
);
} else if (typeof service.format !== 'string') {
// GrpcObject
this._patchLoadedPackage.call(
this,
grpcClient,
service as grpcJs.GrpcObject
);
this._patchLoadedPackage.call(this, service as GrpcObject);
}
});
}
Expand Down
Loading

0 comments on commit 88252d9

Please sign in to comment.