forked from smartcontractkit/chainlink
-
Notifications
You must be signed in to change notification settings - Fork 0
/
common.go
461 lines (412 loc) · 13.1 KB
/
common.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
package pipeline
import (
"context"
"database/sql/driver"
"encoding/hex"
"encoding/json"
"math/big"
"net/url"
"reflect"
"sort"
"strconv"
"strings"
"time"
"github.com/mitchellh/mapstructure"
"github.com/pkg/errors"
uuid "github.com/satori/go.uuid"
"gopkg.in/guregu/null.v4"
"github.com/DCMMC/chainlink/core/chains/evm"
"github.com/DCMMC/chainlink/core/logger"
cnull "github.com/DCMMC/chainlink/core/null"
"github.com/DCMMC/chainlink/core/store/models"
"github.com/DCMMC/chainlink/core/utils"
)
//go:generate mockery --name Config --output ./mocks/ --case=underscore
//go:generate mockery --name Task --output ./mocks/ --case=underscore
type (
Task interface {
Type() TaskType
ID() int
DotID() string
Run(ctx context.Context, vars Vars, inputs []Result) (Result, RunInfo)
Base() *BaseTask
Outputs() []Task
Inputs() []Task
OutputIndex() int32
TaskTimeout() (time.Duration, bool)
TaskRetries() uint32
TaskMinBackoff() time.Duration
TaskMaxBackoff() time.Duration
}
Config interface {
BridgeResponseURL() *url.URL
DatabaseMaximumTxDuration() time.Duration
DatabaseURL() url.URL
DefaultHTTPLimit() int64
DefaultHTTPTimeout() models.Duration
DefaultMaxHTTPAttempts() uint
DefaultHTTPAllowUnrestrictedNetworkAccess() bool
TriggerFallbackDBPollInterval() time.Duration
JobPipelineMaxRunDuration() time.Duration
JobPipelineReaperInterval() time.Duration
JobPipelineReaperThreshold() time.Duration
}
)
var (
ErrWrongInputCardinality = errors.New("wrong number of task inputs")
ErrBadInput = errors.New("bad input for task")
ErrInputTaskErrored = errors.New("input task errored")
ErrParameterEmpty = errors.New("parameter is empty")
ErrTooManyErrors = errors.New("too many errors")
ErrTimeout = errors.New("timeout")
ErrTaskRunFailed = errors.New("task run failed")
ErrCancelled = errors.New("task run cancelled (fail early)")
)
const (
InputTaskKey = "input"
)
// RunInfo contains additional information about the finished TaskRun
type RunInfo struct {
IsRetryable bool
IsPending bool
}
// retryableMeta should be returned if the error is non-deterministic; i.e. a
// repeated attempt sometime later _might_ succeed where the current attempt
// failed
func retryableRunInfo() RunInfo {
return RunInfo{IsRetryable: true}
}
func pendingRunInfo() RunInfo {
return RunInfo{IsPending: true}
}
func isRetryableHTTPError(statusCode int, err error) bool {
if statusCode >= 400 && statusCode < 500 {
// Client errors are not likely to succeed by resubmitting the exact same information again
return false
} else if statusCode >= 500 {
// Remote errors _might_ work on a retry
return true
}
return err != nil
}
// Result is the result of a TaskRun
type Result struct {
Value interface{}
Error error
}
// OutputDB dumps a single result output for a pipeline_run or pipeline_task_run
func (result Result) OutputDB() JSONSerializable {
return JSONSerializable{Val: result.Value, Valid: !(result.Value == nil || (reflect.ValueOf(result.Value).Kind() == reflect.Ptr && reflect.ValueOf(result.Value).IsNil()))}
}
// ErrorDB dumps a single result error for a pipeline_task_run
func (result Result) ErrorDB() null.String {
var errString null.String
if result.Error != nil {
errString = null.StringFrom(result.Error.Error())
}
return errString
}
// FinalResult is the result of a Run
type FinalResult struct {
Values []interface{}
AllErrors []error
FatalErrors []error
}
// HasFatalErrors returns true if the final result has any errors
func (result FinalResult) HasFatalErrors() bool {
for _, err := range result.FatalErrors {
if err != nil {
return true
}
}
return false
}
// HasErrors returns true if the final result has any errors
func (result FinalResult) HasErrors() bool {
for _, err := range result.AllErrors {
if err != nil {
return true
}
}
return false
}
// SingularResult returns a single result if the FinalResult only has one set of outputs/errors
func (result FinalResult) SingularResult() (Result, error) {
if len(result.FatalErrors) != 1 || len(result.Values) != 1 {
return Result{}, errors.Errorf("cannot cast FinalResult to singular result; it does not have exactly 1 error and exactly 1 output: %#v", result)
}
return Result{Error: result.FatalErrors[0], Value: result.Values[0]}, nil
}
// TaskRunResult describes the result of a task run, suitable for database
// update or insert.
// ID might be zero if the TaskRun has not been inserted yet
// TaskSpecID will always be non-zero
type TaskRunResult struct {
ID uuid.UUID
Task Task
TaskRun TaskRun
Result Result
Attempts uint
CreatedAt time.Time
FinishedAt null.Time
// runInfo is never persisted
runInfo RunInfo
}
func (result *TaskRunResult) IsPending() bool {
return !result.FinishedAt.Valid && result.Result == Result{}
}
func (result *TaskRunResult) IsTerminal() bool {
return len(result.Task.Outputs()) == 0
}
// TaskRunResults represents a collection of results for all task runs for one pipeline run
type TaskRunResults []TaskRunResult
// FinalResult pulls the FinalResult for the pipeline_run from the task runs
// It needs to respect the output index of each task
func (trrs TaskRunResults) FinalResult() FinalResult {
var found bool
var fr FinalResult
sort.Slice(trrs, func(i, j int) bool {
return trrs[i].Task.OutputIndex() < trrs[j].Task.OutputIndex()
})
for _, trr := range trrs {
fr.AllErrors = append(fr.AllErrors, trr.Result.Error)
if trr.IsTerminal() {
fr.Values = append(fr.Values, trr.Result.Value)
fr.FatalErrors = append(fr.FatalErrors, trr.Result.Error)
found = true
}
}
if !found {
logger.Errorw("expected at least one task to be final", "tasks", trrs)
panic("expected at least one task to be final")
}
return fr
}
type JSONSerializable struct {
Val interface{}
Valid bool
}
// NewJSONSerializable returns an instance of JSONSerializable with the passed parameters.
func NewJSONSerializable(val interface{}, valid bool) JSONSerializable {
return JSONSerializable{
Val: val,
Valid: valid,
}
}
// JSONSerializableFrom creates a new JSONSerializable that will always be valid.
func JSONSerializableFrom(val interface{}) JSONSerializable {
return NewJSONSerializable(val, true)
}
// UnmarshalJSON implements custom unmarshaling logic
func (js *JSONSerializable) UnmarshalJSON(bs []byte) error {
if js == nil {
*js = JSONSerializable{}
}
str := string(bs)
if str == "" || str == "null" {
js.Valid = false
return nil
}
err := json.Unmarshal(bs, &js.Val)
js.Valid = err == nil
return err
}
// MarshalJSON implements custom marshaling logic
func (js JSONSerializable) MarshalJSON() ([]byte, error) {
if !js.Valid {
return []byte("null"), nil
}
switch x := js.Val.(type) {
case []byte:
// Don't need to HEX encode if it is a valid JSON string
if json.Valid(x) {
return json.Marshal(string(x))
}
// Don't need to HEX encode if it is already HEX encoded value
if utils.IsHexBytes(x) {
return json.Marshal(string(x))
}
return json.Marshal(hex.EncodeToString(x))
default:
return json.Marshal(js.Val)
}
}
func (js *JSONSerializable) Scan(value interface{}) error {
if value == nil {
*js = JSONSerializable{}
return nil
}
bytes, ok := value.([]byte)
if !ok {
return errors.Errorf("JSONSerializable#Scan received a value of type %T", value)
}
if js == nil {
*js = JSONSerializable{}
}
return js.UnmarshalJSON(bytes)
}
func (js JSONSerializable) Value() (driver.Value, error) {
if !js.Valid {
return nil, nil
}
return js.MarshalJSON()
}
func (js *JSONSerializable) Empty() bool {
return js == nil || !js.Valid
}
type TaskType string
func (t TaskType) String() string {
return string(t)
}
const (
TaskTypeHTTP TaskType = "http"
TaskTypeBridge TaskType = "bridge"
TaskTypeMean TaskType = "mean"
TaskTypeMedian TaskType = "median"
TaskTypeMode TaskType = "mode"
TaskTypeSum TaskType = "sum"
TaskTypeMultiply TaskType = "multiply"
TaskTypeDivide TaskType = "divide"
TaskTypeJSONParse TaskType = "jsonparse"
TaskTypeCBORParse TaskType = "cborparse"
TaskTypeAny TaskType = "any"
TaskTypeVRF TaskType = "vrf"
TaskTypeVRFV2 TaskType = "vrfv2"
TaskTypeEstimateGasLimit TaskType = "estimategaslimit"
TaskTypeETHCall TaskType = "ethcall"
TaskTypeETHTx TaskType = "ethtx"
TaskTypeETHABIEncode TaskType = "ethabiencode"
TaskTypeETHABIEncode2 TaskType = "ethabiencode2"
TaskTypeETHABIDecode TaskType = "ethabidecode"
TaskTypeETHABIDecodeLog TaskType = "ethabidecodelog"
TaskTypeMerge TaskType = "merge"
// Testing only.
TaskTypePanic TaskType = "panic"
TaskTypeMemo TaskType = "memo"
TaskTypeFail TaskType = "fail"
)
var (
stringType = reflect.TypeOf("")
bytesType = reflect.TypeOf([]byte(nil))
bytes20Type = reflect.TypeOf([20]byte{})
int32Type = reflect.TypeOf(int32(0))
nullUint32Type = reflect.TypeOf(cnull.Uint32{})
)
func UnmarshalTaskFromMap(taskType TaskType, taskMap interface{}, ID int, dotID string) (_ Task, err error) {
defer utils.WrapIfError(&err, "UnmarshalTaskFromMap")
switch taskMap.(type) {
default:
return nil, errors.Errorf("UnmarshalTaskFromMap only accepts a map[string]interface{} or a map[string]string. Got %v (%#v) of type %T", taskMap, taskMap, taskMap)
case map[string]interface{}, map[string]string:
}
taskType = TaskType(strings.ToLower(string(taskType)))
var task Task
switch taskType {
case TaskTypePanic:
task = &PanicTask{BaseTask: BaseTask{id: ID, dotID: dotID}}
case TaskTypeHTTP:
task = &HTTPTask{BaseTask: BaseTask{id: ID, dotID: dotID}}
case TaskTypeBridge:
task = &BridgeTask{BaseTask: BaseTask{id: ID, dotID: dotID}}
case TaskTypeMean:
task = &MeanTask{BaseTask: BaseTask{id: ID, dotID: dotID}}
case TaskTypeMedian:
task = &MedianTask{BaseTask: BaseTask{id: ID, dotID: dotID}}
case TaskTypeMode:
task = &ModeTask{BaseTask: BaseTask{id: ID, dotID: dotID}}
case TaskTypeSum:
task = &SumTask{BaseTask: BaseTask{id: ID, dotID: dotID}}
case TaskTypeAny:
task = &AnyTask{BaseTask: BaseTask{id: ID, dotID: dotID}}
case TaskTypeJSONParse:
task = &JSONParseTask{BaseTask: BaseTask{id: ID, dotID: dotID}}
case TaskTypeMemo:
task = &MemoTask{BaseTask: BaseTask{id: ID, dotID: dotID}}
case TaskTypeMultiply:
task = &MultiplyTask{BaseTask: BaseTask{id: ID, dotID: dotID}}
case TaskTypeDivide:
task = &DivideTask{BaseTask: BaseTask{id: ID, dotID: dotID}}
case TaskTypeVRF:
task = &VRFTask{BaseTask: BaseTask{id: ID, dotID: dotID}}
case TaskTypeVRFV2:
task = &VRFTaskV2{BaseTask: BaseTask{id: ID, dotID: dotID}}
case TaskTypeEstimateGasLimit:
task = &EstimateGasLimitTask{BaseTask: BaseTask{id: ID, dotID: dotID}}
case TaskTypeETHCall:
task = ÐCallTask{BaseTask: BaseTask{id: ID, dotID: dotID}}
case TaskTypeETHTx:
task = ÐTxTask{BaseTask: BaseTask{id: ID, dotID: dotID}}
case TaskTypeETHABIEncode:
task = ÐABIEncodeTask{BaseTask: BaseTask{id: ID, dotID: dotID}}
case TaskTypeETHABIEncode2:
task = ÐABIEncodeTask2{BaseTask: BaseTask{id: ID, dotID: dotID}}
case TaskTypeETHABIDecode:
task = ÐABIDecodeTask{BaseTask: BaseTask{id: ID, dotID: dotID}}
case TaskTypeETHABIDecodeLog:
task = ÐABIDecodeLogTask{BaseTask: BaseTask{id: ID, dotID: dotID}}
case TaskTypeCBORParse:
task = &CBORParseTask{BaseTask: BaseTask{id: ID, dotID: dotID}}
case TaskTypeFail:
task = &FailTask{BaseTask: BaseTask{id: ID, dotID: dotID}}
case TaskTypeMerge:
task = &MergeTask{BaseTask: BaseTask{id: ID, dotID: dotID}}
default:
return nil, errors.Errorf(`unknown task type: "%v"`, taskType)
}
decoder, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
Result: task,
WeaklyTypedInput: true,
DecodeHook: mapstructure.ComposeDecodeHookFunc(
mapstructure.StringToTimeDurationHookFunc(),
func(from reflect.Type, to reflect.Type, data interface{}) (interface{}, error) {
if from != stringType {
return data, nil
}
switch to {
case nullUint32Type:
i, err2 := strconv.ParseUint(data.(string), 10, 32)
return cnull.Uint32From(uint32(i)), err2
}
return data, nil
},
),
})
if err != nil {
return nil, err
}
err = decoder.Decode(taskMap)
if err != nil {
return nil, err
}
return task, nil
}
func CheckInputs(inputs []Result, minLen, maxLen, maxErrors int) ([]interface{}, error) {
if minLen >= 0 && len(inputs) < minLen {
return nil, errors.Wrapf(ErrWrongInputCardinality, "min: %v max: %v (got %v)", minLen, maxLen, len(inputs))
} else if maxLen >= 0 && len(inputs) > maxLen {
return nil, errors.Wrapf(ErrWrongInputCardinality, "min: %v max: %v (got %v)", minLen, maxLen, len(inputs))
}
var vals []interface{}
var errs int
for _, input := range inputs {
if input.Error != nil {
errs++
continue
}
vals = append(vals, input.Value)
}
if maxErrors >= 0 && errs > maxErrors {
return nil, ErrTooManyErrors
}
return vals, nil
}
func getChainByString(chainSet evm.ChainSet, str string) (evm.Chain, error) {
if str == "" {
return chainSet.Default()
}
id, ok := new(big.Int).SetString(str, 10)
if !ok {
return nil, errors.Errorf("invalid EVM chain ID: %s", str)
}
return chainSet.Get(id)
}