11import type { Agent } from 'http' ;
22import http from 'http' ;
3+ import { performance } from 'perf_hooks' ;
34import axios from 'axios' ;
45import _ from 'lodash' ;
56import { v4 as uuidv4 } from 'uuid' ;
@@ -207,6 +208,22 @@ abstract class AbstractMicroservice {
207208 return this ;
208209 }
209210
211+ /**
212+ * Inject performance record to request or response
213+ * @protected
214+ */
215+ protected injectPerformance ( data : Record < string , any > , key : string , type : 'req' | 'res' ) : void {
216+ const stack = data ?. payload ?. performance ?? [ ] ;
217+
218+ stack . push ( {
219+ key,
220+ type,
221+ point : performance . now ( ) ,
222+ } ) ;
223+
224+ _ . set ( data , 'payload.performance' , stack ) ;
225+ }
226+
210227 /**
211228 * Add process exit handler
212229 * E.g. for close DB connection etc.
@@ -345,6 +362,8 @@ abstract class AbstractMicroservice {
345362
346363 const task = new MicroserviceRequest ( req . data ) ;
347364
365+ this . injectPerformance ( task . getParams ( ) ! , `${ name } -start` , 'req' ) ;
366+
348367 return { task, req } ;
349368 } catch ( e ) {
350369 // Could not connect to ijson or channel
@@ -369,6 +388,7 @@ abstract class AbstractMicroservice {
369388 task : ITask [ 'task' ] ,
370389 req : ITask [ 'req' ] ,
371390 ) : Promise < MicroserviceResponse > {
391+ const { name } = this . options ;
372392 const response = new MicroserviceResponse ( { id : task . getId ( ) } ) ;
373393 const taskSender =
374394 task instanceof MicroserviceRequest ? task . getParams ( ) ?. payload ?. sender : null ;
@@ -437,6 +457,8 @@ abstract class AbstractMicroservice {
437457 response . getId ( ) ,
438458 ) ;
439459
460+ this . injectPerformance ( response . getResult ( ) ! , `${ name } -end` , 'res' ) ;
461+
440462 return response ;
441463 }
442464
@@ -631,6 +653,7 @@ abstract class AbstractMicroservice {
631653 _ . set ( requestParams , 'payload.sender' , sender ) ;
632654 _ . set ( requestParams , 'payload.senderStack' , [ ...( data . payload ?. senderStack ?? [ ] ) , sender ] ) ;
633655 _ . set ( requestParams , 'payload.isInternal' , isInternal ) ;
656+ this . injectPerformance ( requestParams , `${ microservice } -start` , 'req' ) ;
634657
635658 const request = new MicroserviceRequest ( {
636659 ...( shouldGenerateId || reqId ? { id : reqId ?? uuidv4 ( ) } : { } ) ,
@@ -670,6 +693,8 @@ abstract class AbstractMicroservice {
670693 throw new BaseException ( result . error ) ;
671694 }
672695
696+ this . injectPerformance ( result . result , `${ microservice } -end` , 'res' ) ;
697+
673698 response . setResult ( result . result ) ;
674699
675700 return response ;
0 commit comments