Debian Codegraph @

tools/kv/keyvaluestore.go

raw symbols SCIP
1 package kv
2
3 import (
4 "encoding/gob"
5 "io"
6 "os"
7 "sync"
8
9 "github.com/git-lfs/git-lfs/v3/errors"
10 "github.com/git-lfs/git-lfs/v3/tr"
11 )
12
13 // Store provides an in-memory key/value store which is persisted to
14 // a file. The file handle itself is not kept locked for the duration; it is
15 // only locked during load and save, to make it concurrency friendly. When
16 // saving, the store uses optimistic locking to determine whether the db on disk
17 // has been modified by another process; in which case it loads the latest
18 // version and re-applies modifications made during this session. This means
19 // the Lost Update db concurrency issue is possible; so don't use this if you
20 // need more DB integrity than Read Committed isolation levels.
21 type Store struct {
22 // Locks the entire store
23 mu sync.RWMutex
24 filename string
25 log []change
26
27 // This is the persistent data
28 // version for optimistic locking, this field is incremented with every Save()
29 version int64
30 db map[string]interface{}
31 }
32
33 // Type of operation; set or remove
34 type operation int
35
36 const (
37 // Set a value for a key
38 setOperation = operation(iota)
39 // Removed a value for a key
40 removeOperation = operation(iota)
41 )
42
43 type change struct {
44 op operation
45 key string
46 value interface{}
47 }
48
49 // NewStore creates a new key/value store and initialises it with contents from
50 // the named file, if it exists
51 func NewStore(filepath string) (*Store, error) {
52 kv := &Store{filename: filepath, db: make(map[string]interface{})}
53 return kv, kv.loadAndMergeIfNeeded()
54 }
55
56 // Set updates the key/value store in memory
57 // Changes are not persisted until you call Save()
58 func (k *Store) Set(key string, value interface{}) {
59 k.mu.Lock()
60 defer k.mu.Unlock()
61
62 k.db[key] = value
63 k.logChange(setOperation, key, value)
64 }
65
66 // Remove removes the key and its value from the store in memory
67 // Changes are not persisted until you call Save()
68 func (k *Store) Remove(key string) {
69 k.mu.Lock()
70 defer k.mu.Unlock()
71
72 delete(k.db, key)
73 k.logChange(removeOperation, key, nil)
74 }
75
76 // RemoveAll removes all entries from the store
77 // These changes are not persisted until you call Save()
78 func (k *Store) RemoveAll() {
79 k.mu.Lock()
80 defer k.mu.Unlock()
81
82 // Log all changes
83 for key, _ := range k.db {
84 k.logChange(removeOperation, key, nil)
85 }
86 k.db = make(map[string]interface{})
87 }
88
89 // Visit walks through the entire store via a function; return false from
90 // your visitor function to halt the walk
91 func (k *Store) Visit(cb func(string, interface{}) bool) {
92 // Read-only lock
93 k.mu.RLock()
94 defer k.mu.RUnlock()
95
96 for k, v := range k.db {
97 if !cb(k, v) {
98 break
99 }
100 }
101 }
102
103 // Append a change to the log; mutex must already be locked
104 func (k *Store) logChange(op operation, key string, value interface{}) {
105 k.log = append(k.log, change{op, key, value})
106 }
107
108 // Get retrieves a value from the store, or nil if it is not present
109 func (k *Store) Get(key string) interface{} {
110 // Read-only lock
111 k.mu.RLock()
112 defer k.mu.RUnlock()
113
114 // zero value of interface{} is nil so this does what we want
115 return k.db[key]
116 }
117
118 // Save persists the changes made to disk
119 // If any changes have been written by other code they will be merged
120 func (k *Store) Save() error {
121 k.mu.Lock()
122 defer k.mu.Unlock()
123
124 // Short-circuit if we have no changes
125 if len(k.log) == 0 {
126 return nil
127 }
128
129 // firstly peek at version; open read/write to keep lock between check & write
130 f, err := os.OpenFile(k.filename, os.O_RDWR|os.O_CREATE, 0664)
131 if err != nil {
132 return err
133 }
134
135 defer f.Close()
136
137 // Only try to merge if > 0 bytes, ignore empty files (decoder will fail)
138 if stat, _ := f.Stat(); stat.Size() > 0 {
139 k.loadAndMergeReaderIfNeeded(f)
140 // Now we overwrite the file
141 f.Seek(0, io.SeekStart)
142 f.Truncate(0)
143 }
144
145 k.version++
146
147 enc := gob.NewEncoder(f)
148 if err := enc.Encode(k.version); err != nil {
149 return errors.New(tr.Tr.Get("error while writing version data to %v: %v", k.filename, err))
150 }
151 if err := enc.Encode(k.db); err != nil {
152 return errors.New(tr.Tr.Get("error while writing new key/value data to %v: %v", k.filename, err))
153 }
154 // Clear log now that it's saved
155 k.log = nil
156
157 return nil
158 }
159
160 // Reads as little as possible from the passed in file to determine if the
161 // contents are different from the version already held. If so, reads the
162 // contents and merges with any outstanding changes. If not, stops early without
163 // reading the rest of the file
164 func (k *Store) loadAndMergeIfNeeded() error {
165 stat, err := os.Stat(k.filename)
166 if err != nil {
167 if os.IsNotExist(err) {
168 return nil // missing is OK
169 }
170 return err
171 }
172 // Do nothing if empty file
173 if stat.Size() == 0 {
174 return nil
175 }
176
177 f, err := os.OpenFile(k.filename, os.O_RDONLY, 0664)
178 if err == nil {
179 defer f.Close()
180 return k.loadAndMergeReaderIfNeeded(f)
181 } else {
182 return err
183 }
184 }
185
186 // As loadAndMergeIfNeeded but lets caller decide how to manage file handles
187 func (k *Store) loadAndMergeReaderIfNeeded(f io.Reader) error {
188 var versionOnDisk int64
189 // Decode *only* the version field to check whether anyone else has
190 // modified the db; gob serializes structs in order so it will always be 1st
191 dec := gob.NewDecoder(f)
192 err := dec.Decode(&versionOnDisk)
193 if err != nil {
194 return errors.New(tr.Tr.Get("problem checking version of key/value data from %v: %v", k.filename, err))
195 }
196 // Totally uninitialised Version == 0, saved versions are always >=1
197 if versionOnDisk != k.version {
198 // Reload data & merge
199 var dbOnDisk map[string]interface{}
200 err = dec.Decode(&dbOnDisk)
201 if err != nil {
202 return errors.New(tr.Tr.Get("problem reading updated key/value data from %v: %v", k.filename, err))
203 }
204 k.reapplyChanges(dbOnDisk)
205 k.version = versionOnDisk
206 }
207 return nil
208 }
209
210 // reapplyChanges replays the changes made since the last load onto baseDb
211 // and stores the result as our own DB
212 func (k *Store) reapplyChanges(baseDb map[string]interface{}) {
213 for _, change := range k.log {
214 switch change.op {
215 case setOperation:
216 baseDb[change.key] = change.value
217 case removeOperation:
218 delete(baseDb, change.key)
219 }
220 }
221 // Note, log is not cleared here, that only happens on Save since it's a
222 // list of unsaved changes
223 k.db = baseDb
224
225 }
226
227 // RegisterTypeForStorage registers a custom type (e.g. a struct) for
228 // use in the key value store. This is necessary if you intend to pass custom
229 // structs to Store.Set() rather than primitive types.
230 func RegisterTypeForStorage(val interface{}) {
231 gob.Register(val)
232 }