-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathwebhook_services_cache.go
More file actions
73 lines (59 loc) · 1.85 KB
/
Copy pathwebhook_services_cache.go
File metadata and controls
73 lines (59 loc) · 1.85 KB
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
70
71
72
73
package webhook_traffic
import (
"fmt"
"github.com/hashicorp/golang-lru/v2/expirable"
"github.com/otterize/intents-operator/src/shared/errors"
"github.com/otterize/network-mapper/src/mapper/pkg/cloudclient"
"github.com/otterize/network-mapper/src/mapper/pkg/config"
"github.com/samber/lo"
"github.com/sirupsen/logrus"
"github.com/spf13/viper"
"golang.org/x/exp/slices"
"hash/crc32"
"time"
)
const (
cacheTTL = 5 * time.Hour
)
type CacheValue []byte
type WebhookServicesCache struct {
cache *expirable.LRU[string, CacheValue]
}
func NewWebhookServicesCache() *WebhookServicesCache {
size := viper.GetInt(config.WebhookServicesCacheSizeKey)
cache := expirable.NewLRU[string, CacheValue](size, OnEvict, cacheTTL)
return &WebhookServicesCache{
cache: cache,
}
}
func (c *WebhookServicesCache) Get() (CacheValue, bool) {
return c.cache.Get("webhooks")
}
func (c *WebhookServicesCache) Set(value CacheValue) bool {
return c.cache.Add("webhooks", value)
}
func K8sWebhookServiceInputKey(webhookService cloudclient.K8sWebhookServiceInput) string {
return fmt.Sprintf("%s#%s#%s#%s",
webhookService.Identity.Namespace,
webhookService.Identity.Name,
webhookService.WebhookName,
webhookService.WebhookType)
}
func (c *WebhookServicesCache) GenerateValue(webhookServices []cloudclient.K8sWebhookServiceInput) (CacheValue, error) {
values := lo.Map(webhookServices, func(item cloudclient.K8sWebhookServiceInput, _ int) string {
return K8sWebhookServiceInputKey(item)
})
slices.Sort(values)
hash := crc32.NewIEEE()
for _, value := range values {
_, err := hash.Write([]byte(value))
if err != nil {
return nil, errors.Wrap(err)
}
}
hashSum := hash.Sum(nil)
return hashSum, nil
}
func OnEvict(key string, _ CacheValue) {
logrus.WithField("namespace", key).Debug("key evicted from cache, you may change configuration to increase cache size")
}