UserAnalyticsIdCache.mjs 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import UserGetter from '../User/UserGetter.mjs'
  2. import { CacheLoader } from 'cache-flow'
  3. import { callbackify } from 'node:util'
  4. import Metrics from '@overleaf/metrics'
  5. class UserAnalyticsIdCache extends CacheLoader {
  6. constructor() {
  7. super('user-analytics-id', {
  8. expirationTime: 60,
  9. maxSize: 10000,
  10. })
  11. }
  12. async load(userId) {
  13. const user = await UserGetter.promises.getUser(userId, { analyticsId: 1 })
  14. if (user) {
  15. return user.analyticsId || user._id.toString()
  16. }
  17. }
  18. keyToString(userId) {
  19. if (userId) {
  20. return userId.toString()
  21. }
  22. }
  23. get() {
  24. throw new Error('use UserAnalyticsIdCache.getWithMetrics')
  25. }
  26. async getWithMetrics(userId, path) {
  27. const { value, cached } = await this.getWithMetadata(userId)
  28. Metrics.inc('user_analytics_id_cache', 1, {
  29. status: cached ? 'hit' : 'miss',
  30. path,
  31. })
  32. return value
  33. }
  34. }
  35. const userAnalyticsIdCache = new UserAnalyticsIdCache()
  36. userAnalyticsIdCache.callbacks = {
  37. get: callbackify(userAnalyticsIdCache.get).bind(userAnalyticsIdCache),
  38. }
  39. export default userAnalyticsIdCache