forked from kyma-project/kyma
-
Notifications
You must be signed in to change notification settings - Fork 0
/
entity_instance.go
110 lines (83 loc) · 2.1 KB
/
entity_instance.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
package memory
import (
"github.com/kyma-project/kyma/components/remote-environment-broker/internal"
"github.com/pkg/errors"
)
// NewInstance creates new Instances storage
func NewInstance() *Instance {
return &Instance{
storage: make(map[internal.InstanceID]*internal.Instance),
}
}
// Instance implements in-memory storage for Instance entities.
type Instance struct {
threadSafeStorage
storage map[internal.InstanceID]*internal.Instance
}
// Insert inserts object to storage.
func (s *Instance) Insert(i *internal.Instance) error {
defer unlock(s.lockW())
if i == nil {
return errors.New("entity may not be nil")
}
if i.ID.IsZero() {
return errors.New("instance id must be set")
}
if _, found := s.storage[i.ID]; found {
return alreadyExistsError{}
}
s.storage[i.ID] = i
return nil
}
// Get returns object from storage.
func (s *Instance) Get(id internal.InstanceID) (*internal.Instance, error) {
defer unlock(s.lockR())
i, found := s.storage[id]
if !found {
return nil, notFoundError{}
}
return i, nil
}
func (s *Instance) get(iID internal.InstanceID) (*internal.Instance, error) {
if iID.IsZero() {
return nil, errors.New("instance id must be set")
}
if _, found := s.storage[iID]; !found {
return nil, notFoundError{}
}
i, found := s.storage[iID]
if !found {
return nil, notFoundError{}
}
return i, nil
}
// Remove removing object from storage.
func (s *Instance) Remove(id internal.InstanceID) error {
defer unlock(s.lockW())
_, found := s.storage[id]
if !found {
return notFoundError{}
}
delete(s.storage, id)
return nil
}
// FindOne returns from storage first object which passes the match.
func (s *Instance) FindOne(m func(i *internal.Instance) bool) (*internal.Instance, error) {
defer unlock(s.lockW())
for iID, i := range s.storage {
if m(i) {
return s.storage[iID], nil
}
}
return nil, nil
}
// UpdateState modifies state on object in storage.
func (s *Instance) UpdateState(iID internal.InstanceID, state internal.InstanceState) error {
defer unlock(s.lockW())
i, err := s.get(iID)
if err != nil {
return err
}
i.State = state
return nil
}