-
Notifications
You must be signed in to change notification settings - Fork 125
/
trie.go
2394 lines (2020 loc) · 54.8 KB
/
trie.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
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package carbonserver
import (
"crypto/md5" // skipcq: GSC-G501
"errors"
"fmt"
"io"
"path/filepath"
"sort"
"strings"
"sync"
"sync/atomic"
"time"
"unsafe"
trigram "github.com/dgryski/go-trigram"
"github.com/go-graphite/go-carbon/points"
)
// debug codes diff for reference: https://play.golang.org/p/FxuvRyosk3U
// dfa inspiration: https://swtch.com/~rsc/regexp/
const (
gstateSplit = 256
maxGstateCLen = 257
// used in walking over the tree, a lazy way to make sure that all the nodes are
// covered without risking index out of range.
trieDepthBuffer = 7
)
var endGstate = &gstate{}
type gmatcher struct {
exact bool
root *gstate
expr string
dstates []*gdstate
dsindex int //nolint:unused,structcheck
// TODO: depcreate lsComplex and trigrams. the gains of it isn't very
// clear and it would make things simpler.
//
// has leading star following by complex expressions
lsComplex bool
trigrams []uint32
}
type gstate struct {
// TODO: make c compact
c [maxGstateCLen]bool
next []*gstate
}
type gdstate struct {
gstates []*gstate
}
func (g *gmatcher) dstate() *gdstate { return g.dstates[len(g.dstates)-1] }
func (g *gmatcher) push(s *gdstate) { g.dstates = append(g.dstates, s) }
func (g *gmatcher) pop(i int) {
if len(g.dstates) <= i {
g.dstates = g.dstates[:1]
return
}
g.dstates = g.dstates[:len(g.dstates)-i]
}
func (g *gstate) String() string {
var toStr func(g *gstate) string
var ref = map[*gstate]string{}
toStr = func(g *gstate) string {
if r, ok := ref[g]; ok {
return r
}
if g == endGstate {
ref[g] = "end"
return "end"
}
var b []byte
for c, t := range g.c {
if t {
if isAlphanumeric(byte(c)) {
b = append(b, byte(c))
} else {
b = append(b, '.')
}
}
}
var r = string(b)
ref[g] = r + "(...)"
for _, n := range g.next {
r += "(" + toStr(n) + ")"
}
ref[g] = r
return r
}
return toStr(g)
}
func (g gdstate) String() string {
var r []string
for _, s := range g.gstates {
r = append(r, s.String())
}
return strings.Join(r, ",")
}
func (g *gdstate) step(c byte) *gdstate {
// if g.next[c] != nil {
// g.cacheHit++
// return g.next[c]
// }
var ng gdstate
for _, s := range g.gstates {
if s.c[c] || s.c['*'] {
for _, ns := range s.next {
ng.gstates = g.add(ng.gstates, ns)
}
}
}
// g.next[c] = &ng
return &ng
}
func (g *gdstate) add(list []*gstate, s *gstate) []*gstate {
if s.c[gstateSplit] {
for _, ns := range s.next {
list = g.add(list, ns)
}
return list
}
list = append(list, s)
return list
}
func (g *gdstate) matched() bool {
for _, s := range g.gstates {
if s == endGstate {
return true
}
}
return false
}
// TODO:
// add range value validation
func newGlobState(expr string, expand func(globs []string) ([]string, error)) (*gmatcher, error) {
var m = gmatcher{root: &gstate{}, exact: true, expr: expr}
var cur = m.root
var alters [][2]*gstate
for i := 0; i < len(expr); i++ {
c := expr[i]
switch c {
case '[':
m.exact = false
s := &gstate{}
i++
if i >= len(expr) {
return nil, errors.New("glob: broken range syntax")
}
negative := expr[i] == '^'
if negative {
i++
}
for i < len(expr) && expr[i] != ']' {
if expr[i] == '-' {
if i+1 >= len(expr) {
return nil, errors.New("glob: missing closing range")
}
if expr[i-1] > expr[i+1] {
return nil, errors.New("glob: range start is bigger than range end")
}
// a simple check to make sure that range doesn't ends with 0xff,
// which would causes endless loop bellow
if expr[i-1] > 128 || expr[i+1] > 128 {
return nil, errors.New("glob: range overflow")
}
for j := expr[i-1] + 1; j <= expr[i+1]; j++ {
if j != '*' {
s.c[j] = true
}
}
i += 2
continue
}
s.c[expr[i]] = true
i++
}
if i >= len(expr) || expr[i] != ']' {
return nil, errors.New("glob: missing ]")
}
if negative {
// TODO: revisit
for i := 32; i <= 126; i++ {
if i != '*' {
s.c[i] = !s.c[i]
}
}
}
cur.next = append(cur.next, s)
cur = s
m.lsComplex = false
case '?':
m.exact = false
var star gstate
star.c['*'] = true
cur.next = append(cur.next, &star)
cur = &star
m.lsComplex = false
case '*':
m.exact = false
if i == 0 && len(expr) > 2 {
// TODO: check dup stars
m.lsComplex = true
}
// de-dup multi stars: *** -> *
for ; i+1 < len(expr) && expr[i+1] == '*'; i++ {
}
var split, star gstate
star.c['*'] = true
split.c[gstateSplit] = true
split.next = append(split.next, &star)
cur.next = append(cur.next, &split)
star.next = append(star.next, &split)
cur = &split
case '{':
alterStart := &gstate{c: [maxGstateCLen]bool{gstateSplit: true}}
alterEnd := &gstate{c: [maxGstateCLen]bool{gstateSplit: true}}
cur.next = append(cur.next, alterStart)
cur = alterStart
alters = append(alters, [2]*gstate{alterStart, alterEnd})
m.lsComplex = false
case '}':
if len(alters) == 0 {
return nil, errors.New("glob: missing {")
}
cur.next = append(cur.next, alters[len(alters)-1][1])
cur = alters[len(alters)-1][1]
alters = alters[:len(alters)-1]
m.lsComplex = false
case ',':
if len(alters) > 0 {
cur.next = append(cur.next, alters[len(alters)-1][1])
cur = alters[len(alters)-1][0]
continue
}
// TODO: should return error?
fallthrough
default:
s := &gstate{}
s.c[c] = true
cur.next = append(cur.next, s)
cur = s
}
}
cur.next = append(cur.next, endGstate)
if len(alters) > 0 {
return nil, errors.New("glob: missing }")
}
var droot gdstate
for _, s := range m.root.next {
droot.gstates = droot.add(droot.gstates, s)
}
m.dstates = append(m.dstates, &droot)
// TODO: consider dropping trigram integration
if m.lsComplex && expand != nil {
es, err := expand([]string{expr})
if err != nil {
return &m, nil
}
for _, e := range es {
trigrams := extractTrigrams(e)
appendt:
for i := 0; i < len(trigrams); i++ {
for _, t := range m.trigrams {
if t == uint32(trigrams[i]) {
continue appendt
}
}
m.trigrams = append(m.trigrams, uint32(trigrams[i]))
}
}
}
return &m, nil
}
func isAlphanumeric(c byte) bool {
return 32 <= c && c <= 126
}
type trieIndex struct {
root *trieNode
fileExt string
fileCount int
depth uint64
longestMetric string
trigrams map[*trieNode][]uint32
// qau: Quota And Usage
qauMetrics []points.Points
estimateSize func(metric string) (size, dataPoints int64)
throughputs *throughputQuotaManager
resetFrequency time.Duration
}
func (ti *trieIndex) setResetFrequency(f time.Duration) {
atomic.StoreInt64((*int64)(&ti.resetFrequency), int64(f))
}
func (ti *trieIndex) getResetFrequency() time.Duration {
return time.Duration(atomic.LoadInt64((*int64)(&ti.resetFrequency)))
}
// note: root and file leaf node has a nil c, mainly used in trieNode.fullPath
type trieNode struct {
c []byte // TODO: look for a more compact/compressed formats
childrens *[]*trieNode
gen uint8
meta trieMeta
}
type trieMeta interface{ trieMeta() }
type fileMeta struct {
logicalSize int64
physicalSize int64
dataPoints int64
// a timestamp of the first time when go-carbon has seen this metric.
// stricly speacking, it is not metric creation time, but can be used
// as a timing reference to infer that the metric is at least created
// before this timestamp. some file systems doesn't maintain ctime of
// files (like xfs before v5:
// https://unix.stackexchange.com/questions/7562/what-file-systems-on-linux-store-the-creation-time#comment1184213_40093)
//
// the reliablity of this timestamp counts on file list cache v2
// (and above), more in carbonserver.go and flc.go.
firstSeenAt int64
}
func (*fileMeta) trieMeta() {}
type dirMeta struct {
// type: *Quota
// note: the underlying Quota value is shared with other dir nodes.
//
// TODO: save 8 bytes by using a pointer value?
quota atomic.Value
usage *QuotaUsage
}
func newDirMeta() *dirMeta { return &dirMeta{usage: &QuotaUsage{}} }
func (*dirMeta) trieMeta() {}
func (dm *dirMeta) setQuota(quota *Quota) { dm.quota.Store(quota) }
func (dm *dirMeta) getQuota() *Quota { return dm.quota.Load().(*Quota) }
func (dm *dirMeta) withinQuota(metrics, namespaces, logical, physical, dataPoints int64) bool {
quota, ok := dm.quota.Load().(*Quota)
if !ok {
return true
}
var (
qmetrics = quota.Metrics
qnamespaces = quota.Namespaces
qlogicalSize = quota.LogicalSize
qphysicalSize = quota.PhysicalSize
qdataPoints = quota.DataPoints
umetrics = atomic.LoadInt64(&dm.usage.Metrics)
unamespaces = atomic.LoadInt64(&dm.usage.Namespaces)
ulogicalsize = atomic.LoadInt64(&dm.usage.LogicalSize)
uphysicalsize = atomic.LoadInt64(&dm.usage.PhysicalSize)
udataPoints = atomic.LoadInt64(&dm.usage.DataPoints)
)
if qmetrics > 0 && umetrics+metrics > qmetrics {
return false
}
if qnamespaces > 0 && unamespaces+namespaces > qnamespaces {
return false
}
if qlogicalSize > 0 && ulogicalsize+logical > qlogicalSize {
return false
}
if qphysicalSize > 0 && uphysicalsize+physical > qphysicalSize {
return false
}
if qdataPoints > 0 && udataPoints+dataPoints > qdataPoints {
return false
}
return true
}
var emptyTrieNodes = &[]*trieNode{}
// TODO: consider not initialize fileMeta if quota feature isn't enabled?
func newFileNode(m uint8, logicalSize, physicalSize, dataPoints, firstSeenAt int64) *trieNode {
return &trieNode{
childrens: emptyTrieNodes,
gen: m,
meta: &fileMeta{
logicalSize: logicalSize,
physicalSize: physicalSize,
dataPoints: dataPoints,
firstSeenAt: firstSeenAt,
},
}
}
func (tn *trieNode) dir() bool { return len(tn.c) == 1 && tn.c[0] == '/' }
func (tn *trieNode) file() bool { return tn.c == nil }
func (tn *trieNode) getChildrens() []*trieNode {
// skipcq: GSC-G103
return *(*[]*trieNode)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(&tn.childrens))))
}
func (*trieNode) getChild(curChildrens []*trieNode, i int) *trieNode {
// skipcq: GSC-G103
return (*trieNode)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(&curChildrens[i]))))
}
func (tn *trieNode) setChildrens(cs []*trieNode) {
// skipcq: GSC-G103
atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(&tn.childrens)), unsafe.Pointer(&cs))
}
func (tn *trieNode) addChild(n *trieNode) {
tn.setChildrens(append(*tn.childrens, n))
}
func (tn *trieNode) setChild(i int, n *trieNode) {
atomic.StorePointer(
(*unsafe.Pointer)(unsafe.Pointer(&(*tn.childrens)[i])), // skipcq: GSC-G103
unsafe.Pointer(n), // skipcq: GSC-G103
)
}
func (ti *trieIndex) trigramsContains(tn *trieNode, t uint32) bool {
for _, i := range ti.trigrams[tn] {
if i == t {
return true
}
}
return false
}
func newTrie(fileExt string, estimateSize func(metric string) (size, dataPoints int64)) *trieIndex {
meta := newDirMeta()
return &trieIndex{
root: &trieNode{childrens: &[]*trieNode{}, meta: meta},
fileExt: fileExt,
trigrams: map[*trieNode][]uint32{},
estimateSize: estimateSize,
throughputs: newQuotaThroughputQuotaManager(),
}
}
func (ti *trieIndex) getDepth() uint64 { return atomic.LoadUint64(&ti.depth) }
func (ti *trieIndex) setDepth(d uint64) { atomic.StoreUint64(&ti.depth, d) }
type nilFilenameError string
func (nfe nilFilenameError) Error() string { return string(nfe) }
type trieInsertError struct {
typ string
info string
}
func (t *trieInsertError) Error() string { return t.typ }
// TODO: add some more defensive logics agains bad paths?
//
// abc.def.ghi
// abc.def2.ghi
// abc.daf2.ghi
// efg.cjk
//
// insert expects / separated file path, like ns1/ns2/ns3/metric.wsp.
// insert considers path name ending with trieIndex.fileExt as a metric.
//
// insert returns either a file node or dir node, after inserted.
func (ti *trieIndex) insert(path string, logicalSize, physicalSize, dataPoints, firstSeenAt int64) (*trieNode, error) {
path = filepath.Clean(path)
if len(path) > 0 && path[0] == '/' { // skipcq: GO-S1005
path = path[1:]
}
if path == "" || path == "." {
return nil, nil
}
isFile := strings.HasSuffix(path, ti.fileExt)
if isFile {
path = path[:len(path)-len(ti.fileExt)]
}
if path == "" || path[len(path)-1] == '/' {
return nil, nilFilenameError("metric filename is nil")
}
if uint64(len(path)) > ti.getDepth() {
ti.setDepth(uint64(len(path)))
ti.longestMetric = path
}
var start, nlen int
var sn, newn *trieNode
var cur = ti.root
var dirNodes = [16]*trieNode{ti.root} // why arrray: avoiding heap allocation
var dirNodesIdx = 1
outer:
// why len(path)+1: make sure the last node is also processed in the loop
for i := 0; i < len(path)+1; i++ {
// getting a full node
if i < len(path) && path[i] != '/' {
continue
}
// case 1:
// abc . xxx
// ab . xxx
// case 2:
// ab . xxx
// abc . xxx
// case 3:
// abc . xxx
// abc . xxx
// case 4:
// abc . xxx
// xyz . xxx
// case 5:
// abc . xxx
// acc . xxx
// case 6:
// abc . xxx
// abd . xxx
// case 7:
// abc . xxx
// abde . xxx
// case 8:
// abc . xxx
// abc
inner:
for ci := 0; ci < len(*cur.childrens); ci++ {
child := (*cur.childrens)[ci]
match := 0
if len(child.c) == 0 || child.c[0] != path[start] {
continue
}
nlen = i - start
start++
for match = 1; match < len(child.c) && match < nlen; match++ {
if child.c[match] != path[start] {
break
}
start++
}
if match == nlen {
// case 1
if len(child.c) > match {
goto split
}
// case 3
if len(child.c) == match {
child.gen = ti.root.gen
cur = child
goto dir
}
return nil, &trieInsertError{typ: "failed to index metric: unknwon case of match == nlen", info: fmt.Sprintf("match == nlen == %d", nlen)}
}
if match == len(child.c) && len(child.c) < nlen { // case 2
child.gen = ti.root.gen
cur = child
goto inner
}
split:
// case 5, 6, 7
prefix, suffix := child.c[:match], child.c[match:]
sn = &trieNode{c: suffix, childrens: child.childrens, gen: child.gen}
cur.setChild(ci, &trieNode{c: prefix, childrens: &[]*trieNode{sn}, gen: ti.root.gen})
cur = (*cur.childrens)[ci]
if nlen-match > 0 {
newn = &trieNode{c: make([]byte, nlen-match), childrens: &[]*trieNode{}, gen: ti.root.gen}
copy(newn.c, path[start:i])
cur.addChild(newn)
cur = newn
}
goto dir
}
// case 4 & 2
if i-start > 0 {
newn = &trieNode{c: make([]byte, i-start), childrens: &[]*trieNode{}, gen: ti.root.gen}
copy(newn.c, path[start:i])
cur.addChild(newn)
cur = newn
}
dir:
// case 8
if i == len(path) {
break outer
}
start = i + 1
for _, child := range *cur.childrens {
if child.dir() {
cur = child
cur.gen = ti.root.gen
if dirNodesIdx < len(dirNodes) {
dirNodes[dirNodesIdx] = child
dirNodesIdx++
}
continue outer
}
}
if i < len(path) {
newn = ti.newDir()
if dirNodesIdx < len(dirNodes) {
if dirNodes[dirNodesIdx-1].meta != nil {
// Purpose of transient child?
//
//
pmeta := dirNodes[dirNodesIdx-1].meta
pquota, ok := pmeta.(*dirMeta).quota.Load().(*Quota)
if ok && pquota.TransientChild != nil {
meta := newDirMeta()
meta.setQuota(pquota.TransientChild)
newn.meta = meta
}
}
dirNodes[dirNodesIdx] = newn
dirNodesIdx++
}
cur.addChild(newn)
cur = newn
}
}
// TODO: there seems to be a problem of fetching a directory node without files
if !isFile {
if cur.dir() {
cur.gen = ti.root.gen
return cur, nil
}
var newDir = true
for _, child := range *cur.childrens {
if child.dir() {
cur = child
cur.gen = ti.root.gen
newDir = false
break
}
}
if newDir {
child := ti.newDir()
cur.addChild(child)
cur = child
}
return cur, nil
}
if firstSeenAt == 0 {
firstSeenAt = time.Now().Unix()
}
var hasFileNode bool
for _, c := range *cur.childrens {
if c.file() {
hasFileNode = true
c.gen = ti.root.gen
meta := c.meta.(*fileMeta)
if logicalSize > 0 || physicalSize > 0 || dataPoints > 0 {
atomic.StoreInt64(&meta.logicalSize, logicalSize)
atomic.StoreInt64(&meta.physicalSize, physicalSize)
atomic.StoreInt64(&meta.dataPoints, dataPoints)
}
if meta.firstSeenAt == 0 || meta.firstSeenAt > firstSeenAt {
atomic.StoreInt64(&meta.firstSeenAt, firstSeenAt)
}
cur = c
break
}
}
if !hasFileNode {
if ti.estimateSize != nil && logicalSize == 0 && physicalSize == 0 && dataPoints == 0 {
logicalSize, dataPoints = ti.estimateSize(strings.ReplaceAll(path, "/", "."))
physicalSize = logicalSize
}
child := newFileNode(ti.root.gen, logicalSize, physicalSize, dataPoints, firstSeenAt)
cur.addChild(child)
cur = child
// TODO: need to support realtime and concurrent index?
ti.fileCount++
for i := 0; i < dirNodesIdx; i++ {
if dirNodes[i] == nil {
continue
}
meta, ok := dirNodes[i].meta.(*dirMeta)
if !ok || meta.usage == nil {
continue
}
atomic.AddInt64(&meta.usage.Metrics, 1)
atomic.AddInt64(&meta.usage.LogicalSize, logicalSize)
atomic.AddInt64(&meta.usage.PhysicalSize, physicalSize)
atomic.AddInt64(&meta.usage.DataPoints, dataPoints)
}
}
return cur, nil
}
func (ti *trieIndex) newDir() *trieNode {
n := &trieNode{
c: []byte{'/'},
childrens: &[]*trieNode{},
gen: ti.root.gen,
}
return n
}
// TODO: add some defensive logics agains bad queries?
// depth first search
func (ti *trieIndex) query(expr string, limit int, expand func(globs []string) ([]string, error)) (files []string, isFiles []bool, nodes []*trieNode, err error) {
expr = strings.TrimSpace(expr)
if expr == "" {
expr = "*"
}
var matchers []*gmatcher
var exact bool
for _, node := range strings.Split(expr, "/") {
if node == "" {
continue
}
gs, err := newGlobState(node, expand)
if err != nil {
return nil, nil, nil, err
}
exact = exact && gs.exact
matchers = append(matchers, gs)
}
if len(matchers) == 0 {
return nil, nil, nil, nil
}
var cur = ti.root
var curChildrens = cur.getChildrens()
var depth = ti.getDepth() + trieDepthBuffer
var nindex = make([]int, depth)
var trieNodes = make([]*trieNode, depth)
var childrensStack = make([][]*trieNode, depth)
var ncindex int
var mindex int
var curm = matchers[0]
var ndstate *gdstate
var isFile, isDir, hasMoreNodes bool
var dirNode, fileNode *trieNode
for {
if nindex[ncindex] >= len(curChildrens) {
curm.pop(len(cur.c))
goto parent
}
trieNodes[ncindex] = cur
childrensStack[ncindex] = curChildrens
cur = cur.getChild(curChildrens, nindex[ncindex])
curChildrens = cur.getChildrens()
ncindex++
// It's possible to run into a situation of newer and longer metrics
// are added during the query, for such situation, it's safer to just
// skip them for the current query.
if ncindex >= len(nindex)-1 {
goto parent
}
if cur.dir() {
if mindex+1 >= len(matchers) || !curm.dstate().matched() || len(curChildrens) == 0 {
goto parent
}
mindex++
curm = matchers[mindex]
curm.dstates = curm.dstates[:1]
continue
}
if curm.lsComplex && len(curm.trigrams) > 0 {
if _, ok := ti.trigrams[cur]; ok {
for _, t := range curm.trigrams {
if !ti.trigramsContains(cur, t) {
goto parent
}
}
}
}
for i := 0; i < len(cur.c); i++ {
ndstate = curm.dstate().step(cur.c[i])
if len(ndstate.gstates) == 0 {
if i > 0 {
// TODO: add test case
curm.pop(i)
}
goto parent
}
curm.push(ndstate)
}
if mindex+1 < len(matchers) {
continue
}
isFile = false
isDir = false
hasMoreNodes = false
for i := 0; i < len(curChildrens); i++ {
child := cur.getChild(curChildrens, i)
switch {
case child.file():
isFile = true
fileNode = child
case child.dir():
isDir = true
dirNode = child
default:
hasMoreNodes = true
}
}
if !(isFile || isDir) {
continue
}
if !curm.dstate().matched() {
if hasMoreNodes {
continue
}
curm.pop(len(cur.c))
goto parent
}
if isFile {
files = append(files, cur.fullPath('.', trieNodes[:ncindex]))
isFiles = append(isFiles, isFile)
nodes = append(nodes, fileNode)
}
if isDir {
files = append(files, cur.fullPath('.', trieNodes[:ncindex]))
isFiles = append(isFiles, false)
nodes = append(nodes, dirNode)
}
if len(files) >= limit || exact {
break
}
if hasMoreNodes {
continue
}
curm.pop(len(cur.c))
goto parent
parent:
// use exact for fast exit
nindex[ncindex] = 0
ncindex--
if ncindex < 0 {
break
}
nindex[ncindex]++
cur = trieNodes[ncindex]
curChildrens = childrensStack[ncindex]
if cur.dir() && nindex[ncindex] >= len(curChildrens) {
mindex--
curm = matchers[mindex]
goto parent
}
continue
}
return files, isFiles, nodes, nil
}
// note: tn might be a root or file node, which has a nil c
func (tn *trieNode) fullPath(sep byte, parents []*trieNode) string {
var size = len(tn.c)
for _, n := range parents {
size += len(n.c)
}
var r = make([]byte, size)
var i int
for _, n := range parents {
if n.dir() {
r[i] = sep
i++
} else if len(n.c) > 0 {
copy(r[i:], n.c)
i += len(n.c)
}
}
if len(tn.c) > 0 {
copy(r[i:], tn.c)
}
// skipcq: GSC-G103
return *(*string)(unsafe.Pointer(&r))
}
func dumpTrigrams(data []uint32) []trigram.T { //nolint:deadcode,unused
var ts []trigram.T
for _, t := range data {
ts = append(ts, trigram.T(t))
}
return ts
}
func (ti *trieIndex) allMetrics(sep byte) []string {
var files = make([]string, 0, ti.fileCount)
var depth = ti.getDepth() + trieDepthBuffer
var nindex = make([]int, depth)
var ncindex int
var cur = ti.root
var curChildrens = cur.getChildrens()
var trieNodes = make([]*trieNode, depth)
for {
if nindex[ncindex] >= len(curChildrens) {
goto parent
}