-
Notifications
You must be signed in to change notification settings - Fork 279
/
meta.go
355 lines (323 loc) · 10.3 KB
/
meta.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
// Licensed to LinDB under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. LinDB licenses this file to you 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 tagkeymeta
import (
"bytes"
"encoding/binary"
"regexp"
"sort"
"strings"
"github.com/lindb/roaring"
"github.com/lindb/lindb/constants"
"github.com/lindb/lindb/pkg/encoding"
"github.com/lindb/lindb/pkg/strutil"
"github.com/lindb/lindb/pkg/trie"
)
//go:generate mockgen -source ./meta.go -destination=./meta_mock.go -package tagkeymeta
type TagKeyMeta interface {
// TagValueIDSeq returns the auto sequence of tag value id under this tag key
TagValueIDSeq() uint32
// TagValueIDs returns all tag value ids under this tag key
TagValueIDs() (*roaring.Bitmap, error)
// CollectTagValues collects the tag values by tag value ids,
CollectTagValues(tagValueIDs *roaring.Bitmap, tagValues map[uint32]string) error
// TrieTree returns the trie tree
TrieTree() (trie.SuccinctTrie, error)
// PrefixIterator returns a iterator for prefix iterating the Iterator
PrefixIterator(tagValuePrefix []byte) (*trie.PrefixIterator, error)
// FindTagValueID finds tagValueIDs by tagValue
FindTagValueID(tagValue string) (tagValueIDs []uint32)
// FindTagValueIDs finds tagValueIDs in tagValue
FindTagValueIDs(tagValues []string) (tagValueIDs []uint32)
// FindTagValueIDsByLike finds tagValueIDs like tagValue,
// 3 cases: *sdb, ts*, *sd*
FindTagValueIDsByLike(tagValue string) (tagValueIDs []uint32)
// FindTagValueIDsByRegex finds tagValueIDs by regex pattern,
FindTagValueIDsByRegex(tagValuePattern string) (tagValueIDs []uint32)
}
const (
tagFooterSize = 4 + // bitmap position
4 + // offsets position
4 + // tag value sequence
4 // crc32 checksum
)
type TagKeyMetas []TagKeyMeta
// GetTagValueIDs gets all tag value ids under tag-keys meta
func (metas TagKeyMetas) GetTagValueIDs() (*roaring.Bitmap, error) {
unionIDSet := roaring.New()
for _, tagMeta := range metas {
tagValueIDs, err := tagMeta.TagValueIDs()
if err != nil {
return nil, err
}
unionIDSet.Or(tagValueIDs)
}
return unionIDSet, nil
}
// tagKeyMeta implements TagKeyMeta
type tagKeyMeta struct {
block []byte
tree trie.SuccinctTrie
unmarshalError error
offsetsDecoder *encoding.FixedOffsetDecoder
trieBlock []byte // tag value trie
bitmapData []byte // tag value ids
offsetsData []byte
bitmapPos int
offsetsPos int
tagValueIDSeq uint32
crc32CheckSum uint32
}
func newTagKeyMeta(tagKeyMetaBlock []byte) (TagKeyMeta, error) {
if len(tagKeyMetaBlock) < tagFooterSize {
return nil, constants.ErrDataFileCorruption
}
meta := &tagKeyMeta{
block: tagKeyMetaBlock,
}
// read footer(4+4+4+4+4)
footerPos := len(tagKeyMetaBlock) - tagFooterSize
meta.bitmapPos = int(binary.LittleEndian.Uint32(tagKeyMetaBlock[footerPos : footerPos+4]))
meta.offsetsPos = int(binary.LittleEndian.Uint32(tagKeyMetaBlock[footerPos+4 : footerPos+8]))
meta.tagValueIDSeq = binary.LittleEndian.Uint32(tagKeyMetaBlock[footerPos+8 : footerPos+12])
meta.crc32CheckSum = binary.LittleEndian.Uint32(tagKeyMetaBlock[footerPos+12 : footerPos+16])
expectedOrders := []int{0,
meta.bitmapPos, meta.bitmapPos + 1,
meta.offsetsPos, meta.offsetsPos + 1,
footerPos}
// data validation
if !sort.IntsAreSorted(expectedOrders) {
return nil, constants.ErrDataFileCorruption
}
// read trie block data, lazy unmarshal
meta.trieBlock = tagKeyMetaBlock[:meta.bitmapPos] // 0->bitmap pos
// read bitmap data, lazy unmarshal
meta.bitmapData = tagKeyMetaBlock[meta.bitmapPos:meta.offsetsPos]
// read offsets data, lazy unmarshal
meta.offsetsData = tagKeyMetaBlock[meta.offsetsPos:footerPos]
return meta, nil
}
func (meta *tagKeyMeta) TagValueIDSeq() uint32 {
return meta.tagValueIDSeq
}
func (meta *tagKeyMeta) TagValueIDs() (*roaring.Bitmap, error) {
tagValueIDs := roaring.New()
if err := encoding.BitmapUnmarshal(tagValueIDs, meta.bitmapData); err != nil {
return nil, err
}
return tagValueIDs, nil
}
func (meta *tagKeyMeta) TrieTree() (trie.SuccinctTrie, error) {
if meta.tree == nil && meta.unmarshalError == nil {
meta.tree = trie.NewTrie()
meta.unmarshalError = meta.tree.UnmarshalBinary(meta.trieBlock)
}
return meta.tree, meta.unmarshalError
}
// idRanksOffsets sorts ids slice based on the order in ranks
type idRanksOffsets struct {
ids []uint32 // tag-value ids
keys []string // tag-values
ranks []int
offsets []uint32
}
func makeIDRankOffsets(size int) *idRanksOffsets {
return &idRanksOffsets{
ids: make([]uint32, 0, size),
keys: make([]string, 0, size),
ranks: make([]int, 0, size),
offsets: make([]uint32, 0, size),
}
}
func (ir *idRanksOffsets) Len() int { return len(ir.ranks) }
func (ir *idRanksOffsets) Less(i, j int) bool { return ir.ranks[i] < ir.ranks[j] }
func (ir *idRanksOffsets) Swap(i, j int) {
ir.ranks[i], ir.ranks[j] = ir.ranks[j], ir.ranks[i]
ir.ids[i], ir.ids[j] = ir.ids[j], ir.ids[i]
}
func (meta *tagKeyMeta) CollectTagValues(tagValueIds *roaring.Bitmap, tagValues map[uint32]string) error {
tagValueIDsInFile, err := meta.TagValueIDs()
if err != nil {
return err
}
needCollectTagValueIDs := roaring.And(tagValueIds, tagValueIDsInFile)
// tag value ids not exist in current file
if needCollectTagValueIDs.IsEmpty() {
return nil
}
// remove found tag value ids
tagValueIds.Xor(needCollectTagValueIDs)
// pre-allocate all buffer data
mappings := makeIDRankOffsets(int(tagValueIds.GetCardinality()))
highKeys := tagValueIDsInFile.GetHighKeys()
idx := 0
for i, highKey := range highKeys {
hk := uint32(highKey) << 16
containerInFile := tagValueIDsInFile.GetContainerAtIndex(i)
collectContainer := needCollectTagValueIDs.GetContainer(highKey)
if collectContainer != nil {
it := collectContainer.PeekableIterator()
for it.HasNext() {
lowKey := it.Next()
lowIdx := containerInFile.Rank(lowKey)
// calculate offset
offset := idx + lowIdx - 1
mappings.offsets = append(mappings.offsets, uint32(offset))
// calculate id
id := encoding.ValueWithHighLowBits(hk, lowKey)
mappings.ids = append(mappings.ids, id)
}
}
idx += containerInFile.GetCardinality()
}
if err := meta.walkTrieTree(mappings); err != nil {
return err
}
for i, id := range mappings.ids {
tagValues[id] = mappings.keys[i]
}
return nil
}
func (meta *tagKeyMeta) walkTrieTree(mappings *idRanksOffsets) error {
tree, err := meta.TrieTree()
if err != nil {
return err
}
if meta.offsetsDecoder == nil {
meta.offsetsDecoder = encoding.NewFixedOffsetDecoder()
if _, err := meta.offsetsDecoder.Unmarshal(meta.offsetsData); err != nil {
return err
}
}
for _, offset := range mappings.offsets {
rank, ok := meta.offsetsDecoder.Get(int(offset))
if !ok {
return constants.ErrDataFileCorruption
}
mappings.ranks = append(mappings.ranks, rank)
}
sort.Sort(mappings)
itr := tree.NewIterator()
itr.SeekToFirst()
expectedRankIdx := 0 // pop left from ranks
walkedRankAt := 0
for itr.Valid() {
if expectedRankIdx >= len(mappings.ranks) {
break
}
if mappings.ranks[expectedRankIdx] == walkedRankAt {
mappings.keys = append(mappings.keys, string(itr.Key()))
expectedRankIdx++
}
itr.Next()
walkedRankAt++
}
if len(mappings.keys) != len(mappings.ranks) {
return constants.ErrDataFileCorruption
}
return nil
}
func (meta *tagKeyMeta) FindTagValueID(tagValue string) (tagValueIDs []uint32) {
tree, err := meta.TrieTree()
if err != nil {
return nil
}
if slice, ok := tree.Get(strutil.String2ByteSlice(tagValue)); ok {
return []uint32{encoding.ByteSlice2Uint32(slice)}
}
return nil
}
func (meta *tagKeyMeta) FindTagValueIDs(tagValues []string) (tagValueIDs []uint32) {
for _, tagValue := range tagValues {
tagValueIDs = append(tagValueIDs, meta.FindTagValueID(tagValue)...)
}
return tagValueIDs
}
func (meta *tagKeyMeta) PrefixIterator(tagValuePrefix []byte) (*trie.PrefixIterator, error) {
tree, err := meta.TrieTree()
if err != nil {
return nil, err
}
return tree.NewPrefixIterator(tagValuePrefix), nil
}
func (meta *tagKeyMeta) FindTagValueIDsByLike(tagValue string) (tagValueIDs []uint32) {
hashPrefix := strings.HasPrefix(tagValue, "*")
hasSuffix := strings.HasSuffix(tagValue, "*")
tagValueSlice := strutil.String2ByteSlice(tagValue)
switch {
case tagValue == "":
break
// only ends with *
case !hashPrefix && hasSuffix:
itr, err := meta.PrefixIterator(tagValueSlice[:len(tagValueSlice)-1])
if err != nil {
return nil
}
for itr.Valid() {
tagValueIDs = append(tagValueIDs, encoding.ByteSlice2Uint32(itr.Value()))
itr.Next()
}
// only starts with *
case hashPrefix && !hasSuffix:
suffix := tagValueSlice[1:]
itr, err := meta.PrefixIterator(nil)
if err != nil {
return nil
}
for itr.Valid() {
if bytes.HasSuffix(itr.Key(), suffix) {
tagValueIDs = append(tagValueIDs, encoding.ByteSlice2Uint32(itr.Value()))
}
itr.Next()
}
// starts with and ends with *
case hashPrefix && hasSuffix:
middle := tagValueSlice[1 : len(tagValueSlice)-1]
itr, err := meta.PrefixIterator(nil)
if err != nil {
return nil
}
for itr.Valid() {
if bytes.Contains(itr.Key(), middle) {
tagValueIDs = append(tagValueIDs, encoding.ByteSlice2Uint32(itr.Value()))
}
itr.Next()
}
default:
return meta.FindTagValueID(tagValue)
}
return tagValueIDs
}
func (meta *tagKeyMeta) FindTagValueIDsByRegex(tagValuePattern string) (tagValueIDs []uint32) {
rp, err := regexp.Compile(tagValuePattern)
if err != nil {
return nil
}
literalPrefix, _ := rp.LiteralPrefix()
literalPrefixByte := strutil.String2ByteSlice(literalPrefix)
itr, err := meta.PrefixIterator(literalPrefixByte)
if err != nil {
return nil
}
for itr.Valid() {
if rp.Match(itr.Key()) {
tagValueIDs = append(tagValueIDs, encoding.ByteSlice2Uint32(itr.Value()))
}
itr.Next()
}
return tagValueIDs
}