-
Notifications
You must be signed in to change notification settings - Fork 0
/
aggregate_results.go
308 lines (263 loc) · 7.83 KB
/
aggregate_results.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
// Copyright (c) 2019 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package index
import (
"fmt"
"sync"
"github.com/m3db/m3/src/m3ninx/doc"
"github.com/m3db/m3/src/x/ident"
"github.com/m3db/m3/src/x/pool"
)
const missingDocumentFields = "invalid document fields: empty %s"
type aggregatedResults struct {
sync.RWMutex
nsID ident.ID
aggregateOpts AggregateResultsOptions
resultsMap *AggregateResultsMap
idPool ident.Pool
bytesPool pool.CheckedBytesPool
pool AggregateResultsPool
valuesPool AggregateValuesPool
}
// NewAggregateResults returns a new AggregateResults object.
func NewAggregateResults(
namespaceID ident.ID,
aggregateOpts AggregateResultsOptions,
opts Options,
) AggregateResults {
return &aggregatedResults{
nsID: namespaceID,
aggregateOpts: aggregateOpts,
resultsMap: newAggregateResultsMap(opts.IdentifierPool()),
idPool: opts.IdentifierPool(),
bytesPool: opts.CheckedBytesPool(),
pool: opts.AggregateResultsPool(),
valuesPool: opts.AggregateValuesPool(),
}
}
func (r *aggregatedResults) Reset(
nsID ident.ID,
aggregateOpts AggregateResultsOptions,
) {
r.Lock()
r.aggregateOpts = aggregateOpts
// finalize existing held nsID
if r.nsID != nil {
r.nsID.Finalize()
}
// make an independent copy of the new nsID
if nsID != nil {
nsID = r.idPool.Clone(nsID)
}
r.nsID = nsID
// reset all values from map first
for _, entry := range r.resultsMap.Iter() {
valueMap := entry.Value()
valueMap.finalize()
}
// reset all keys in the map next
r.resultsMap.Reset()
// NB: could do keys+value in one step but I'm trying to avoid
// using an internal method of a code-gen'd type.
r.Unlock()
}
func (r *aggregatedResults) AddDocuments(batch []doc.Document) (int, error) {
r.Lock()
err := r.addDocumentsBatchWithLock(batch)
size := r.resultsMap.Len()
r.Unlock()
return size, err
}
func (r *aggregatedResults) AggregateResultsOptions() AggregateResultsOptions {
return r.aggregateOpts
}
func (r *aggregatedResults) AddFields(batch []AggregateResultsEntry) int {
r.Lock()
for _, entry := range batch {
f := entry.Field
aggValues, ok := r.resultsMap.Get(f)
if !ok {
aggValues = r.valuesPool.Get()
// we can avoid the copy because we assume ownership of the passed ident.ID,
// but still need to finalize it.
r.resultsMap.SetUnsafe(f, aggValues, AggregateResultsMapSetUnsafeOptions{
NoCopyKey: true,
NoFinalizeKey: false,
})
} else {
// because we already have a entry for this field, we release the ident back to
// the underlying pool.
f.Finalize()
}
valuesMap := aggValues.Map()
for _, t := range entry.Terms {
if !valuesMap.Contains(t) {
// we can avoid the copy because we assume ownership of the passed ident.ID,
// but still need to finalize it.
valuesMap.SetUnsafe(t, struct{}{}, AggregateValuesMapSetUnsafeOptions{
NoCopyKey: true,
NoFinalizeKey: false,
})
} else {
// because we already have a entry for this term, we release the ident back to
// the underlying pool.
t.Finalize()
}
}
}
size := r.resultsMap.Len()
r.Unlock()
return size
}
func (r *aggregatedResults) addDocumentsBatchWithLock(
batch []doc.Document,
) error {
for _, doc := range batch {
switch r.aggregateOpts.Type {
case AggregateTagNamesAndValues:
if err := r.addDocumentWithLock(doc); err != nil {
return err
}
case AggregateTagNames:
// NB: if aggregating by name only, can ignore any additional documents
// after the result map size exceeds the optional size limit, since all
// incoming terms are either duplicates or new values which will exceed
// the limit.
size := r.resultsMap.Len()
if r.aggregateOpts.SizeLimit > 0 && size >= r.aggregateOpts.SizeLimit {
return nil
}
if err := r.addDocumentTermsWithLock(doc); err != nil {
return err
}
default:
return fmt.Errorf("unsupported aggregation type: %v", r.aggregateOpts.Type)
}
}
return nil
}
func (r *aggregatedResults) addDocumentTermsWithLock(
document doc.Document,
) error {
for _, field := range document.Fields {
if err := r.addTermWithLock(field.Name); err != nil {
return fmt.Errorf("unable to add document terms [%+v]: %v", document, err)
}
}
return nil
}
func (r *aggregatedResults) addTermWithLock(
term []byte,
) error {
if len(term) == 0 {
return fmt.Errorf(missingDocumentFields, "term")
}
// if a term filter is provided, ensure this field matches the filter,
// otherwise ignore it.
filter := r.aggregateOpts.FieldFilter
if filter != nil && !filter.Allow(term) {
return nil
}
// NB: can cast the []byte -> ident.ID to avoid an alloc
// before we're sure we need it.
termID := ident.BytesID(term)
if r.resultsMap.Contains(termID) {
// NB: this term is already added; continue.
return nil
}
// Set results map to an empty AggregateValues since we only care about
// existence of the term in the map, rather than its set of values.
r.resultsMap.Set(termID, r.valuesPool.Get())
return nil
}
func (r *aggregatedResults) addDocumentWithLock(
document doc.Document,
) error {
for _, field := range document.Fields {
if err := r.addFieldWithLock(field.Name, field.Value); err != nil {
return fmt.Errorf("unable to add document [%+v]: %v", document, err)
}
}
return nil
}
func (r *aggregatedResults) addFieldWithLock(
term []byte,
value []byte,
) error {
if len(term) == 0 {
return fmt.Errorf(missingDocumentFields, "term")
}
if len(value) == 0 {
return fmt.Errorf(missingDocumentFields, "value")
}
// if a term filter is provided, ensure this field matches the filter,
// otherwise ignore it.
filter := r.aggregateOpts.FieldFilter
if filter != nil && !filter.Allow(term) {
return nil
}
// NB: can cast the []byte -> ident.ID to avoid an alloc
// before we're sure we need it.
termID := ident.BytesID(term)
valueID := ident.BytesID(value)
valueMap, found := r.resultsMap.Get(termID)
if found {
return valueMap.addValue(valueID)
}
// NB: if over limit, do not add any new values to the map.
if r.aggregateOpts.SizeLimit > 0 &&
r.resultsMap.Len() >= r.aggregateOpts.SizeLimit {
// Early return if limit enforced and we hit our limit.
return nil
}
aggValues := r.valuesPool.Get()
if err := aggValues.addValue(valueID); err != nil {
// Return these values to the pool.
r.valuesPool.Put(aggValues)
return err
}
r.resultsMap.Set(termID, aggValues)
return nil
}
func (r *aggregatedResults) Namespace() ident.ID {
r.RLock()
ns := r.nsID
r.RUnlock()
return ns
}
func (r *aggregatedResults) Map() *AggregateResultsMap {
r.RLock()
m := r.resultsMap
r.RUnlock()
return m
}
func (r *aggregatedResults) Size() int {
r.RLock()
l := r.resultsMap.Len()
r.RUnlock()
return l
}
func (r *aggregatedResults) Finalize() {
r.Reset(nil, AggregateResultsOptions{})
if r.pool == nil {
return
}
r.pool.Put(r)
}