-
Notifications
You must be signed in to change notification settings - Fork 28
/
collection_utils.go
625 lines (569 loc) · 17.6 KB
/
collection_utils.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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
// Copyright 2020-Present Couchbase, Inc.
//
// Use of this software is governed by the Business Source License included
// in the file licenses/BSL-Couchbase.txt. As of the Change Date specified
// in that file, in accordance with the Business Source License, use of this
// software will be governed by the Apache License, Version 2.0, included in
// the file licenses/APL2.txt.
package cbft
import (
"encoding/json"
"fmt"
"strings"
"sync"
"github.com/blevesearch/bleve/v2/analysis"
"github.com/blevesearch/bleve/v2/mapping"
"github.com/couchbase/cbgt"
log "github.com/couchbase/clog"
)
const defaultScopeName = "_default"
const defaultCollName = "_default"
type sourceDetails struct {
scopeName string
collUIDNameMap map[uint32]string // coll uid => coll name
}
type collMetaFieldCache struct {
m sync.RWMutex
cache map[string]string // indexName$collName => _$suid_$cuid
sourceDetailsMap map[string]*sourceDetails // indexName => sourceDetails
}
// metaFieldValCache holds a runtime volatile cache
// for collection meta field look ups during the collection
// specific query in a multi collection index.
var metaFieldValCache *collMetaFieldCache
func init() {
metaFieldValCache = &collMetaFieldCache{
cache: make(map[string]string),
sourceDetailsMap: make(map[string]*sourceDetails),
}
}
// refreshMetaFieldValCache updates the metaFieldValCache with
// the latest index definitions.
func refreshMetaFieldValCache(indexDefs *cbgt.IndexDefs) {
if indexDefs == nil || metaFieldValCache == nil {
return
}
bleveParams := NewBleveParams()
for _, indexDef := range indexDefs.IndexDefs {
err := json.Unmarshal([]byte(indexDef.Params), bleveParams)
if err != nil {
log.Printf("collection_utils: refreshMetaFieldValCache,"+
" indexName: %v, err: %v", indexDef.Name, err)
continue
}
// check if the mapping has synonym sources or is in scope.coll mode
var synonymsAvailable bool
if im, ok := bleveParams.Mapping.(*mapping.IndexMappingImpl); ok {
synonymsAvailable = im.SynonymCount() > 0
}
scopeDotCollMode := strings.HasPrefix(bleveParams.DocConfig.Mode, ConfigModeCollPrefix)
// need to validate and refresh the cache if either of the conditions are met
if scopeDotCollMode || synonymsAvailable {
if im, ok := bleveParams.Mapping.(*mapping.IndexMappingImpl); ok {
scope, err := validateScopeCollFromMappings(indexDef.SourceName,
im, false, scopeDotCollMode)
if err != nil {
return
}
_ = initMetaFieldValCache(indexDef.Name, indexDef.SourceName, im, scope)
}
}
}
}
func (c *collMetaFieldCache) getMetaFieldValue(indexName, collName string) string {
c.m.RLock()
rv := c.cache[indexName+"$"+collName]
c.m.RUnlock()
return rv
}
func encodeCollMetaFieldValue(suid, cuid int64) string {
return fmt.Sprintf("_$%d_$%d", suid, cuid)
}
func (c *collMetaFieldCache) setValue(indexName, scopeName string,
suid int64, collName string, cuid int64, multiCollIndex bool) {
key := indexName + "$" + collName
c.m.Lock()
c.cache[key] = encodeCollMetaFieldValue(suid, cuid)
if multiCollIndex {
var sd *sourceDetails
var ok bool
if sd, ok = c.sourceDetailsMap[indexName]; !ok {
sd = &sourceDetails{scopeName: scopeName,
collUIDNameMap: make(map[uint32]string)}
c.sourceDetailsMap[indexName] = sd
}
sd.collUIDNameMap[uint32(cuid)] = collName
}
c.m.Unlock()
}
func (c *collMetaFieldCache) reset(indexName string) {
prefix := indexName + "$"
c.m.Lock()
delete(c.sourceDetailsMap, indexName)
for k := range c.cache {
if strings.HasPrefix(k, prefix) {
delete(c.cache, k)
}
}
c.m.Unlock()
}
func (c *collMetaFieldCache) getSourceDetailsMap(indexName string) (
*sourceDetails, bool) {
c.m.RLock()
sdm, multiCollIndex := c.sourceDetailsMap[indexName]
var ret *sourceDetails
if sdm != nil {
// obtain a copy of the sourceDetails
ret = &sourceDetails{
scopeName: sdm.scopeName,
collUIDNameMap: make(map[uint32]string),
}
for k, v := range sdm.collUIDNameMap {
ret.collUIDNameMap[k] = v
}
}
c.m.RUnlock()
return ret, multiCollIndex
}
func (c *collMetaFieldCache) getScopeCollectionNames(indexName string) (
scopeName string, collectionNames []string) {
c.m.RLock()
sdm, _ := c.sourceDetailsMap[indexName]
if sdm != nil {
scopeName = sdm.scopeName
collectionNames = make([]string, len(sdm.collUIDNameMap))
i := 0
for _, v := range sdm.collUIDNameMap {
collectionNames[i] = v
i++
}
}
c.m.RUnlock()
return
}
func scopeCollTypeMapping(in string) (string, string, string) {
vals := strings.SplitN(in, ".", 3)
scope := "_default"
collection := "_default"
typeMapping := ""
if len(vals) == 1 {
typeMapping = vals[0]
} else if len(vals) == 2 {
scope = vals[0]
collection = vals[1]
} else {
scope = vals[0]
collection = vals[1]
typeMapping = vals[2]
}
return scope, collection, typeMapping
}
func getSynonymCollectionsFromMapping(im *mapping.IndexMappingImpl) []string {
if im == nil || im.SynonymCount() == 0 {
return nil
}
uniqueCollections := make(map[string]struct{})
rv := make([]string, 0, im.SynonymCount())
im.SynonymSourceVisitor(func(name string, s analysis.SynonymSource) error {
collectionName := s.Collection()
if _, exists := uniqueCollections[collectionName]; !exists {
uniqueCollections[collectionName] = struct{}{}
rv = append(rv, collectionName)
}
return nil
})
return rv
}
// getScopeCollTypeMappings will return a deduplicated
// list of collection names when skipMappings is enabled.
func getScopeCollTypeMappings(im *mapping.IndexMappingImpl,
skipMappings bool) (scope string,
cols []string, typeMappings []string, err error) {
// index the _default/_default scope and collection when
// default mapping is enabled.
if im.DefaultMapping.Enabled {
scope = defaultScopeName
cols = []string{defaultCollName}
typeMappings = []string{""}
}
hash := make(map[string]struct{}, len(im.TypeMapping))
for tp, dm := range im.TypeMapping {
if !dm.Enabled {
continue
}
s, c, t := scopeCollTypeMapping(tp)
key := c
if !skipMappings {
key += t
}
if _, exists := hash[key]; !exists {
hash[key] = struct{}{}
cols = append(cols, c)
if !skipMappings {
typeMappings = append(typeMappings, t)
}
}
if scope == "" {
scope = s
continue
}
if scope != s {
return "", nil, nil, fmt.Errorf("collection_utils: multiple scopes"+
" found: '%s', '%s'; index can only span collections on a single"+
" scope", scope, s)
}
}
return scope, cols, typeMappings, nil
}
// validateScopeCollFromMappings performs the $scope.$collection
// validations in the type mappings defined. It also performs
// - single scope validation across collections
// - verify scope to collection mapping with kv manifest
// call only when mode is either scope.collection or when synonym collections available
func validateScopeCollFromMappings(bucket string,
im *mapping.IndexMappingImpl, ignoreCollNotFoundErrs bool, scopeDotCollMode bool) (*Scope, error) {
var sName string
var collNames []string
var typeMappings []string
var err error
if scopeDotCollMode {
sName, collNames, typeMappings, err = getScopeCollTypeMappings(im, false)
if err != nil {
return nil, err
}
} else {
sName = defaultScopeName
collNames = []string{defaultCollName}
typeMappings = []string{""}
}
synColls := getSynonymCollectionsFromMapping(im)
if len(synColls) > 0 {
// ensure the synonym collections are disjoint from the
// regular collections.
for _, sc := range synColls {
for _, c := range collNames {
if sc == c {
return nil, fmt.Errorf("collection_utils: synonym collection:"+
" '%s' cannot be a indexed with a type mapping", sc)
}
}
}
}
manifest, err := GetBucketManifest(bucket)
if err != nil {
return nil, err
}
rv := &Scope{Collections: make([]Collection, 0, len(collNames)+len(synColls))}
for _, scope := range manifest.Scopes {
if scope.Name == sName {
rv.Name = scope.Name
rv.Uid = scope.Uid
OUTER:
for i := range collNames {
for _, collection := range scope.Collections {
if collection.Name == collNames[i] {
rv.Collections = append(rv.Collections, Collection{
Uid: collection.Uid,
Name: collection.Name,
typeMapping: typeMappings[i],
})
continue OUTER
}
}
if !ignoreCollNotFoundErrs {
return nil, fmt.Errorf("collection_utils: collection:"+
" '%s' doesn't belong to scope: '%s' in bucket: '%s'",
collNames[i], sName, bucket)
}
}
OUTER2:
for i := range synColls {
for _, collection := range scope.Collections {
if collection.Name == synColls[i] {
rv.Collections = append(rv.Collections, Collection{
Uid: collection.Uid,
Name: collection.Name,
isSynonym: true,
})
continue OUTER2
}
}
if !ignoreCollNotFoundErrs {
return nil, fmt.Errorf("collection_utils: synonym collection:"+
" '%s' doesn't belong to scope: '%s' in bucket: '%s'",
synColls[i], sName, bucket)
}
}
break
}
}
if rv.Name == "" {
return nil, fmt.Errorf("collection_utils: scope:"+
" '%s' not found in bucket: '%s' ",
sName, bucket)
}
return rv, nil
}
func enhanceMappingsWithCollMetaField(tm map[string]*mapping.DocumentMapping) error {
OUTER:
for _, mp := range tm {
fm := metaFieldMapping()
for fname := range mp.Properties {
if fname == CollMetaFieldName {
continue OUTER
}
}
mp.AddFieldMappingsAt(CollMetaFieldName, fm)
}
return nil
}
func metaFieldMapping() *mapping.FieldMapping {
fm := mapping.NewTextFieldMapping()
fm.Store = false
fm.DocValues = false
fm.IncludeInAll = false
fm.IncludeTermVectors = false
fm.Name = CollMetaFieldName
fm.Analyzer = "keyword"
return fm
}
// -----------------------------------------------------------------------------
// API to retrieve the scope & unique list of collection names from the
// provided index definition.
func GetScopeCollectionsFromIndexDef(indexDef *cbgt.IndexDef) (
scope string, collections []string, err error) {
if indexDef == nil || indexDef.Type != "fulltext-index" {
return "", nil,
fmt.Errorf("no fulltext-index definition provided")
}
bp := NewBleveParams()
if len(indexDef.Params) > 0 {
if err = json.Unmarshal([]byte(indexDef.Params), bp); err != nil {
return "", nil, err
}
var synonymsAvailable bool
if im, ok := bp.Mapping.(*mapping.IndexMappingImpl); ok {
synonymsAvailable = im.SynonymCount() > 0
}
scopeDotCollMode := strings.HasPrefix(bp.DocConfig.Mode, ConfigModeCollPrefix)
if scopeDotCollMode || synonymsAvailable {
if im, ok := bp.Mapping.(*mapping.IndexMappingImpl); ok {
var collectionNames []string
var scope string
if scopeDotCollMode {
scope, collectionNames, _, err = getScopeCollTypeMappings(im, false)
if err != nil {
return "", nil, err
}
if synonymsAvailable {
collectionNames = append(collectionNames, getSynonymCollectionsFromMapping(im)...)
}
} else {
scope = defaultScopeName
collectionNames = getSynonymCollectionsFromMapping(im)
}
uniqueCollections := map[string]struct{}{}
for _, coll := range collectionNames {
if _, exists := uniqueCollections[coll]; !exists {
uniqueCollections[coll] = struct{}{}
collections = append(collections, coll)
}
}
return scope, collections, nil
}
}
}
return "_default", []string{"_default"}, nil
}
func multiCollection(colls []Collection) bool {
hash := make(map[string]struct{}, 1)
for _, c := range colls {
if _, ok := hash[c.Name]; !ok {
hash[c.Name] = struct{}{}
}
}
return len(hash) > 1
}
// -----------------------------------------------------------------------------
// obtainIndexSourceFromDefinition obtains the source name from the index definition
// and recursively if the index definition is an alias.
// - input argument `rv` will be updated to contain a map of source names (buckets).
func obtainIndexSourceFromDefinition(mgr *cbgt.Manager, indexName string,
rv map[string]struct{}) (map[string]struct{}, error) {
if rv == nil {
rv = make(map[string]struct{})
}
if bucket, _ := getKeyspaceFromScopedIndexName(indexName); len(bucket) > 0 {
// indexName is a scoped index name
rv[bucket] = struct{}{}
return rv, nil
}
// else obtain bucket from definition of index
indexDef, _, err := mgr.GetIndexDef(indexName, false)
if err != nil || indexDef == nil {
return rv, fmt.Errorf("failed to retrieve index def for `%v`, err: %v",
indexName, err)
}
if indexDef.Type == "fulltext-index" {
rv[indexDef.SourceName] = struct{}{}
return rv, nil
} else if indexDef.Type == "fulltext-alias" {
params := AliasParams{}
err := UnmarshalJSON([]byte(indexDef.Params), ¶ms)
if err == nil {
for idxName := range params.Targets {
if rv, err = obtainIndexSourceFromDefinition(mgr, idxName, rv); err != nil {
return rv, err
}
}
}
} else {
// unrecognized index type
return rv, fmt.Errorf("unrecognized index type %v", indexDef.Type)
}
return rv, nil
}
const maxAliasDepth = 50
// obtainIndexBucketScopesForDefinition obtains the bucket.scope sources for the
// index definition and if it's alias - by recursively looking through the targets.
// it also performs a check for alias cycles, returning an error if an alias“
// cycle is detected. Cycle detection in the directed alias graph is done using the
// three color DFS algorithm from CLRS.
func obtainIndexBucketScopesForDefinition(mgr *cbgt.Manager,
indexDef *cbgt.IndexDef, rv map[string]int, visitedAndInPath map[string]bool,
depth int) (map[string]int, error) {
if rv == nil {
rv = make(map[string]int)
}
if visitedAndInPath == nil {
visitedAndInPath = make(map[string]bool)
}
if depth > maxAliasDepth {
return rv, fmt.Errorf("alias expansion depth exceeded, maxAliasDepth allowed is %v", maxAliasDepth)
}
// else obtain bucket & scope from definition of index
if indexDef.Type == "fulltext-index" {
bucketName, scopeName := getKeyspaceFromScopedIndexName(indexDef.Name)
if len(bucketName) > 0 && len(scopeName) > 0 {
// indexName is a scoped index name
key := bucketName + "." + scopeName
rv[key]++
return rv, nil
}
scope, _, err := GetScopeCollectionsFromIndexDef(indexDef)
if err != nil {
return rv, err
}
key := indexDef.SourceName + "." + scope
rv[key]++
return rv, nil
} else if indexDef.Type == "fulltext-alias" {
visitedAndInPath[indexDef.Name] = true
params, err := parseAliasParams(indexDef.Params)
if err == nil {
for idxName := range params.Targets {
inPath, visited := visitedAndInPath[idxName]
if inPath && visited {
return rv, fmt.Errorf("cyclic index alias %s "+
"detected in alias path", idxName)
}
if visited {
continue
}
idxDef, err := mgr.CheckAndGetIndexDef(idxName, true)
if err != nil {
return rv, fmt.Errorf("failed to retrieve index defs for `%v`, err: %v",
idxDef.Name, err)
}
bucketName, scopeName := getKeyspaceFromScopedIndexName(idxName)
if len(bucketName) > 0 && len(scopeName) > 0 {
// indexName is a scoped index name
key := bucketName + "." + scopeName
rv[key]++
if idxDef == nil {
return rv, fmt.Errorf("scoped index target %v not found", idxName)
}
if idxDef.Type == "fulltext-alias" {
err := detectIndexAliasCycle(mgr, idxDef, visitedAndInPath, depth+1)
if err != nil {
return rv, err
}
}
continue
}
// global alias or non-scoped index target does not exist
if idxDef == nil {
continue
}
if rv, err = obtainIndexBucketScopesForDefinition(mgr, idxDef, rv, visitedAndInPath, depth+1); err != nil {
return rv, err
}
}
visitedAndInPath[indexDef.Name] = false
}
} else {
// unrecognized index type
return rv, fmt.Errorf("unrecognized index type %v", indexDef.Type)
}
return rv, nil
}
func detectIndexAliasCycle(mgr *cbgt.Manager, indexDef *cbgt.IndexDef,
visitedAndInPath map[string]bool, depth int) error {
// Detect cycle in the alias graph using an iterative DFS
type stackEntry struct {
indexDef *cbgt.IndexDef
depth int
}
var stack []*stackEntry
stack = append(stack, &stackEntry{indexDef: indexDef, depth: depth})
for len(stack) > 0 {
indexDef = stack[len(stack)-1].indexDef
currentDepth := stack[len(stack)-1].depth
if stack[len(stack)-1].depth > maxAliasDepth {
return fmt.Errorf("alias expansion depth exceeded, maxAliasDepth allowed is %v", maxAliasDepth)
}
if visitedAndInPath[indexDef.Name] {
visitedAndInPath[indexDef.Name] = false
stack = stack[:len(stack)-1]
continue
}
visitedAndInPath[indexDef.Name] = true
params, err := parseAliasParams(indexDef.Params)
if err != nil {
return err
}
for target := range params.Targets {
targetIndexDef, err := mgr.CheckAndGetIndexDef(target, false)
if err != nil {
return fmt.Errorf("failed to retrieve index definition for `%v`, err: %v", target, err)
}
if targetIndexDef == nil {
return fmt.Errorf("scoped index target `%v` not found", target)
}
inPath, visited := visitedAndInPath[targetIndexDef.Name]
if inPath && visited {
return fmt.Errorf("cyclic index alias %s "+
"detected in alias path", targetIndexDef.Name)
}
if visited {
continue
}
if targetIndexDef.Type == "fulltext-alias" {
stack = append(stack, &stackEntry{indexDef: targetIndexDef, depth: currentDepth + 1})
}
}
}
return nil
}
// getKeyspaceFromScopedIndexName gets the bucket and
// scope names from an index name if available
func getKeyspaceFromScopedIndexName(indexName string) (string, string) {
pos1 := strings.LastIndex(indexName, ".")
if pos1 > 0 {
pos2 := strings.LastIndex(indexName[:pos1], ".")
if pos2 > 0 {
return indexName[:pos2], indexName[pos2+1 : pos1]
}
}
return "", ""
}