StatsManager.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. const crypto = require('node:crypto')
  2. const { shouldSkipMetrics } = require('./Metrics')
  3. /**
  4. * Consistently sample a keyspace with a given sample percentage.
  5. * The same key will always produce a consistent percentile value that
  6. * can be compared against the sample percentage.
  7. * Example: if key is the userId and the samplePercentage is 10, then
  8. * we see all the activity for the 10% of users who are selected.
  9. *
  10. * @param {string} key - The unique identifier to be hashed and checked.
  11. * @param {number} samplePercentage - The percentage (0-100) of keys that should return true.
  12. * @returns {boolean} - True if the key is within the sample, false otherwise.
  13. */
  14. function sampleByHash(key, samplePercentage) {
  15. if (samplePercentage <= 0) {
  16. return false
  17. }
  18. const hash = crypto.createHash('md5').update(key).digest()
  19. const hashValue = hash.readUInt32BE(0)
  20. const percentile = Math.floor((hashValue / 0xffffffff) * 100)
  21. return percentile < samplePercentage
  22. }
  23. /**
  24. * Determines whether a given request should be sampled based on user ID and sampling percentage.
  25. * The request will not be sampled if it lacks a user_id, if its metrics path is in the exclusion list,
  26. * or if the sampling percentage is zero or less.
  27. *
  28. * @param {object} request - The request object to check.
  29. * @param {string} [request.user_id] - The ID of the user making the request.
  30. * @param {object} [request.metricsOpts] - Metrics options for the request.
  31. * @param {string} [request.metricsOpts.path] - The path associated with the request metrics.
  32. * @param {number} samplingPercentage - The percentage of requests to sample (e.g., 10 for 10%).
  33. * @returns {boolean|undefined} The result from sampleByHash if the request is eligible for sampling, otherwise undefined.
  34. */
  35. function sampleRequest(request, samplingPercentage) {
  36. if (!request.user_id) {
  37. return
  38. }
  39. if (shouldSkipMetrics(request)) {
  40. return
  41. }
  42. if (samplingPercentage > 0) {
  43. return sampleByHash(request.user_id, samplingPercentage)
  44. }
  45. }
  46. module.exports = { sampleByHash, sampleRequest }