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

fix(connect): fix wrong rpcMetada.route value not handle nested route #1555

Merged
merged 15 commits into from
Aug 12, 2023
Merged
Show file tree
Hide file tree
Changes from 11 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
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,13 @@ import {
ConnectNames,
ConnectTypes,
} from './enums/AttributeNames';
import { Use, UseArgs, UseArgs2 } from './internal-types';
import {
_LAYERS_STORE_PROPERTY,
PatchedRequest,
Use,
UseArgs,
UseArgs2,
} from './internal-types';
import { VERSION } from './version';
import {
InstrumentationBase,
Expand All @@ -35,6 +41,22 @@ import { SemanticAttributes } from '@opentelemetry/semantic-conventions';

export const ANONYMOUS_NAME = 'anonymous';

const addNewStackLayer = (request: PatchedRequest) => {
if (Array.isArray(request[_LAYERS_STORE_PROPERTY]) === false) {
Object.defineProperty(request, _LAYERS_STORE_PROPERTY, {
enumerable: false,
value: [],
});
}
request[_LAYERS_STORE_PROPERTY].push('/');
};

const replaceCurrentStackRoute = (request: PatchedRequest, value?: string) => {
chigia001 marked this conversation as resolved.
Show resolved Hide resolved
if (value) {
request[_LAYERS_STORE_PROPERTY].splice(-1, 1, value);
}
};

chigia001 marked this conversation as resolved.
Show resolved Hide resolved
/** Connect instrumentation for OpenTelemetry */
export class ConnectInstrumentation extends InstrumentationBase<Server> {
constructor(config: InstrumentationConfig = {}) {
Expand Down Expand Up @@ -65,6 +87,9 @@ export class ConnectInstrumentation extends InstrumentationBase<Server> {
if (!isWrapped(patchedApp.use)) {
this._wrap(patchedApp, 'use', this._patchUse.bind(this));
}
if (!isWrapped(patchedApp.handle)) {
this._wrap(patchedApp, 'handle', this._patchHandle.bind(this));
}
}

private _patchConstructor(original: () => Server): () => Server {
Expand Down Expand Up @@ -120,13 +145,20 @@ export class ConnectInstrumentation extends InstrumentationBase<Server> {
if (!instrumentation.isEnabled()) {
return (middleWare as any).apply(this, arguments);
}
const [resArgIdx, nextArgIdx] = isErrorMiddleware ? [2, 3] : [1, 2];
const [reqArgIdx, resArgIdx, nextArgIdx] = isErrorMiddleware
? [1, 2, 3]
: [0, 1, 2];
const req = arguments[reqArgIdx] as PatchedRequest;
const res = arguments[resArgIdx] as ServerResponse;
const next = arguments[nextArgIdx] as NextFunction;

replaceCurrentStackRoute(req, routeName);

const rpcMetadata = getRPCMetadata(context.active());
if (routeName && rpcMetadata?.type === RPCType.HTTP) {
rpcMetadata.route = routeName;
rpcMetadata.route = req[_LAYERS_STORE_PROPERTY].reduce(
(acc, sub) => acc.replace(/\/+$/, '') + sub
chigia001 marked this conversation as resolved.
Show resolved Hide resolved
);
}
let spanName = '';
if (routeName) {
Expand Down Expand Up @@ -180,4 +212,33 @@ export class ConnectInstrumentation extends InstrumentationBase<Server> {
return original.apply(this, args as UseArgs2);
};
}

public _patchHandle(original: Server['handle']): Server['handle'] {
const instrumentation = this;
return function (this: Server): ReturnType<Server['handle']> {
const [reqIdx, outIdx] = [0, 2];
const req = arguments[reqIdx] as PatchedRequest;
const out = arguments[outIdx];
addNewStackLayer(req);

function completeStack() {
req[_LAYERS_STORE_PROPERTY].pop();
}
chigia001 marked this conversation as resolved.
Show resolved Hide resolved
if (typeof out === 'function') {
arguments[outIdx] = instrumentation._patchOut(
out as NextFunction,
completeStack
);
}

return (original as any).apply(this, arguments);
};
}

public _patchOut(out: NextFunction, completeStack: () => void): NextFunction {
return function nextFunction(this: NextFunction, ...args: any[]): void {
completeStack();
return Reflect.apply(out, this, args);
};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,14 @@
* limitations under the License.
*/

import type { HandleFunction, Server } from 'connect';
import type { HandleFunction, IncomingMessage, Server } from 'connect';

export const _LAYERS_STORE_PROPERTY: unique symbol = Symbol('__ot_middlewares');
chigia001 marked this conversation as resolved.
Show resolved Hide resolved

export type UseArgs1 = [HandleFunction];
export type UseArgs2 = [string, HandleFunction];
export type UseArgs = UseArgs1 | UseArgs2;
export type Use = (...args: UseArgs) => Server;
export type PatchedRequest = {
[_LAYERS_STORE_PROPERTY]: string[];
} & IncomingMessage;
Original file line number Diff line number Diff line change
Expand Up @@ -243,5 +243,88 @@ describe('connect', () => {
changedRootSpan.spanContext().spanId
);
});

it('should append nested route in RpcMetadata', async () => {
const rootSpan = tracer.startSpan('root span');
const rpcMetadata: RPCMetadata = { type: RPCType.HTTP, span: rootSpan };
app.use((req, res, next) => {
return context.with(
setRPCMetadata(
trace.setSpan(context.active(), rootSpan),
rpcMetadata
),
next
);
});

const nestedApp = connect();

app.use('/foo/', nestedApp);
nestedApp.use('/bar/', (req, res, next) => {
next();
});

await httpRequest.get(`http://localhost:${PORT}/foo/bar`);
rootSpan.end();

assert.strictEqual(rpcMetadata.route, '/foo/bar/');
chigia001 marked this conversation as resolved.
Show resolved Hide resolved
});

it('should use latest match route when multiple route is match', async () => {
const rootSpan = tracer.startSpan('root span');
const rpcMetadata: RPCMetadata = { type: RPCType.HTTP, span: rootSpan };
app.use((req, res, next) => {
return context.with(
setRPCMetadata(
trace.setSpan(context.active(), rootSpan),
rpcMetadata
),
next
);
});

app.use('/foo', (req, res, next) => {
next();
});

app.use('/foo/bar', (req, res, next) => {
next();
});

await httpRequest.get(`http://localhost:${PORT}/foo/bar`);
rootSpan.end();

assert.strictEqual(rpcMetadata.route, '/foo/bar');
});

it('should use latest match route when multiple route is match (with nested app)', async () => {
const rootSpan = tracer.startSpan('root span');
const rpcMetadata: RPCMetadata = { type: RPCType.HTTP, span: rootSpan };
app.use((req, res, next) => {
return context.with(
setRPCMetadata(
trace.setSpan(context.active(), rootSpan),
rpcMetadata
),
next
);
});

const nestedApp = connect();

app.use('/foo/', nestedApp);
nestedApp.use('/bar/', (req, res, next) => {
next();
});

app.use('/foo/bar/test', (req, res, next) => {
next();
});

await httpRequest.get(`http://localhost:${PORT}/foo/bar/test`);
rootSpan.end();

assert.strictEqual(rpcMetadata.route, '/foo/bar/test');
chigia001 marked this conversation as resolved.
Show resolved Hide resolved
});
});
});
Loading