-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathstore.go
90 lines (75 loc) · 1.56 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
package memory
import (
"bytes"
"context"
"sync"
"time"
"github.com/google/uuid"
"github.com/code-payments/code-server/pkg/code/data/onramp"
)
type store struct {
mu sync.Mutex
records []*onramp.Record
last uint64
}
// New returns a new in memory onramp.Store
func New() onramp.Store {
return &store{}
}
// Put implements onramp.Store.Put
func (s *store) Put(_ context.Context, data *onramp.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 {
return onramp.ErrPurchaseAlreadyExists
} else {
if data.Id == 0 {
data.Id = s.last
}
if data.CreatedAt.IsZero() {
data.CreatedAt = time.Now()
}
c := data.Clone()
s.records = append(s.records, &c)
}
return nil
}
// Get implements onramp.Store.Get
func (s *store) Get(_ context.Context, nonce uuid.UUID) (*onramp.Record, error) {
s.mu.Lock()
defer s.mu.Unlock()
if item := s.findByNonce(nonce); item != nil {
cloned := item.Clone()
return &cloned, nil
}
return nil, onramp.ErrPurchaseNotFound
}
func (s *store) find(data *onramp.Record) *onramp.Record {
for _, item := range s.records {
if item.Id == data.Id {
return item
}
if bytes.Equal(data.Nonce[:], item.Nonce[:]) {
return item
}
}
return nil
}
func (s *store) findByNonce(nonce uuid.UUID) *onramp.Record {
for _, item := range s.records {
if bytes.Equal(nonce[:], item.Nonce[:]) {
return item
}
}
return nil
}
func (s *store) reset() {
s.mu.Lock()
defer s.mu.Unlock()
s.records = nil
s.last = 0
}