-
Notifications
You must be signed in to change notification settings - Fork 13
/
index.go
392 lines (351 loc) · 11.2 KB
/
index.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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
/*
Copyright © 2020 FairOS Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http:// www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package collection
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"runtime"
"sync/atomic"
"time"
"github.com/fairdatasociety/fairOS-dfs/pkg/account"
"github.com/fairdatasociety/fairOS-dfs/pkg/blockstore"
"github.com/fairdatasociety/fairOS-dfs/pkg/feed"
"github.com/fairdatasociety/fairOS-dfs/pkg/file"
"github.com/fairdatasociety/fairOS-dfs/pkg/logging"
"github.com/fairdatasociety/fairOS-dfs/pkg/utils"
)
// IndexType is the type of the index
type IndexType int
const (
// InvalidIndex is returned when the index type is invalid
InvalidIndex IndexType = iota
// BytesIndex is returned when the index type is bytes
BytesIndex
// StringIndex is returned when the index type is string
StringIndex
// NumberIndex is returned when the index type is number
NumberIndex
// MapIndex is returned when the index type is map
MapIndex
// ListIndex is returned when the index type is list
ListIndex
VectorIndex
)
func (e IndexType) String() string {
switch e {
case BytesIndex:
return "BytesIndex"
case StringIndex:
return "StringIndex"
case NumberIndex:
return "NumberIndex"
case MapIndex:
return "MapIndex"
case ListIndex:
return "ListIndex"
case VectorIndex: // skipcq: TCV-001
return "VectorIndex"
default:
return "InvalidIndex"
}
}
func toIndexTypeEnum(s string) IndexType {
switch s {
case "BytesIndex":
return BytesIndex
case "StringIndex":
return StringIndex
case "NumberIndex":
return NumberIndex
case "MapIndex":
return MapIndex
case "ListIndex":
return ListIndex
case "VectorIndex": // skipcq: TCV-001
return VectorIndex
default:
return InvalidIndex
}
}
// Index is the structure of the index
type Index struct {
name string
mutable bool
indexType IndexType
podFile string
encryptionPassword string
user utils.Address
accountInfo *account.Info
feed *feed.API
client blockstore.Client
count uint64
memDB *Manifest
logger logging.Logger
}
var (
// NoOfParallelWorkers is the number of parallel workers to be used for index creation
NoOfParallelWorkers = runtime.NumCPU() * 4
)
// CreateIndex creates a common index file to be used in kv or document tables.
func CreateIndex(podName, collectionName, indexName, encryptionPassword string, indexType IndexType, fd *feed.API, user utils.Address, client blockstore.Client, mutable bool) error {
if fd.IsReadOnlyFeed() { // skipcq: TCV-001
return ErrReadOnlyIndex
}
actualIndexName := podName + collectionName + indexName
topic := utils.HashString(actualIndexName)
_, oldData, err := fd.GetFeedData(topic, user, []byte(encryptionPassword), false)
if err == nil && len(oldData) != 0 && string(oldData) != utils.DeletedFeedMagicWord {
// if the feed is present, and it has some data means there index is still valid
return ErrIndexAlreadyPresent
}
manifest := NewManifest(actualIndexName, time.Now().Unix(), indexType, mutable)
// marshall and store the Manifest as new feed
data, err := json.Marshal(manifest)
if err != nil { // skipcq: TCV-001
return ErrManifestUnmarshall
}
ref, err := client.UploadBlob(data, 0, true)
if err != nil { // skipcq: TCV-001
return ErrManifestUnmarshall
}
if string(oldData) == utils.DeletedFeedMagicWord { // skipcq: TCV-001
err = fd.UpdateFeed(user, topic, ref, []byte(encryptionPassword), false)
if err != nil {
return ErrManifestCreate
}
return nil
}
err = fd.CreateFeed(user, topic, ref, []byte(encryptionPassword))
if err != nil { // skipcq: TCV-001
return ErrManifestCreate
}
return nil
}
// OpenIndex open the index and load any index in to the memory.
func OpenIndex(podName, collectionName, indexName, podPassword string, fd *feed.API, ai *account.Info, user utils.Address, client blockstore.Client, logger logging.Logger) (*Index, error) {
actualIndexName := podName + collectionName + indexName
manifest := getRootManifestOfIndex(actualIndexName, podPassword, fd, user, client) // this will load the entire Manifest for immutable indexes
if manifest == nil {
return nil, ErrIndexNotPresent
}
idx := &Index{
name: manifest.Name,
encryptionPassword: podPassword,
mutable: manifest.Mutable,
indexType: manifest.IdxType,
podFile: manifest.PodFile,
user: user,
accountInfo: ai,
feed: fd,
client: client,
count: manifest.Count,
memDB: manifest,
logger: logger,
}
return idx, nil
}
// DeleteIndex delete the index from file and all its entries.
func (idx *Index) DeleteIndex(encryptionPassword string) error {
if idx.isReadOnlyFeed() { // skipcq: TCV-001
return ErrReadOnlyIndex
}
manifest := getRootManifestOfIndex(idx.name, encryptionPassword, idx.feed, idx.user, idx.client)
if manifest == nil {
return ErrIndexNotPresent
}
// erase the top Manifest
topic := utils.HashString(idx.name)
err := idx.feed.UpdateFeed(idx.user, topic, []byte(utils.DeletedFeedMagicWord), []byte(encryptionPassword), false)
if err != nil { // skipcq: TCV-001
return ErrDeleteingIndex
}
return nil
}
func (idx *Index) IsEmpty(encryptionPassword string) (bool, error) {
if idx.memDB == nil || idx.memDB.Entries == nil {
manifest, err := idx.loadManifest(idx.name, encryptionPassword)
if err != nil {
return true, err
}
idx.memDB = manifest
}
return len(idx.memDB.Entries) == 0, nil
}
// CountIndex counts the entries in an index.
func (idx *Index) CountIndex(encryptionPassword string) (uint64, error) {
if idx.memDB == nil || idx.memDB.Entries == nil {
manifest, err := idx.loadManifest(idx.name, encryptionPassword)
if err != nil {
return 0, err
}
idx.memDB = manifest
}
if len(idx.memDB.Entries) == 0 {
return 0, nil
}
idx.count = 0
errC := make(chan error, 1) // get only one error
workers := make(chan bool, NoOfParallelWorkers)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
idx.loadIndexAndCount(ctx, cancel, workers, idx.memDB, encryptionPassword, errC)
select {
case err := <-errC: // skipcq: TCV-001
if err != nil {
idx.count = 0
return 0, err
}
default: // Default is must avoid blocking
}
return idx.count, nil
}
func (idx *Index) loadIndexAndCount(ctx context.Context, cancel context.CancelFunc, workers chan bool, manifest *Manifest,
encryptionPassword string, errC chan error) {
var count uint64
for _, entry := range manifest.Entries {
if entry.EType == intermediateEntry {
var newManifest *Manifest
if entry.Manifest == nil {
man, err := idx.loadManifest(manifest.Name+entry.Name, encryptionPassword)
if err != nil { // skipcq: TCV-001
idx.logger.Error("Manifest load error: ", manifest.Name+entry.Name)
return
}
newManifest = man
entry.Manifest = newManifest
} else { // skipcq: TCV-001
newManifest = entry.Manifest
}
idx.loadIndexAndCount(ctx, cancel, workers, newManifest, encryptionPassword, errC)
} else {
count++
}
}
atomic.AddUint64(&idx.count, count)
}
// Manifest related functions
func (idx *Index) loadManifest(manifestPath, encryptionPassword string) (*Manifest, error) {
// get feed data and unmarshall the Manifest
idx.logger.Info("loading Manifest: ", manifestPath)
topic := utils.HashString(manifestPath)
_, refData, err := idx.feed.GetFeedData(topic, idx.user, []byte(encryptionPassword), false)
if err != nil { // skipcq: TCV-001
return nil, ErrNoManifestFound
}
data, respCode, err := idx.client.DownloadBlob(refData)
if err != nil { // skipcq: TCV-001
return nil, ErrNoManifestFound
}
if respCode != http.StatusOK { // skipcq: TCV-001
return nil, ErrNoManifestFound
}
var manifest Manifest
err = json.Unmarshal(data, &manifest)
if err != nil { // skipcq: TCV-001
return nil, ErrManifestUnmarshall
}
return &manifest, nil
}
func (idx *Index) updateManifest(manifest *Manifest, encryptionPassword string) error {
// marshall and update the Manifest in the feed
idx.logger.Info("updating Manifest: ", manifest.Name)
data, err := json.Marshal(manifest)
if err != nil { // skipcq: TCV-001
return ErrManifestUnmarshall
}
ref, err := idx.client.UploadBlob(data, 0, true)
if err != nil { // skipcq: TCV-001
return ErrManifestUnmarshall
}
topic := utils.HashString(manifest.Name)
err = idx.feed.UpdateFeed(idx.user, topic, ref, []byte(encryptionPassword), false)
if err != nil { // skipcq: TCV-001
return ErrManifestCreate
}
return nil
}
func (idx *Index) storeManifest(manifest *Manifest, encryptionPassword string) error {
// marshall and store the Manifest as new feed
data, err := json.Marshal(manifest)
if err != nil { // skipcq: TCV-001
return ErrManifestUnmarshall
}
logStr := fmt.Sprintf("storing Manifest: %s, data len = %d", manifest.Name, len(data))
idx.logger.Debug(logStr)
ref, err := idx.client.UploadBlob(data, 0, true)
// TODO: once the tags issue is fixed i bytes.
// remove the error string check
if err != nil { // skipcq: TCV-001
idx.logger.Errorf("uploadBlob failed in storeManifest : %s", err.Error())
return ErrManifestCreate
}
topic := utils.HashString(manifest.Name)
_, _, err = idx.feed.GetFeedData(topic, idx.user, []byte(encryptionPassword), false)
if err == nil || errors.Is(err, file.ErrDeletedFeed) {
err = idx.feed.UpdateFeed(idx.user, topic, ref, []byte(encryptionPassword), false)
if err != nil { // skipcq: TCV-001
idx.logger.Errorf("updateFeed failed in storeManifest : %s", err.Error())
return ErrManifestCreate
}
return nil
}
err = idx.feed.CreateFeed(idx.user, topic, ref, []byte(encryptionPassword))
if err != nil { // skipcq: TCV-001
idx.logger.Errorf("createFeed failed in storeManifest : %s", err.Error())
return ErrManifestCreate
}
return nil
}
func (idx *Index) isReadOnlyFeed() bool {
return idx.feed.IsReadOnlyFeed()
}
func longestCommonPrefix(str1, str2 string) (string, string, string) {
if str1 == "" || str2 == "" {
return "", "", ""
}
maxLen := len(str2)
if len(str1) < len(str2) {
maxLen = len(str1)
}
matchLen := 0
for i := 0; i < maxLen; i++ {
if str1[i] != str2[i] {
break
}
matchLen++
}
if matchLen == 0 {
return "", str1, str2
}
return str1[:matchLen], str1[matchLen:], str2[matchLen:]
}
func getRootManifestOfIndex(actualIndexName, encryptionPassword string, fd *feed.API, user utils.Address, client blockstore.Client) *Manifest {
var manifest Manifest
topic := utils.HashString(actualIndexName)
_, addr, err := fd.GetFeedData(topic, user, []byte(encryptionPassword), false)
if err != nil {
return nil
}
data, _, err := client.DownloadBlob(addr)
if err != nil {
return nil
}
err = json.Unmarshal(data, &manifest)
if err != nil { // skipcq: TCV-001
return nil
}
return &manifest
}