-
Notifications
You must be signed in to change notification settings - Fork 0
/
storage.go
53 lines (42 loc) · 1.16 KB
/
storage.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
package synchronizer
import (
"fmt"
"sync"
cloudevents "github.com/cloudevents/sdk-go/v2"
)
// storage holds the map of open connections and corresponding channels.
type storage struct {
sync.Mutex
sessions map[string]chan *cloudevents.Event
}
// newStorage returns an instance of the sessions storage.
func newStorage() *storage {
return &storage{
sessions: make(map[string]chan *cloudevents.Event),
}
}
// add creates the new communication channel and adds it to the session storage.
func (s *storage) add(id string) (<-chan *cloudevents.Event, error) {
s.Lock()
defer s.Unlock()
if _, exists := s.sessions[id]; exists {
return nil, fmt.Errorf("session already exists")
}
c := make(chan *cloudevents.Event)
s.sessions[id] = c
return c, nil
}
// delete closes the communication channel and removes it from the storage.
func (s *storage) delete(id string) {
s.Lock()
defer s.Unlock()
close(s.sessions[id])
delete(s.sessions, id)
}
// open returns the communication channel for the session id.
func (s *storage) get(id string) (chan<- *cloudevents.Event, bool) {
s.Lock()
defer s.Unlock()
session, exists := s.sessions[id]
return session, exists
}