CoolFace
Apppublic

strong-tie/inbound-calls

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
reqIdGenFactory.js53 linesDownload Raw Back to lib
1'use strict'2 3/**4 * @callback GenerateRequestId5 * @param {Object} req6 * @returns {string}7 */8 9/**10 * @param {string} [requestIdHeader]11 * @param {GenerateRequestId} [optGenReqId]12 * @returns {GenerateRequestId}13 */14function reqIdGenFactory (requestIdHeader, optGenReqId) {15  const genReqId = optGenReqId || buildDefaultGenReqId()16 17  if (requestIdHeader) {18    return buildOptionalHeaderReqId(requestIdHeader, genReqId)19  }20 21  return genReqId22}23 24function getGenReqId (contextServer, req) {25  return contextServer.genReqId(req)26}27 28function buildDefaultGenReqId () {29  // 2,147,483,647 (2^31 − 1) stands for max SMI value (an internal optimization of V8).30  // With this upper bound, if you'll be generating 1k ids/sec, you're going to hit it in ~25 days.31  // This is very likely to happen in real-world applications, hence the limit is enforced.32  // Growing beyond this value will make the id generation slower and cause a deopt.33  // In the worst cases, it will become a float, losing accuracy.34  const maxInt = 214748364735 36  let nextReqId = 037  return function defaultGenReqId () {38    nextReqId = (nextReqId + 1) & maxInt39    return `req-${nextReqId.toString(36)}`40  }41}42 43function buildOptionalHeaderReqId (requestIdHeader, genReqId) {44  return function (req) {45    return req.headers[requestIdHeader] || genReqId(req)46  }47}48 49module.exports = {50  getGenReqId,51  reqIdGenFactory52}53