-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstore.go
89 lines (67 loc) · 1.71 KB
/
store.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
package varto
import "sync"
// Store defines the interface for different store implementations
type Store interface {
AddConnection(conn Connection) error
RemoveConnection(conn Connection) error
GetAllConnections() ([]Connection, error)
AddTopic(name string) (Topic, error)
GetTopic(name string) (Topic, error)
RemoveTopic(name string) error
}
type inMemoryStore struct {
sync.RWMutex
connections map[string]Connection
topics map[string]Topic
}
func newInMemoryStore() *inMemoryStore {
return &inMemoryStore{
connections: make(map[string]Connection),
topics: make(map[string]Topic),
}
}
func (s *inMemoryStore) GetTopic(topicName string) (Topic, error) {
s.Lock()
defer s.Unlock()
if _, ok := s.topics[topicName]; !ok {
return nil, ErrTopicNotFound
}
return s.topics[topicName], nil
}
func (s *inMemoryStore) AddTopic(topicName string) (Topic, error) {
s.Lock()
defer s.Unlock()
newTopic := NewTopic(topicName)
s.topics[topicName] = newTopic
return newTopic, nil
}
func (s *inMemoryStore) RemoveTopic(topicName string) error {
s.Lock()
defer s.Unlock()
delete(s.topics, topicName)
return nil
}
func (s *inMemoryStore) AddConnection(conn Connection) error {
s.Lock()
defer s.Unlock()
s.connections[conn.GetId()] = conn
return nil
}
func (s *inMemoryStore) RemoveConnection(conn Connection) error {
s.Lock()
defer s.Unlock()
delete(s.connections, conn.GetId())
for _, topic := range s.topics {
topic.Unsubscribe(conn)
}
return nil
}
func (s *inMemoryStore) GetAllConnections() ([]Connection, error) {
s.RLock()
defer s.RUnlock()
var connections []Connection
for conn := range s.connections {
connections = append(connections, s.connections[conn])
}
return connections, nil
}