EventLogger.coffee 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. logger = require 'logger-sharelatex'
  2. metrics = require 'metrics-sharelatex'
  3. # keep track of message counters to detect duplicate and out of order events
  4. # messsage ids have the format "UNIQUEHOSTKEY-COUNTER"
  5. EVENT_LOG_COUNTER = {}
  6. EVENT_LOG_TIMESTAMP = {}
  7. EVENT_LAST_CLEAN_TIMESTAMP = 0
  8. module.exports = EventLogger =
  9. MAX_STALE_TIME_IN_MS: 3600 * 1000
  10. checkEventOrder: (channel, message_id, message) ->
  11. return if typeof(message_id) isnt 'string'
  12. return if !(result = message_id.match(/^(.*)-(\d+)$/))
  13. key = result[1]
  14. count = parseInt(result[2], 0)
  15. if !(count >= 0)# ignore checks if counter is not present
  16. return
  17. # store the last count in a hash for each host
  18. previous = EventLogger._storeEventCount(key, count)
  19. if !previous? || count == (previous + 1)
  20. metrics.inc "event.#{channel}.valid", 0.001 # downsample high rate docupdater events
  21. return # order is ok
  22. if (count == previous)
  23. metrics.inc "event.#{channel}.duplicate"
  24. # logger.error {key:key, previous: previous, count:count, message:message}, "duplicate event"
  25. return "duplicate"
  26. else
  27. metrics.inc "event.#{channel}.out-of-order"
  28. # logger.error {key:key, previous: previous, count:count, message:message}, "events out of order"
  29. return "out-of-order"
  30. _storeEventCount: (key, count) ->
  31. previous = EVENT_LOG_COUNTER[key]
  32. now = Date.now()
  33. EVENT_LOG_COUNTER[key] = count
  34. EVENT_LOG_TIMESTAMP[key] = now
  35. # periodically remove old counts
  36. if (now - EVENT_LAST_CLEAN_TIMESTAMP) > EventLogger.MAX_STALE_TIME_IN_MS
  37. EventLogger._cleanEventStream(now)
  38. EVENT_LAST_CLEAN_TIMESTAMP = now
  39. return previous
  40. _cleanEventStream: (now) ->
  41. for key, timestamp of EVENT_LOG_TIMESTAMP
  42. if (now - timestamp) > EventLogger.MAX_STALE_TIME_IN_MS
  43. delete EVENT_LOG_COUNTER[key]
  44. delete EVENT_LOG_TIMESTAMP[key]