loggingMap.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package ccq
  2. import (
  3. "context"
  4. "sync"
  5. "time"
  6. "github.com/certusone/wormhole/node/pkg/common"
  7. "go.uber.org/zap"
  8. )
  9. // LoggingMap is used to track the requests for which we should log response. It contains a map keyed by the request signature
  10. // where the payload is time the request was received. Requests will be removed from the map after two minutes.
  11. type LoggingMap struct {
  12. loggingLock sync.Mutex
  13. loggingMap map[string]time.Time
  14. }
  15. // NewLoggingMap creates the map used to track requests for which we should log responses.
  16. func NewLoggingMap() *LoggingMap {
  17. return &LoggingMap{
  18. loggingMap: make(map[string]time.Time),
  19. }
  20. }
  21. // Start starts a go routine to clean up requests that have been in the map for two minutes.
  22. func (lm *LoggingMap) Start(ctx context.Context, logger *zap.Logger, errC chan error) {
  23. common.RunWithScissors(ctx, errC, "logging_cleanup", func(ctx context.Context) error {
  24. ticker := time.NewTicker(1 * time.Minute)
  25. defer ticker.Stop()
  26. for {
  27. select {
  28. case <-ctx.Done():
  29. return nil
  30. case <-ticker.C:
  31. lm.CleanUp(logger)
  32. }
  33. }
  34. })
  35. }
  36. // CleanUp iterates over the map and removes all entries that are more than two minutes old.
  37. func (lm *LoggingMap) CleanUp(logger *zap.Logger) {
  38. lm.loggingLock.Lock()
  39. defer lm.loggingLock.Unlock()
  40. for requestId, cleanUpTime := range lm.loggingMap {
  41. if time.Now().After(cleanUpTime) {
  42. delete(lm.loggingMap, requestId)
  43. }
  44. }
  45. }
  46. // AddRequest adds a request to the map, giving it an expiration time two minutes into the future.
  47. func (lm *LoggingMap) AddRequest(requestSignature string) {
  48. lm.loggingLock.Lock()
  49. defer lm.loggingLock.Unlock()
  50. lm.loggingMap[requestSignature] = time.Now().Add(2 * time.Minute)
  51. }
  52. // ShouldLogResponse returns true if the request is in the map.
  53. func (lm *LoggingMap) ShouldLogResponse(requestSignature string) bool {
  54. lm.loggingLock.Lock()
  55. defer lm.loggingLock.Unlock()
  56. if _, exists := lm.loggingMap[requestSignature]; exists {
  57. return true
  58. }
  59. return false
  60. }