Repository URL to install this package:
|
Version:
0.9.2 ▾
|
// (c) Copyright 2023 Supertenant Ltd. - all rights reserved.
// See LICENSE file in project root for license terms.
"use strict";const superbrain=require("@supertenant/superbrain")["superbrain"],superconsts=require("@supertenant/superconsts"),{getWaitPollInterval,getHttpRejectActionStatusCode,getDelayDuration}=require("../../actions"),dedupReportError=require("../../../logger")["dedupReportError"],httpServer=require("../protocols/httpServer"),cls=require("../../cls");let logger=require("../../../logger").getLogger("tracing/fastify",newLogger=>{logger=newLogger});function fastifyHandleAction(openSpanResult,req,res,firstCall=!0){let actionRef;if((actionRef=firstCall?superbrain.getAction(openSpanResult.action):superbrain.pollSpanAction(openSpanResult.openSpanResult)).Action===superconsts.Action.Execute)req._stExecuted=!0;else{if(actionRef.Action===superconsts.Action.Wait){const pollInterval=getWaitPollInterval(actionRef);return new Promise(resolve=>setTimeout(resolve,pollInterval).unref()).then(cls.ns.bind(()=>fastifyHandleAction(openSpanResult,req,res,!1)))}if(actionRef.Action===superconsts.Action.Delay){const delayDuration=getDelayDuration(actionRef);return new Promise(resolve=>setTimeout(resolve,delayDuration).unref()).then(cls.ns.bind(()=>{res.sent||(req._stExecuted=!0)}))}actionRef.Action===superconsts.Action.Reject?res.sent||(firstCall=getHttpRejectActionStatusCode(actionRef),res.header("x-supertenant-rejected","true").code(firstCall).send({error:"SuperTenant rejected"}),req._stExecuted=!0):dedupReportError("httpServer:UNKNOWN_ACTION","received unknown action ID",actionRef)}}function instrument(app,hook,tenantGetter){var version=require("fastify/package.json")["version"];return version.startsWith("1.")||version.startsWith("2.")?(logger.warn("Not able to instrument Fastify V1 or V2. The instrumention of http requests is still working."),app):app.addHook?["preValidation","preHandler","onRequest"].includes(hook)?null!=tenantGetter&&"function"!=typeof tenantGetter?(logger.warn("Not able to instrument Fastify (tenantGetter has to be a function). The instrumention of http requests is still working."),app):(httpServer.deactivate(),app.addHook(hook,async(request,reply)=>{let tenantId;if(tenantGetter){var tenantGetterResult=tenantGetter(request);if(tenantGetterResult instanceof Promise){if(null!=(tenantId=await tenantGetterResult)&&"string"!=typeof tenantId)try{tenantId=String(tenantId)}catch(e){tenantId=void 0}}else if("string"==typeof tenantGetterResult)tenantId=tenantGetterResult;else if(null!=tenantGetterResult)try{tenantId=String(tenantGetterResult)}catch(e){tenantId=void 0}}return cls.ns.runAndReturn(()=>{let result;var span=(result=null!=tenantId?httpServer.startHttpSpan(request.raw,tenantId):httpServer.startHttpSpan(request.raw)).span,openSpanResult=result.openSpanResult;if(request._st_openSpanResult=openSpanResult,request._span=span,null!=openSpanResult)return request._stExecuted=!1,fastifyHandleAction(openSpanResult,request,reply)})}),void app.addHook("onResponse",async(request,reply)=>{var closeSpanData;null!=request._st_openSpanResult&&(closeSpanData={},request._stExecuted||(closeSpanData[superconsts.Label.SupertenantCanceled]="true"),closeSpanData[superconsts.Label.HttpStatus]=reply.statusCode,500<=reply.statusCode&&(closeSpanData[superconsts.Label.SupertenantError]="true"),superbrain.closeSpan(request._st_openSpanResult.spanId,closeSpanData))})):(logger.warn("Not able to instrument Fastify (hook has to be one of preValidation, preHandler, onRequest). The instrumention of http requests is still working."),app):(logger.warn("Not able to instrument Fastify (app does not have addHook function). The instrumention of http requests is still working."),app)}exports.instrumentFastify=instrument;