-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache.go
More file actions
64 lines (57 loc) · 1.75 KB
/
cache.go
File metadata and controls
64 lines (57 loc) · 1.75 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
package main
import "sync"
// NetworkEntry holds the cached state and file path for a single network.
type NetworkEntry struct {
State *NetworkState
FilePath string
}
// NetworkCache is a concurrent-safe cache of per-network entries.
// Pollers write via Set; HTTP handlers read via Get.
type NetworkCache struct {
mu sync.RWMutex
entries map[string]*NetworkEntry
networks []string
}
// NewNetworkCache creates a NetworkCache that expects the given networks.
// Ready returns true only once all expected networks have been cached.
func NewNetworkCache(networks []string) *NetworkCache {
return &NetworkCache{
entries: make(map[string]*NetworkEntry),
networks: networks,
}
}
// Get returns a copy of the entry for the given network, or nil if not cached.
// The caller receives an independent copy so it does not hold the read lock
// during subsequent I/O.
func (nc *NetworkCache) Get(network string) *NetworkEntry {
nc.mu.RLock()
defer nc.mu.RUnlock()
entry := nc.entries[network]
if entry == nil {
return nil
}
// Shallow copy the entry and State so the caller gets an independent copy.
// Strings are immutable in Go, so shallow copy is safe.
stateCopy := *entry.State
return &NetworkEntry{
State: &stateCopy,
FilePath: entry.FilePath,
}
}
// Ready returns true when all expected networks have a cached entry.
func (nc *NetworkCache) Ready() bool {
nc.mu.RLock()
defer nc.mu.RUnlock()
for _, n := range nc.networks {
if nc.entries[n] == nil {
return false
}
}
return true
}
// Set stores or replaces the entry for the given network.
func (nc *NetworkCache) Set(network string, state *NetworkState, filePath string) {
nc.mu.Lock()
defer nc.mu.Unlock()
nc.entries[network] = &NetworkEntry{State: state, FilePath: filePath}
}