-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcache.go
103 lines (82 loc) · 1.98 KB
/
cache.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package caddy_clienthello
import (
"sync"
"github.com/caddyserver/caddy/v2"
"time"
)
const (
CacheAppId = "client_hello.cache"
)
func init() {
caddy.RegisterModule(Cache{})
}
const MaxCacheSize = 1000 // Maximum number of entries in the cache
type CacheEntry struct {
Value string
Expiration int64
}
type Cache struct {
clientHellos map[string]CacheEntry
lock sync.RWMutex
}
func (c *Cache) Provision(_ caddy.Context) error {
c.clientHellos = make(map[string]CacheEntry)
return nil
}
func (c *Cache) SetClientHello(addr string, encoded string) error {
c.lock.Lock()
defer c.lock.Unlock()
// Set an expiration time for the cache (e.g., 1 hour)
expiration := time.Now().Add(1 * time.Hour).Unix()
// Check cache size and evict if needed
if len(c.clientHellos) >= MaxCacheSize {
// Eviction strategy (e.g., remove the first element or an LRU item)
for key := range c.clientHellos {
delete(c.clientHellos, key)
break
}
}
c.clientHellos[addr] = CacheEntry{
Value: encoded,
Expiration: expiration,
}
return nil
}
func (c *Cache) ClearClientHello(addr string) {
c.lock.Lock()
defer c.lock.Unlock()
delete(c.clientHellos, addr)
}
func (c *Cache) GetClientHello(addr string) *string {
c.lock.RLock()
defer c.lock.RUnlock()
entry, found := c.clientHellos[addr]
if !found {
return nil // Entry doesn't exist
}
if entry.Expiration < time.Now().Unix() {
c.ClearClientHello(addr)
return nil // Entry expired
}
return &entry.Value
}
// CaddyModule implements caddy.Module
func (Cache) CaddyModule() caddy.ModuleInfo {
return caddy.ModuleInfo{
ID: CacheAppId,
New: func() caddy.Module { return new(Cache) },
}
}
// Start implements caddy.App
func (c *Cache) Start() error {
return nil
}
// Stop implements caddy.App
func (c *Cache) Stop() error {
return nil
}
// Interface guards
var (
_ caddy.App = (*Cache)(nil)
_ caddy.Provisioner = (*Cache)(nil)
)