Skip to content
This repository has been archived by the owner on Aug 25, 2021. It is now read-only.

Feat/refactor http hook #244

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
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/hook/src/patch/HttpClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export type bufferTransformer = (buffer) => object | string;

export class HttpClientPatcher extends Patcher {

constructor(options: {
constructor(options?: {
forceHttps?: boolean,
recordResponse?: boolean,
bufferTransformer?: bufferTransformer
Expand Down
213 changes: 120 additions & 93 deletions packages/hook/src/patch/HttpServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,8 @@ import { HEADER_TRACE_ID } from '../utils/Constants';
import { parse as parseUrl } from 'url';
import { parse as parseQS, ParsedUrlQuery } from 'querystring';
import * as http from 'http';
import { IncomingMessage } from 'http';

const debug = require('debug')('Pandora:Hook:HttpServerPatcher');
const debug = require('debug')('PandoraHook:HttpServerPatcher');

export type bufferTransformer = (buffer) => object | string;

Expand Down Expand Up @@ -52,7 +51,7 @@ export class HttpServerPatcher extends Patcher {
createTracer(req) {
const traceId = this.getTraceId(req);

return this.getTraceManager().create({ traceId });
return this.getTraceManager().create({traceId});
}

buildTags(req) {
Expand Down Expand Up @@ -82,42 +81,126 @@ export class HttpServerPatcher extends Patcher {
return false;
}

_beforeExecute(tracer, req, res) {}
_beforeExecute(tracer, req, res) {
}

beforeFinish(span, res) {
span.setTag('http.status_code', {
type: 'number',
value: res.statusCode
});
bufferTransformer(buffer): ParsedUrlQuery | string {
try {
return parseQS(buffer.toString('utf8'));
} catch (error) {
debug('transform post data error. ', error);
return '';
}
}

initTracerAndSpan(req, res) {
const traceManager = this.getTraceManager();
traceManager.bindEmitter(req);
traceManager.bindEmitter(res);

const tracer = this.createTracer(req);
this._beforeExecute(tracer, req, res);
const tags = this.buildTags(req);
const span = this.createSpan(tracer, tags);
tracer.named(`HTTP-${tags['http.method'].value}:${tags['http.url'].value}`);
tracer.setCurrentSpan(span);
return {tracer, span};
}

processGetParams(req) {
const url = req.url;
/**
* 放 class 层,方便子类 overwrite
* @param req
* @param res
* @param tracer
* @param span
*/
recordQuery(req, res, tracer, span) {
if (this.options.recordGetParams) {
const query = processGetParams(req);
span.log({
query
});
}

function processGetParams(req) {
const url = req.url;

if (url) {
let urlParsed;

if (url) {
let urlParsed;
try {
urlParsed = parseUrl(url, true);
} catch (error) {
debug('process get params error. ', error);

try {
urlParsed = parseUrl(url, true);
} catch (error) {
debug('process get params error. ', error);
return {};
}

return {};
return urlParsed.query;
}

return urlParsed.query;
return {};
}
}

return {};
recordBodyData(req, res, tracer, span) {
const self = this;
const options = this.options;
let chunks = [];
if (options.recordPostData && req.method && req.method.toUpperCase() === 'POST') {
req.on('data', (data) => {
const chunk = data || [];
chunks.push(chunk);
});
res.once('finish', () => {
if (options.recordPostData && req.method && req.method.toUpperCase() === 'POST') {
const transformer = options.bufferTransformer || self.bufferTransformer;
const postData = transformer(chunks);
span.log({
data: postData
});
// clear cache
chunks = [];
}
});
}
}

bufferTransformer(buffer): ParsedUrlQuery | string {
try {
return parseQS(buffer.toString('utf8'));
} catch (error) {
debug('transform post data error. ', error);
return '';
/**
* 完成所有钩子的注册
* @param req
* @param res
* @param tracer
* @param span
*/
wrapRequest(req, res, tracer, span) {
this.recordQuery(req, res, tracer, span);
this.recordBodyData(req, res, tracer, span);
// TODO recordResponse
}

handleResponse(req, res, tracer, span) {
const self = this;
const options = this.options;

function onFinishedFactory(eventName) {
return function onFinished() {
res.removeListener('finish', onFinished);
req.removeListener('aborted', onFinished);
span.setTag('http.aborted', {
type: 'bool',
value: eventName === 'aborted'
});

self.beforeFinish(span, res);
span.finish();
tracer.finish(options);
self.afterFinish(span, res);
};
}

res.once('finish', onFinishedFactory('finish'));
req.once('aborted', onFinishedFactory('aborted'));
}

shimmer(options) {
Expand All @@ -130,80 +213,17 @@ export class HttpServerPatcher extends Patcher {
return function wrappedCreateServer(this: any, requestListener) {
if (requestListener) {

const listener = traceManager.bind(function(req, res) {
const listener = traceManager.bind(function (req, res) {
const requestFilter = options.requestFilter || self.requestFilter;

if (requestFilter(req)) {
debug('request filter by requestFilter, skip trace.');
return requestListener(req, res);
}

traceManager.bindEmitter(req);
traceManager.bindEmitter(res);

const tracer = self.createTracer(req);
self._beforeExecute(tracer, req, res);
const tags = self.buildTags(req);
const span = self.createSpan(tracer, tags);

if (options.recordGetParams) {
const query = self.processGetParams(req);

span.log({
query
});
}

let chunks = [];
if (options.recordPostData && req.method && req.method.toUpperCase() === 'POST') {
shimmer.wrap(req, 'emit', function wrapRequestEmit(emit) {
const bindRequestEmit = traceManager.bind(emit);

return function wrappedRequestEmit(this: IncomingMessage, event) {
if (event === 'data') {
const chunk = arguments[1] || [];

chunks.push(chunk);
}

return bindRequestEmit.apply(this, arguments);
};
});
}

tracer.named(`HTTP-${tags['http.method'].value}:${tags['http.url'].value}`);
tracer.setCurrentSpan(span);

function onFinishedFactory(eventName) {
return function onFinished() {
res.removeListener('finish', onFinished);
req.removeListener('aborted', onFinished);

if (eventName !== 'aborted' && options.recordPostData && req.method && req.method.toUpperCase() === 'POST') {
const transformer = options.bufferTransformer || self.bufferTransformer;
const postData = transformer(chunks);

span.log({
data: postData
});
// clear cache
chunks = [];
}

span.setTag('http.aborted', {
type: 'bool',
value: eventName === 'aborted'
});

self.beforeFinish(span, res);
span.finish();
tracer.finish(options);
self.afterFinish(span, res);
};
}

res.once('finish', onFinishedFactory('finish'));
req.once('aborted', onFinishedFactory('aborted'));
const {tracer, span} = self.initTracerAndSpan(req, res);
self.wrapRequest(req, res, tracer, span);
self.handleResponse(req, res, tracer, span);

return requestListener(req, res);
});
Expand All @@ -217,6 +237,13 @@ export class HttpServerPatcher extends Patcher {
});
}

beforeFinish(span, res) {
span.setTag('http.status_code', {
type: 'number',
value: res.statusCode
});
}

afterFinish(span, res) {
// overwrite
}
Expand Down
Loading