in_memory_store.go raw
1 // Copyright 2022-2025 The sacloud/iaas-api-go Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package fake
16
17 import (
18 "fmt"
19 "sync"
20
21 "github.com/sacloud/iaas-api-go/types"
22 )
23
24 // InMemoryStore データをメモリ上に保存するためのデータストア
25 type InMemoryStore struct {
26 data map[string]map[string]interface{}
27 mu sync.Mutex
28 }
29
30 // NewInMemoryStore .
31 func NewInMemoryStore() *InMemoryStore {
32 return &InMemoryStore{
33 data: make(map[string]map[string]interface{}),
34 }
35 }
36
37 // Init .
38 func (s *InMemoryStore) Init() error {
39 return nil
40 }
41
42 // NeedInitData .
43 func (s *InMemoryStore) NeedInitData() bool {
44 return true
45 }
46
47 // Put .
48 func (s *InMemoryStore) Put(resourceKey, zone string, id types.ID, value interface{}) {
49 s.mu.Lock()
50 defer s.mu.Unlock()
51
52 values := s.values(resourceKey, zone)
53 if values == nil {
54 values = map[string]interface{}{}
55 }
56 values[id.String()] = value
57 s.data[s.key(resourceKey, zone)] = values
58 }
59
60 // Get .
61 func (s *InMemoryStore) Get(resourceKey, zone string, id types.ID) interface{} {
62 s.mu.Lock()
63 defer s.mu.Unlock()
64
65 values := s.values(resourceKey, zone)
66 if values == nil {
67 return nil
68 }
69 return values[id.String()]
70 }
71
72 // List .
73 func (s *InMemoryStore) List(resourceKey, zone string) []interface{} {
74 s.mu.Lock()
75 defer s.mu.Unlock()
76
77 values := s.values(resourceKey, zone)
78 var ret []interface{}
79 for _, v := range values {
80 ret = append(ret, v)
81 }
82 return ret
83 }
84
85 // Delete .
86 func (s *InMemoryStore) Delete(resourceKey, zone string, id types.ID) {
87 s.mu.Lock()
88 defer s.mu.Unlock()
89
90 values := s.values(resourceKey, zone)
91 if values != nil {
92 delete(values, id.String())
93 }
94 }
95
96 func (s *InMemoryStore) key(resourceKey, zone string) string {
97 return fmt.Sprintf("%s/%s", resourceKey, zone)
98 }
99
100 func (s *InMemoryStore) values(resourceKey, zone string) map[string]interface{} {
101 return s.data[s.key(resourceKey, zone)]
102 }
103