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