How to use the aws-xray-sdk.captureAsyncFunc function in aws-xray-sdk

To help you get started, we’ve selected a few aws-xray-sdk examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github alphagov / pay-frontend / app / models / card.js View on Github external
return new Promise(function (resolve, reject) {
    const startTime = new Date()
    const data = { cardNumber: parseInt(cardNo) }

    i18n.setLocale(language || 'en')

    // Use a subSegment if passed, otherwise get our main segment
    if (!subSegment) {
      const namespace = getNamespace(NAMESPACE_NAME)
      subSegment = namespace.get(XRAY_SEGMENT_KEY_NAME)
    }

    AWSXRay.captureAsyncFunc('cardIdClient_post', function (postSubsegment) {
      if (cardNo.length > 0 && cardNo.length < 11) {
        postSubsegment.close()
        return reject(new Error(i18n.__('fieldErrors.fields.cardNo.numberIncorrectLength')))
      }
      cardIdClient.post({ payload: data, correlationId: correlationId }, postSubsegment)
        .then((response) => {
          postSubsegment.close()
          logger.info(`[${correlationId}]  - %s to %s ended - total time %dms`, 'POST', cardIdClient.CARD_URL, new Date() - startTime)

          if (response.statusCode === 404) {
            return reject(new Error('Your card is not supported'))
          }
          if (response.statusCode === 422) {
            return reject(new Error(i18n.__('fieldErrors.fields.cardNo.message')))
          }
          // if the server is down, or returns non 500, just continue
github aws-samples / aws-serverless-workshops / DevOps / 3_XRay / uni-api / app / list.js View on Github external
function list_unicorns(callback) {
  var params = {
    TableName: tableName
  };

  AWSXRay.captureAsyncFunc('List Unicorns', (subsegment) => {
    docClient.scan(params, function(err, data) {
      // Comment or Delete the following line of code to remove simulated error
      err = Error("something is wrong");

      if (err) {
        callback(err, null, subsegment);
      } else {
        callback(null, data, subsegment);
      }
    });
  });
}
github aws-samples / aws-serverless-workshops / DevOps / 3_XRay / uni-api / app / list.js View on Github external
function return_from_stable(callback) {
  // Comment or Delete the following line of code to remove simulated delay
  const isDelayed = true;

  AWSXRay.captureAsyncFunc('Return From Stable', (subsegment) => {
    if (typeof isDelayed !== 'undefined' && isDelayed) {
      setTimeout(function() {
        callback(subsegment);
      }, 5000);
    } else {
      callback(subsegment);
    }
  });
}
github alphagov / pay-selfservice / app / controllers / dashboard / dashboard-activity-controller.js View on Github external
const transactionsPeriodString = `fromDate=${encodeURIComponent(datetime(fromDateTime, 'date'))}&fromTime=${encodeURIComponent(datetime(fromDateTime, 'time'))}&toDate=${encodeURIComponent(datetime(toDateTime, 'date'))}&toTime=${encodeURIComponent(datetime(toDateTime, 'time'))}`

    logger.info(`[${correlationId}] successfully logged in`)

    if (isADirectDebitAccount(gatewayAccountId)) {
      // todo implement transaction list for direct debit
      return response(req, res, 'dashboard/index', Object.assign(model, {
        activityError: true
      }))
    }

    const namespace = getNamespace(clsXrayConfig.nameSpaceName)
    const clsSegment = namespace.get(clsXrayConfig.segmentKeyName)

    AWSXRay.captureAsyncFunc('ledgerClient_getTransactionSummary', function (subsegment) {
      LedgerClient.transactionSummary(gatewayAccountId, fromDateTime, toDateTime, { correlationId: correlationId })
        .then(result => {
          subsegment.close()
          response(req, res, 'dashboard/index', Object.assign(model, {
            activity: result,
            successfulTransactionsState: 'payment-success',
            fromDateTime,
            toDateTime,
            transactionsPeriodString
          }))
        })
        .catch((error, ledgerResponse) => {
          subsegment.close(error)
          const status = _.get(ledgerResponse, 'statusCode', 404)
          logger.error(`[${correlationId}] Calling ledger to get transactions summary failed`, {
            service: 'ledger',
github theburningmonk / manning-aws-lambda-in-motion / functions / get-index.js View on Github external
if (subsegment) {
          subsegment.close();
        }
        resolve(body);
      } catch (err) {
        if (subsegment) {
          subsegment.close(err);
        }
        reject(err);
      }
    });

    // the current sub/segment
    let segment = AWSXRay.getSegment();

    AWSXRay.captureAsyncFunc("getting restaurants", f, segment);
  });
}
github alphagov / pay-frontend / app / controllers / web-payments / payment-auth-request-controller.js View on Github external
module.exports = (req, res) => {
  const { chargeId, params, body } = req
  const { provider } = params
  const payload = provider === 'apple' ? normaliseApplePayPayload(body) : normaliseGooglePayPayload(body)
  const namespace = getNamespace(NAMESPACE_NAME)
  const clsSegment = namespace.get(XRAY_SEGMENT_KEY_NAME)
  return AWSXRay.captureAsyncFunc('Auth_charge_wallet', subsegment => {
    return connectorClient({ correlationId: req.headers[CORRELATION_HEADER] }).chargeAuthWithWallet({ chargeId, provider, payload })
      .then(data => {
        subsegment.close()
        setSessionVariable(req, `ch_${(chargeId)}.webPaymentAuthResponse`, {
          statusCode: data.statusCode
        })
        logger.info(`Successful auth for ${provider} Pay payment. ChargeID: ${chargeId}`)
        res.status(200)
        res.send({ url: `/handle-payment-response/${chargeId}` })
      })
      .catch(err => {
        subsegment.close('error')
        logger.error(`Error while trying to authorise ${provider} Pay payment: ${err}`)
        res.status(200)
        res.send({ url: `/handle-payment-response/${chargeId}` })
      })
github alphagov / pay-selfservice / app / services / auth_service.js View on Github external
namespace.run(() => {
    namespace.set(clsXrayConfig.segmentKeyName, segment)
    AWSXRay.captureAsyncFunc('auth_service_deserializeUser', function (subSegment) {
      return userService.findByExternalId(externalId, req.headers[CORRELATION_HEADER] || '', subSegment)
        .then((user) => {
          segment.close()
          done(null, user)
        })
        .catch(err => {
          segment.close(err)
          logger.info(`[${req.correlationId}]: Failed to retrieve user, '${externalId}', from adminusers with statuscode: ${err.errorCode}`)
          done(err)
        })
    }, segment)
  })
}
github alphagov / pay-selfservice / app / middleware / get_gateway_account.js View on Github external
if (directDebitConnectorClient.isADirectDebitAccount(accountId)) {
    return directDebitConnectorClient.gatewayAccount.get(params)
      .then(gatewayAccount => {
        req.account = gatewayAccount
        next()
      })
      .catch(err => {
        logger.error(`${req.correlationId} - Error when attempting to retrieve direct debit gateway account: ${err}`)
        next()
      })
  }

  const namespace = getNamespace(clsXrayConfig.nameSpaceName)
  const clsSegment = namespace.get(clsXrayConfig.segmentKeyName)

  AWSXRay.captureAsyncFunc('connectorClient_getAccount', function (subsegment) {
    return connectorClient.getAccount(params)
      .then(data => {
        subsegment.close()
        req.account = _.extend({}, data, {
          supports3ds: ['worldpay', 'stripe', 'epdq', 'smartpay'].includes(_.get(data, 'payment_provider')),
          disableToggle3ds: _.get(data, 'payment_provider') === 'stripe'
        })
        next()
      })
      .catch(err => {
        subsegment.close(err)
        logger.error(`${req.correlationId} - Error when attempting to retrieve card gateway account: ${err}`)
        next()
      })
  }, clsSegment)
}