forked from influxdata/flux
-
Notifications
You must be signed in to change notification settings - Fork 0
/
state_tracking.go
322 lines (281 loc) · 8.32 KB
/
state_tracking.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
package universe
import (
"context"
"log"
"time"
"github.com/wolffcm/flux"
"github.com/wolffcm/flux/codes"
"github.com/wolffcm/flux/compiler"
"github.com/wolffcm/flux/execute"
"github.com/wolffcm/flux/internal/errors"
"github.com/wolffcm/flux/interpreter"
"github.com/wolffcm/flux/plan"
"github.com/wolffcm/flux/runtime"
"github.com/wolffcm/flux/values"
)
const StateTrackingKind = "stateTracking"
type StateTrackingOpSpec struct {
Fn interpreter.ResolvedFunction `json:"fn"`
CountColumn string `json:"countColumn"`
DurationColumn string `json:"durationColumn"`
DurationUnit flux.Duration `json:"durationUnit"`
TimeColumn string `json:"timeColumn"`
}
func init() {
stateTrackingSignature := runtime.MustLookupBuiltinType("universe", "stateTracking")
runtime.RegisterPackageValue("universe", StateTrackingKind, flux.MustValue(flux.FunctionValue(StateTrackingKind, createStateTrackingOpSpec, stateTrackingSignature)))
flux.RegisterOpSpec(StateTrackingKind, newStateTrackingOp)
plan.RegisterProcedureSpec(StateTrackingKind, newStateTrackingProcedure, StateTrackingKind)
execute.RegisterTransformation(StateTrackingKind, createStateTrackingTransformation)
}
func createStateTrackingOpSpec(args flux.Arguments, a *flux.Administration) (flux.OperationSpec, error) {
if err := a.AddParentFromArgs(args); err != nil {
return nil, err
}
f, err := args.GetRequiredFunction("fn")
if err != nil {
return nil, err
}
fn, err := interpreter.ResolveFunction(f)
if err != nil {
return nil, err
}
spec := &StateTrackingOpSpec{
Fn: fn,
DurationUnit: flux.ConvertDuration(time.Second),
}
if label, ok, err := args.GetString("countColumn"); err != nil {
return nil, err
} else if ok {
spec.CountColumn = label
}
if label, ok, err := args.GetString("durationColumn"); err != nil {
return nil, err
} else if ok {
spec.DurationColumn = label
}
if unit, ok, err := args.GetDuration("durationUnit"); err != nil {
return nil, err
} else if ok {
spec.DurationUnit = unit
}
if label, ok, err := args.GetString("timeColumn"); err != nil {
return nil, err
} else if ok {
spec.TimeColumn = label
} else {
spec.TimeColumn = execute.DefaultTimeColLabel
}
if spec.DurationColumn != "" && !values.Duration(spec.DurationUnit).IsPositive() {
return nil, errors.New(codes.Invalid, "state tracking duration unit must be greater than zero")
}
return spec, nil
}
func newStateTrackingOp() flux.OperationSpec {
return new(StateTrackingOpSpec)
}
func (s *StateTrackingOpSpec) Kind() flux.OperationKind {
return StateTrackingKind
}
type StateTrackingProcedureSpec struct {
plan.DefaultCost
Fn interpreter.ResolvedFunction
CountColumn,
DurationColumn string
DurationUnit flux.Duration
TimeCol string
}
func newStateTrackingProcedure(qs flux.OperationSpec, pa plan.Administration) (plan.ProcedureSpec, error) {
spec, ok := qs.(*StateTrackingOpSpec)
if !ok {
return nil, errors.Newf(codes.Internal, "invalid spec type %T", qs)
}
return &StateTrackingProcedureSpec{
Fn: spec.Fn,
CountColumn: spec.CountColumn,
DurationColumn: spec.DurationColumn,
DurationUnit: spec.DurationUnit,
TimeCol: spec.TimeColumn,
}, nil
}
func (s *StateTrackingProcedureSpec) Kind() plan.ProcedureKind {
return StateTrackingKind
}
func (s *StateTrackingProcedureSpec) Copy() plan.ProcedureSpec {
ns := new(StateTrackingProcedureSpec)
*ns = *s
ns.Fn = s.Fn.Copy()
return ns
}
// TriggerSpec implements plan.TriggerAwareProcedureSpec
func (s *StateTrackingProcedureSpec) TriggerSpec() plan.TriggerSpec {
return plan.NarrowTransformationTriggerSpec{}
}
func createStateTrackingTransformation(id execute.DatasetID, mode execute.AccumulationMode, spec plan.ProcedureSpec, a execute.Administration) (execute.Transformation, execute.Dataset, error) {
s, ok := spec.(*StateTrackingProcedureSpec)
if !ok {
return nil, nil, errors.Newf(codes.Internal, "invalid spec type %T", spec)
}
cache := execute.NewTableBuilderCache(a.Allocator())
d := execute.NewDataset(id, mode, cache)
t, err := NewStateTrackingTransformation(a.Context(), s, d, cache)
if err != nil {
return nil, nil, err
}
return t, d, nil
}
type stateTrackingTransformation struct {
d execute.Dataset
cache execute.TableBuilderCache
fn *execute.RowPredicateFn
ctx context.Context
timeCol,
countColumn,
durationColumn string
durationUnit int64
}
func NewStateTrackingTransformation(ctx context.Context, spec *StateTrackingProcedureSpec, d execute.Dataset, cache execute.TableBuilderCache) (*stateTrackingTransformation, error) {
fn, err := execute.NewRowPredicateFn(spec.Fn.Fn, compiler.ToScope(spec.Fn.Scope))
if err != nil {
return nil, err
}
return &stateTrackingTransformation{
d: d,
cache: cache,
fn: fn,
countColumn: spec.CountColumn,
durationColumn: spec.DurationColumn,
durationUnit: int64(values.Duration(spec.DurationUnit).Duration()),
timeCol: spec.TimeCol,
ctx: ctx,
}, nil
}
func (t *stateTrackingTransformation) RetractTable(id execute.DatasetID, key flux.GroupKey) error {
return t.d.RetractTable(key)
}
func (t *stateTrackingTransformation) Process(id execute.DatasetID, tbl flux.Table) error {
builder, created := t.cache.TableBuilder(tbl.Key())
if !created {
return errors.Newf(codes.FailedPrecondition, "found duplicate table with key: %v", tbl.Key())
}
err := execute.AddTableCols(tbl, builder)
if err != nil {
return err
}
// Prepare the functions for the column types.
cols := tbl.Cols()
err = t.fn.Prepare(cols)
if err != nil {
// TODO(nathanielc): Should we not fail the query for failed compilation?
return err
}
var countCol, durationCol = -1, -1
// Add new value columns
if t.countColumn != "" {
countCol, err = builder.AddCol(flux.ColMeta{
Label: t.countColumn,
Type: flux.TInt,
})
if err != nil {
return err
}
}
if t.durationColumn != "" {
durationCol, err = builder.AddCol(flux.ColMeta{
Label: t.durationColumn,
Type: flux.TInt,
})
if err != nil {
return err
}
}
var (
startTime values.Time
prevTime values.Time
count int64
duration int64
countInState bool
durationInState bool
)
timeIdx := execute.ColIdx(t.timeCol, tbl.Cols())
if timeIdx < 0 {
return errors.Newf(codes.FailedPrecondition, "no column %q exists", t.timeCol)
}
colMap := make([]int, len(tbl.Cols()))
colMap = execute.ColMap(colMap, builder, tbl.Cols())
// Append modified rows
return tbl.Do(func(cr flux.ColReader) error {
l := cr.Len()
for i := 0; i < l; i++ {
match, err := t.fn.EvalRow(t.ctx, i, cr)
if err != nil {
log.Printf("failed to evaluate state tracking expression: %v", err)
continue
}
// Duration
if durationCol > 0 {
if ts := cr.Times(timeIdx); ts.IsNull(i) {
return errors.New(codes.FailedPrecondition, "got a null timestamp")
}
tValue := values.Time(cr.Times(timeIdx).Value(i))
if prevTime > tValue {
return errors.New(codes.FailedPrecondition, "got an out-of-order timestamp")
}
prevTime = tValue
if !match {
duration = -1
durationInState = false
} else {
if !durationInState {
startTime = tValue
duration = 0
durationInState = true
}
if t.durationUnit > 0 {
tm := tValue
duration = int64(tm-startTime) / t.durationUnit
}
}
}
// Count
if countCol > 0 {
if !match {
count = -1
countInState = false
} else {
if !countInState {
count = 0
countInState = true
}
count++
}
}
err = execute.AppendMappedRecordExplicit(i, cr, builder, colMap)
if err != nil {
return err
}
if countCol > 0 {
err = builder.AppendInt(countCol, count)
if err != nil {
return err
}
}
if durationCol > 0 {
err = builder.AppendInt(durationCol, duration)
if err != nil {
return err
}
}
}
return nil
})
}
func (t *stateTrackingTransformation) UpdateWatermark(id execute.DatasetID, mark execute.Time) error {
return t.d.UpdateWatermark(mark)
}
func (t *stateTrackingTransformation) UpdateProcessingTime(id execute.DatasetID, pt execute.Time) error {
return t.d.UpdateProcessingTime(pt)
}
func (t *stateTrackingTransformation) Finish(id execute.DatasetID, err error) {
t.d.Finish(err)
}