StatsManager.js 2.0 KB

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