loggingMap.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. const (
  16. expireAfter = 2 * time.Minute
  17. cleanupInterval = 1 * time.Minute
  18. )
  19. // NewLoggingMap creates the map used to track requests for which we should log responses.
  20. func NewLoggingMap() *LoggingMap {
  21. return &LoggingMap{
  22. loggingMap: make(map[string]time.Time),
  23. }
  24. }
  25. // Start starts a go routine to clean up the loggingMap.
  26. func (lm *LoggingMap) Start(ctx context.Context, _ *zap.Logger, errC chan error) {
  27. common.RunWithScissors(ctx, errC, "logging_cleanup", func(ctx context.Context) error {
  28. ticker := time.NewTicker(cleanupInterval)
  29. defer ticker.Stop()
  30. for {
  31. select {
  32. case <-ctx.Done():
  33. return nil
  34. case <-ticker.C:
  35. lm.CleanUp()
  36. }
  37. }
  38. })
  39. }
  40. // CleanUp iterates over the map and removes all entries that are expired.
  41. func (lm *LoggingMap) CleanUp() {
  42. lm.loggingLock.Lock()
  43. defer lm.loggingLock.Unlock()
  44. for requestId, cleanUpTime := range lm.loggingMap {
  45. if time.Now().After(cleanUpTime) {
  46. delete(lm.loggingMap, requestId)
  47. }
  48. }
  49. }
  50. // AddRequest adds a request to the map, giving it an expiration time.
  51. func (lm *LoggingMap) AddRequest(requestSignature string) {
  52. lm.loggingLock.Lock()
  53. defer lm.loggingLock.Unlock()
  54. lm.loggingMap[requestSignature] = time.Now().Add(expireAfter)
  55. }
  56. // ShouldLogResponse returns true if the request is in the map.
  57. func (lm *LoggingMap) ShouldLogResponse(requestSignature string) bool {
  58. lm.loggingLock.Lock()
  59. defer lm.loggingLock.Unlock()
  60. if _, exists := lm.loggingMap[requestSignature]; exists {
  61. return true
  62. }
  63. return false
  64. }