-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathstore.go
114 lines (90 loc) · 1.63 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package client
import (
"encoding/json"
"errors"
"sync"
"time"
"github.com/blushft/jitsuclient/event"
)
type StoreEvent struct {
ID string
Event []byte
Attempted bool
Attempts int
LastAttempt time.Time
}
type Store interface {
Set(*event.Event) error
Update(*StoreEvent) error
Remove(*StoreEvent) error
Get(string) (*StoreEvent, error)
GetAll() ([]*StoreEvent, error)
Count() int
}
type memStore struct {
m map[string][]byte
mu sync.RWMutex
}
func NewMemStore() (Store, error) {
return &memStore{
m: make(map[string][]byte),
}, nil
}
func (s *memStore) Set(evt *event.Event) error {
pl, err := evt.Render()
if err != nil {
return err
}
se := &StoreEvent{
ID: evt.ID,
Event: pl,
Attempted: false,
Attempts: 0,
}
return s.Update(se)
}
func (s *memStore) Update(se *StoreEvent) error {
b, err := json.Marshal(se)
if err != nil {
return err
}
s.mu.Lock()
s.m[se.ID] = b
s.mu.Unlock()
return nil
}
func (s *memStore) Remove(se *StoreEvent) error {
s.mu.Lock()
delete(s.m, se.ID)
s.mu.Unlock()
return nil
}
func (s *memStore) Get(id string) (*StoreEvent, error) {
s.mu.RLock()
defer s.mu.RUnlock()
b, ok := s.m[id]
if !ok {
return nil, errors.New("not found")
}
var se *StoreEvent
if err := json.Unmarshal(b, &se); err != nil {
return nil, err
}
return se, nil
}
func (s *memStore) GetAll() ([]*StoreEvent, error) {
var ses []*StoreEvent
for k := range s.m {
se, err := s.Get(k)
if err != nil {
return nil, err
}
ses = append(ses, se)
}
return ses, nil
}
func (s *memStore) Count() int {
s.mu.RLock()
defer s.mu.RUnlock()
return len(s.m)
}