-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
task.median.go
73 lines (62 loc) · 2.01 KB
/
task.median.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
package pipeline
import (
"context"
"sort"
"github.com/pkg/errors"
"github.com/shopspring/decimal"
"go.uber.org/multierr"
"github.com/smartcontractkit/chainlink/core/logger"
)
//
// Return types:
// *decimal.Decimal
//
type MedianTask struct {
BaseTask `mapstructure:",squash"`
Values string `json:"values"`
AllowedFaults string `json:"allowedFaults"`
}
var _ Task = (*MedianTask)(nil)
func (t *MedianTask) Type() TaskType {
return TaskTypeMedian
}
func (t *MedianTask) Run(_ context.Context, _ logger.Logger, vars Vars, inputs []Result) (result Result, runInfo RunInfo) {
var (
maybeAllowedFaults MaybeUint64Param
valuesAndErrs SliceParam
decimalValues DecimalSliceParam
allowedFaults int
faults int
)
err := multierr.Combine(
errors.Wrap(ResolveParam(&maybeAllowedFaults, From(t.AllowedFaults)), "allowedFaults"),
errors.Wrap(ResolveParam(&valuesAndErrs, From(VarExpr(t.Values, vars), JSONWithVarExprs(t.Values, vars, true), Inputs(inputs))), "values"),
)
if err != nil {
return Result{Error: err}, runInfo
}
if allowed, isSet := maybeAllowedFaults.Uint64(); isSet {
allowedFaults = int(allowed)
} else {
allowedFaults = len(valuesAndErrs) - 1
}
values, faults := valuesAndErrs.FilterErrors()
if faults > allowedFaults {
return Result{Error: errors.Wrapf(ErrTooManyErrors, "Number of faulty inputs %v to median task > number allowed faults %v", faults, allowedFaults)}, runInfo
} else if len(values) == 0 {
return Result{Error: errors.Wrap(ErrWrongInputCardinality, "no values to medianize")}, runInfo
}
err = decimalValues.UnmarshalPipelineParam(values)
if err != nil {
return Result{Error: err}, runInfo
}
sort.Slice(decimalValues, func(i, j int) bool {
return decimalValues[i].LessThan(decimalValues[j])
})
k := len(decimalValues) / 2
if len(decimalValues)%2 == 1 {
return Result{Value: decimalValues[k]}, runInfo
}
median := decimalValues[k].Add(decimalValues[k-1]).Div(decimal.NewFromInt(2))
return Result{Value: median}, runInfo
}