Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/445.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在express/nodejs中创建和结束跟踪范围的正确方法_Javascript_Node.js_Express_Opentracing_Open Telemetry - Fatal编程技术网

Javascript 在express/nodejs中创建和结束跟踪范围的正确方法

Javascript 在express/nodejs中创建和结束跟踪范围的正确方法,javascript,node.js,express,opentracing,open-telemetry,Javascript,Node.js,Express,Opentracing,Open Telemetry,我正在尝试nodejs/express库,并试图重写Istio中的bookinfo 我遵循下列文件中给出的跟踪程序配置: 我的请求处理程序如下所示: router.get('/:productIdStr', function(req, res, next) { starsReviewer1 = -1 starsReviewer2 = -1 var productId = parseInt(req.params.productIdStr) tracer =

我正在尝试nodejs/express库,并试图重写Istio中的
bookinfo

我遵循下列文件中给出的跟踪程序配置:

我的请求处理程序如下所示:

router.get('/:productIdStr', function(req, res, next) {
    starsReviewer1 = -1
    starsReviewer2 = -1
      var productId = parseInt(req.params.productIdStr)
      tracer = req.app.locals.tracer
    
      api.context.with(api.propagation.extract(api.ROOT_CONTEXT, req.headers),async () => {
        //---
       var returnedData=""
       span = {}
        Promise.all(
          [ function(){
            span = req.app.locals.tracer.startSpan('calculate-reviews', {
              kind: 1, // server
              attributes: { star_colour: starColor },    
            });
            let promise;
            api.context.with(api.setSpan(api.context.active(), span),async () => {
              additionalHeaders = {'Content-Type':'application/json'}
              function addHeader(value, index, array) {
                if (typeof req.headers[value] !== 'undefined' && req.headers[value] !== null){
                  additionalHeaders[value] = req.headers[value]} 
              }
              headersToPropogate.forEach(addHeader)
              api.propagation.inject(api.context.active(),additionalHeaders)
              requstPath='http://'+ratingsService +":"+ratingsServicePort + "/ratings/" + productId
              //GetRatings
              // Make HTTP Call to the ratings service here.
              promise = axios.get(
                requstPath,
               {headers:additionalHeaders}
              )
              .then((res) => {
                log_info(span,"Get Ratings give value")
                span.addEvent('Data available from ratings ');
                returnedData=res.data
              })
              .catch((error) => {
                log_info(span,"Get Ratings did not give value, Using default Values")
                span.addEvent('Data not available from ratings ');
                console.error(error)
              })
              .finally(() => {
                span.end();
              });
    
            })
            return promise;
          }()]
        )
        .then(() => {
          if (returnedData !== ""){
            
            res.writeHead(200, {'Content-type': 'application/json'})
            res.end(JSON.stringify(getJsonResponse(productId,returnedData.ratings.Reviewer1, returnedData.ratings.Reviewer1)))
          }
          else{
            res.writeHead(200, {'Content-type': 'application/json'})
            res.end(JSON.stringify(getJsonResponse(productId,starsReviewer1, starsReviewer1)))
          }
        })
        .catch((error) => {
          res.writeHead(200, {'Content-type': 'application/json'})
          res.end(JSON.stringify(getJsonResponse(productId,starsReviewer1, starsReviewer1)))
        })
        .finally(()=>{
          span.end()
        })
        
        })
      //---
    });
我面临的问题是,当我查看生成的痕迹时,它似乎是错误的:

这些问题是:

  • “计算评论”范围未关闭
  • 如何删除似乎自动添加的“HTTP GET”。我试图覆盖这是我的跟踪设置,但它不起作用。相反,除了
    httpget
    之外,似乎还创建了一个新的
    node-express-reviews服务:
  • HTTP调用rating.default的范围在
    calculate reviews
    调用之前开始和结束。理想情况下,
    评级的范围。默认值应在
    计算审核之后开始,在计算审核之前结束。但是在图像中,
    calcualte reviews
    span在
    ratings.default
    之后开始和结束。我做错了什么?正确的做法是什么
  • 我在“calculate reviews”下得到的错误“clock skew adjustment disabled;not Applieve calculated delta of-53.6005ms”是什么

我试图重构代码,使其更具可读性和可理解性,希望这将是找出错误的一个良好起点。但实际上,我不明白这应该做什么,所以我不能真正调试它

router.get('/:productIdStr', async (req, res) => {

    const starsReviewer1 = -1;
    const starsReviewer2 = -1;
    const productId = parseInt(req.params.productIdStr);
    const tracer = req.app.locals.tracer;

    await new Promise(resolve => api.context.with(api.propagation.extract(api.ROOT_CONTEXT, req.headers), resolve)); // Not sure what this does? It doesn't return anything?

    const span = req.app.locals.tracer.startSpan('calculate-reviews', {
        kind: 1, // server
        attributes: { star_colour: starColor },
    });

    await new Promise(resolve => api.context.with(api.setSpan(api.context.active(), span), resolve)); // Still not sure what this does, as it still doesn't return anything

    const additionalHeaders = { 'Content-Type': 'application/json' };

    headersToPropogate.forEach(value => { // headersToPropogate is undefined?
        if (typeof req.headers[value] !== 'undefined' && req.headers[value] !== null) {
            additionalHeaders[value] = req.headers[value]
        }
    });

    api.propagation.inject(api.context.active(), additionalHeaders); // No idea what this does, it doesn't seem to be asynchronous

    const requstPath = 'http://' + ratingsService + ":" + ratingsServicePort + "/ratings/" + productId;
    
    const returnedData = await axios.get(
        requstPath,
        { headers: additionalHeaders }
    ).data;

    if (returnedData !== "") {
        res.writeHead(200, { 'Content-type': 'application/json' })
        res.end(JSON.stringify(getJsonResponse(productId, returnedData.ratings.Reviewer1, returnedData.ratings.Reviewer1)))
    }
    else {
        res.writeHead(200, { 'Content-type': 'application/json' })
        res.end(JSON.stringify(getJsonResponse(productId, starsReviewer1, starsReviewer1)))
    }

    span.end(); // No idea what this is either
});

天哪,这段代码需要一些深层次的重构。你怎么能看出来?在函数内部有带
.then()
的承诺,在函数内部有带
的承诺,在数组内部有一个自调用函数内部有回调,在承诺内部有数组。在路由处理程序内部,在定义承诺之前,也可以
返回承诺(您在异步回调中定义了它,因此它将在返回后定义)什么是
api.context.with
?它接受一个没有参数的回调函数?所以它什么也不返回?但仍然接受一个回调函数?我不明白。还有
Promise。所有的
都有一个只有一个Promise的数组,所以不需要Promise。总之,一个简单的Promise就可以了。我正在尝试重构和理解这段代码,但是没有有那么多错误和不可理解的东西。
api.context.with
不返回任何东西,但仍然使用回调函数?为什么?
headersToPropogate
未定义。许多变量在声明时没有
常量,这使它们成为全局变量(
starsReviewer1
starsReviewer2
requstPath
例如)。
ratingsService
ratingsServicePort
未定义。
starsReviewer2
未使用,等等。嗨,Jeremy,谢谢你的帮助。你是对的,代码确实需要很多重构。。。(我也在学习如何正确使用承诺)。
router.get('/:productIdStr', async (req, res) => {

    const starsReviewer1 = -1;
    const starsReviewer2 = -1;
    const productId = parseInt(req.params.productIdStr);
    const tracer = req.app.locals.tracer;

    await new Promise(resolve => api.context.with(api.propagation.extract(api.ROOT_CONTEXT, req.headers), resolve)); // Not sure what this does? It doesn't return anything?

    const span = req.app.locals.tracer.startSpan('calculate-reviews', {
        kind: 1, // server
        attributes: { star_colour: starColor },
    });

    await new Promise(resolve => api.context.with(api.setSpan(api.context.active(), span), resolve)); // Still not sure what this does, as it still doesn't return anything

    const additionalHeaders = { 'Content-Type': 'application/json' };

    headersToPropogate.forEach(value => { // headersToPropogate is undefined?
        if (typeof req.headers[value] !== 'undefined' && req.headers[value] !== null) {
            additionalHeaders[value] = req.headers[value]
        }
    });

    api.propagation.inject(api.context.active(), additionalHeaders); // No idea what this does, it doesn't seem to be asynchronous

    const requstPath = 'http://' + ratingsService + ":" + ratingsServicePort + "/ratings/" + productId;
    
    const returnedData = await axios.get(
        requstPath,
        { headers: additionalHeaders }
    ).data;

    if (returnedData !== "") {
        res.writeHead(200, { 'Content-type': 'application/json' })
        res.end(JSON.stringify(getJsonResponse(productId, returnedData.ratings.Reviewer1, returnedData.ratings.Reviewer1)))
    }
    else {
        res.writeHead(200, { 'Content-type': 'application/json' })
        res.end(JSON.stringify(getJsonResponse(productId, starsReviewer1, starsReviewer1)))
    }

    span.end(); // No idea what this is either
});