-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstorage.go
290 lines (244 loc) · 7.16 KB
/
storage.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
package stuber
import (
"errors"
"iter"
"strings"
"sync"
"github.com/google/uuid"
"github.com/zeebo/xxh3"
)
// ErrLeftNotFound is returned when the left value is not found.
var ErrLeftNotFound = errors.New("left not found")
// ErrRightNotFound is returned when the right value is not found.
var ErrRightNotFound = errors.New("right not found")
// Value is a type used to store the result of a search.
type Value interface {
Key() uuid.UUID
Left() string
Right() string
}
// storage is responsible for managing search results with enhanced
// performance and memory efficiency. It supports concurrent access
// through the use of a read-write mutex.
//
// Fields:
// - mu: Ensures safe concurrent access to the storage.
// - lefts: A map that tracks unique left values by their hashed IDs.
// - items: Stores items by a composite key of hashed left and right IDs.
// - itemsByID: Provides quick access to items by their unique UUIDs.
type storage struct {
mu sync.RWMutex
lefts map[uint32]struct{}
items map[uint64]map[uuid.UUID]Value
itemsByID map[uuid.UUID]Value
itemMapPool *sync.Pool
}
// newStorage creates a new instance of the storage struct.
func newStorage() *storage {
return &storage{
lefts: make(map[uint32]struct{}),
items: make(map[uint64]map[uuid.UUID]Value),
itemsByID: make(map[uuid.UUID]Value),
itemMapPool: &sync.Pool{
New: func() any {
return make(map[uuid.UUID]Value, 1)
},
},
}
}
// clear resets the storage.
func (s *storage) clear() {
s.mu.Lock()
defer s.mu.Unlock()
s.lefts = make(map[uint32]struct{})
s.items = make(map[uint64]map[uuid.UUID]Value)
s.itemsByID = make(map[uuid.UUID]Value)
}
// values returns an iterator sequence of all Value items stored in the
// storage.
func (s *storage) values() iter.Seq[Value] {
return func(yield func(Value) bool) {
s.mu.RLock()
defer s.mu.RUnlock()
for _, v := range s.itemsByID {
if !yield(v) {
return
}
}
}
}
// findAll retrieves all Value items that match the given left and right names.
// It returns an iterator sequence of the matched Value items or an error if the
// names are not found.
//
// Parameters:
// - left: The left name for matching.
// - right: The right name for matching.
//
// Returns:
// - iter.Seq[Value]: A sequence of matched Value items.
// - error: An error if the left or right name is not found.
func (s *storage) findAll(left, right string) (iter.Seq[Value], error) {
indexes, err := s.posByPN(left, right)
if err != nil {
return nil, err
}
return func(yield func(Value) bool) {
s.mu.RLock()
defer s.mu.RUnlock()
for _, index := range indexes {
for _, v := range s.items[index] {
if !yield(v) {
return
}
}
}
}, nil
}
// posByPN attempts to resolve IDs for a given left and right name pair.
// It first tries to resolve the full left name with the right name, and then
// attempts to resolve using a truncated version of the left name if necessary.
//
// Parameters:
// - left: The left name for matching.
// - right: The right name for matching.
//
// Returns:
// - [][2]uint64: A slice of resolved ID pairs.
// - error: An error if no IDs were resolved.
func (s *storage) posByPN(left, right string) ([]uint64, error) {
// Initialize a slice to store the resolved IDs.
var resolvedIDs []uint64
// Attempt to resolve the full left name with the right name.
id, err := s.posByN(left, right)
if err == nil {
// Append the resolved ID to the slice.
resolvedIDs = append(resolvedIDs, id)
}
// Check for a potential truncation point in the left name.
if dotIndex := strings.LastIndex(left, "."); dotIndex != -1 {
truncatedLeft := left[dotIndex+1:]
// Attempt to resolve the truncated left name with the right name.
if id, err := s.posByN(truncatedLeft, right); err == nil {
// Append the resolved ID to the slice.
resolvedIDs = append(resolvedIDs, id)
} else if errors.Is(err, ErrRightNotFound) && len(resolvedIDs) == 0 {
// Return an error if the right name was not found
// and no IDs were resolved.
return nil, err
}
}
// Return an error if no IDs were resolved.
if len(resolvedIDs) == 0 {
// Return the original error if we have it.
return nil, err
}
// Return the resolved IDs.
return resolvedIDs, nil
}
// findByID retrieves the Stub value associated with the given UUID from the
// storage.
//
// Parameters:
// - key: The UUID of the Stub value to retrieve.
//
// Returns:
// - Value: The Stub value associated with the given UUID, or nil if not found.
func (s *storage) findByID(key uuid.UUID) Value { //nolint:ireturn
s.mu.RLock()
defer s.mu.RUnlock()
return s.itemsByID[key]
}
// findByIDs retrieves the Stub values associated with the given UUIDs from the
// storage.
//
// Returns:
// - iter.Seq[Value]: The Stub values associated with the given UUIDs, or nil if
// not found.
func (s *storage) findByIDs(ids iter.Seq[uuid.UUID]) iter.Seq[Value] {
return func(yield func(Value) bool) {
s.mu.RLock()
defer s.mu.RUnlock()
for id := range ids {
if v, ok := s.itemsByID[id]; ok {
if !yield(v) {
return
}
}
}
}
}
// upsert inserts or updates the given Value items in storage.
// It returns the UUIDs of the inserted or updated items.
func (s *storage) upsert(values ...Value) []uuid.UUID {
s.mu.Lock()
defer s.mu.Unlock()
// Prepare a slice to store the result UUIDs.
results := make([]uuid.UUID, len(values))
// Process each value to insert or update.
for i, v := range values {
leftID := s.id(v.Left())
index := s.pos(leftID, s.id(v.Right()))
// Initialize the map at the index if it doesn't exist.
if s.items[index] == nil {
if p := s.itemMapPool.Get(); p != nil {
s.items[index], _ = p.(map[uuid.UUID]Value)
// Clear any pre-existing entries.
for k := range s.items[index] {
delete(s.items[index], k)
}
} else {
s.items[index] = make(map[uuid.UUID]Value, 1)
}
}
// Insert or update the value in the storage.
s.items[index][v.Key()] = v
s.itemsByID[v.Key()] = v
s.lefts[leftID] = struct{}{}
// Record the UUID of the processed value.
results[i] = v.Key()
}
// Return the UUIDs of the inserted or updated values.
return results
}
// del deletes the Stub values with the given UUIDs from the storage.
// It returns the number of Stub values that were successfully deleted.
func (s *storage) del(keys ...uuid.UUID) int {
s.mu.Lock()
defer s.mu.Unlock()
deleted := 0
for _, key := range keys {
if v, ok := s.itemsByID[key]; ok {
pos := s.pos(s.id(v.Left()), s.id(v.Right()))
if m, exists := s.items[pos]; exists {
delete(m, key)
delete(s.itemsByID, key)
deleted++
if len(m) == 0 {
s.itemMapPool.Put(m)
delete(s.items, pos)
}
}
}
}
return deleted
}
func (s *storage) id(value string) uint32 {
return uint32(xxh3.HashString(value)) //nolint:gosec
}
func (s *storage) pos(a, b uint32) uint64 {
return uint64(a)<<32 | uint64(b)
}
func (s *storage) posByN(leftName, rightName string) (uint64, error) {
s.mu.RLock()
defer s.mu.RUnlock()
leftID := s.id(leftName)
if _, exists := s.lefts[leftID]; !exists {
return 0, ErrLeftNotFound
}
key := s.pos(leftID, s.id(rightName))
if _, exists := s.items[key]; !exists {
return 0, ErrRightNotFound
}
return key, nil
}