-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathstore.go
109 lines (87 loc) · 1.85 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
package memory
import (
"context"
"sync"
"time"
"github.com/code-payments/code-server/pkg/code/data/rendezvous"
)
type store struct {
mu sync.Mutex
last uint64
records []*rendezvous.Record
}
// New returns a new in memory rendezvous.Store
func New() rendezvous.Store {
return &store{}
}
// Save implements rendezvous.Store.Save
func (s *store) Save(_ context.Context, data *rendezvous.Record) error {
if err := data.Validate(); err != nil {
return err
}
s.mu.Lock()
defer s.mu.Unlock()
s.last++
if item := s.find(data); item != nil {
item.Location = data.Location
item.LastUpdatedAt = time.Now()
item.CopyTo(data)
} else {
if data.Id == 0 {
data.Id = s.last
}
data.CreatedAt = time.Now()
data.LastUpdatedAt = time.Now()
cloned := data.Clone()
s.records = append(s.records, &cloned)
}
return nil
}
// Get implements rendezvous.Store.Get
func (s *store) Get(_ context.Context, key string) (*rendezvous.Record, error) {
s.mu.Lock()
defer s.mu.Unlock()
item := s.findByKey(key)
if item == nil {
return nil, rendezvous.ErrNotFound
}
cloned := item.Clone()
return &cloned, nil
}
// Delete implements rendezvous.Store.Delete
func (s *store) Delete(_ context.Context, key string) error {
s.mu.Lock()
defer s.mu.Unlock()
for i, item := range s.records {
if item.Key == key {
s.records = append(s.records[:i], s.records[i+1:]...)
return nil
}
}
return nil
}
func (s *store) find(data *rendezvous.Record) *rendezvous.Record {
for _, item := range s.records {
if item.Id == data.Id {
return item
}
if item.Key == data.Key {
return item
}
}
return nil
}
func (s *store) findByKey(key string) *rendezvous.Record {
for _, item := range s.records {
if item.Key == key {
return item
}
}
return nil
}
func (s *store) reset() {
s.mu.Lock()
defer s.mu.Unlock()
s.last = 0
s.records = nil
}