-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
drlistener.go
357 lines (326 loc) · 12.2 KB
/
drlistener.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
package directrequestocr
import (
"context"
"fmt"
"reflect"
"sync"
"time"
"github.com/ethereum/go-ethereum/common"
"github.com/smartcontractkit/chainlink/core/chains/evm/log"
"github.com/smartcontractkit/chainlink/core/gethwrappers/generated/ocr2dr_oracle"
"github.com/smartcontractkit/chainlink/core/logger"
"github.com/smartcontractkit/chainlink/core/services/job"
"github.com/smartcontractkit/chainlink/core/services/ocr2/plugins/directrequestocr/config"
"github.com/smartcontractkit/chainlink/core/services/pg"
"github.com/smartcontractkit/chainlink/core/services/pipeline"
"github.com/smartcontractkit/chainlink/core/utils"
)
var (
_ log.Listener = &DRListener{}
_ job.ServiceCtx = &DRListener{}
)
const (
ParseResultTaskName string = "parse_result"
ParseErrorTaskName string = "parse_error"
)
type DRListener struct {
utils.StartStopOnce
oracle *ocr2dr_oracle.OCR2DROracle
job job.Job
pipelineRunner pipeline.Runner
jobORM job.ORM
logBroadcaster log.Broadcaster
shutdownWaitGroup sync.WaitGroup
mbOracleEvents *utils.Mailbox[log.Broadcast]
serviceContext context.Context
serviceCancel context.CancelFunc
chStop chan struct{}
pluginORM ORM
pluginConfig config.PluginConfig
logger logger.Logger
mailMon *utils.MailboxMonitor
}
func formatRequestId(requestId [32]byte) string {
return fmt.Sprintf("0x%x", requestId)
}
func NewDRListener(oracle *ocr2dr_oracle.OCR2DROracle, jb job.Job, runner pipeline.Runner, jobORM job.ORM, pluginORM ORM, pluginConfig config.PluginConfig, logBroadcaster log.Broadcaster, lggr logger.Logger, mailMon *utils.MailboxMonitor) *DRListener {
return &DRListener{
oracle: oracle,
job: jb,
pipelineRunner: runner,
jobORM: jobORM,
logBroadcaster: logBroadcaster,
mbOracleEvents: utils.NewHighCapacityMailbox[log.Broadcast](),
chStop: make(chan struct{}),
pluginORM: pluginORM,
pluginConfig: pluginConfig,
logger: lggr,
mailMon: mailMon,
}
}
// Start complies with job.Service
func (l *DRListener) Start(context.Context) error {
return l.StartOnce("DirectRequestListener", func() error {
l.serviceContext, l.serviceCancel = context.WithCancel(context.Background())
unsubscribeLogs := l.logBroadcaster.Register(l, log.ListenerOpts{
Contract: l.oracle.Address(),
ParseLog: l.oracle.ParseLog,
LogsWithTopics: map[common.Hash][][]log.Topic{
ocr2dr_oracle.OCR2DROracleOracleRequest{}.Topic(): {},
ocr2dr_oracle.OCR2DROracleOracleResponse{}.Topic(): {},
ocr2dr_oracle.OCR2DROracleUserCallbackError{}.Topic(): {},
ocr2dr_oracle.OCR2DROracleUserCallbackRawError{}.Topic(): {},
},
MinIncomingConfirmations: l.pluginConfig.MinIncomingConfirmations,
})
if l.pluginConfig.ListenerEventHandlerTimeoutSec == 0 {
l.logger.Warn("listenerEventHandlerTimeoutSec set to zero! ORM calls will never time out.")
}
l.shutdownWaitGroup.Add(3)
go l.processOracleEvents()
go l.timeoutRequests()
go func() {
<-l.chStop
unsubscribeLogs()
l.shutdownWaitGroup.Done()
}()
l.mailMon.Monitor(l.mbOracleEvents, "DirectRequestListener", "OracleEvents", fmt.Sprint(l.job.ID))
return nil
})
}
// Close complies with job.Service
func (l *DRListener) Close() error {
return l.StopOnce("DirectRequestListener", func() error {
l.serviceCancel()
close(l.chStop)
l.shutdownWaitGroup.Wait()
return l.mbOracleEvents.Close()
})
}
// HandleLog implements log.Listener
func (l *DRListener) HandleLog(lb log.Broadcast) {
log := lb.DecodedLog()
if log == nil || reflect.ValueOf(log).IsNil() {
l.logger.Error("HandleLog: ignoring nil value")
return
}
switch log := log.(type) {
case *ocr2dr_oracle.OCR2DROracleOracleRequest, *ocr2dr_oracle.OCR2DROracleOracleResponse, *ocr2dr_oracle.OCR2DROracleUserCallbackError, *ocr2dr_oracle.OCR2DROracleUserCallbackRawError:
wasOverCapacity := l.mbOracleEvents.Deliver(lb)
if wasOverCapacity {
l.logger.Error("OracleRequest log mailbox is over capacity - dropped the oldest log")
}
default:
l.logger.Errorf("Unexpected log type %T", log)
}
}
// JobID() complies with log.Listener
func (l *DRListener) JobID() int32 {
return l.job.ID
}
func (l *DRListener) processOracleEvents() {
defer l.shutdownWaitGroup.Done()
for {
select {
case <-l.chStop:
return
case <-l.mbOracleEvents.Notify():
for {
select {
case <-l.chStop:
return
default:
}
lb, exists := l.mbOracleEvents.Retrieve()
if !exists {
break
}
was, err := l.logBroadcaster.WasAlreadyConsumed(lb)
if err != nil {
l.logger.Errorw("Could not determine if log was already consumed", "error", err)
continue
} else if was {
continue
}
log := lb.DecodedLog()
if log == nil || reflect.ValueOf(log).IsNil() {
l.logger.Error("processOracleEvents: ignoring nil value")
continue
}
switch log := log.(type) {
case *ocr2dr_oracle.OCR2DROracleOracleRequest:
l.shutdownWaitGroup.Add(1)
go l.handleOracleRequest(log, lb)
case *ocr2dr_oracle.OCR2DROracleOracleResponse:
l.shutdownWaitGroup.Add(1)
go l.handleOracleResponse("OracleResponse", log.RequestId, lb)
case *ocr2dr_oracle.OCR2DROracleUserCallbackError:
l.shutdownWaitGroup.Add(1)
go l.handleOracleResponse("UserCallbackError", log.RequestId, lb)
case *ocr2dr_oracle.OCR2DROracleUserCallbackRawError:
l.shutdownWaitGroup.Add(1)
go l.handleOracleResponse("UserCallbackRawError", log.RequestId, lb)
default:
l.logger.Warnf("Unexpected log type %T", log)
}
}
}
}
}
// Process result from the EA saved by a jsonparse pipeline task.
// That value is a valid JSON string so it contains double quote characters.
// Allowed inputs are:
//
// 1. "" (2 characters) -> return empty byte array
// 2. "0x<val>" where <val> is a non-empty, valid hex -> return hex-decoded <val>
func ExtractRawBytes(input []byte) ([]byte, error) {
if len(input) < 2 || input[0] != '"' || input[len(input)-1] != '"' {
return nil, fmt.Errorf("unable to decode input: %v", input)
}
input = input[1 : len(input)-1]
if len(input) == 0 {
return []byte{}, nil
}
if len(input) < 4 || len(input)%2 != 0 {
return nil, fmt.Errorf("input is not a valid, non-empty hex string of even length: %v", input)
}
return utils.TryParseHex(string(input))
}
func (l *DRListener) getNewHandlerContext() (context.Context, context.CancelFunc) {
timeoutSec := l.pluginConfig.ListenerEventHandlerTimeoutSec
if timeoutSec == 0 {
return context.WithCancel(l.serviceContext)
}
return context.WithTimeout(l.serviceContext, time.Duration(timeoutSec)*time.Second)
}
func (l *DRListener) handleOracleRequest(request *ocr2dr_oracle.OCR2DROracleOracleRequest, lb log.Broadcast) {
defer l.shutdownWaitGroup.Done()
l.logger.Infow("Oracle request received",
"requestId", formatRequestId(request.RequestId),
"data", fmt.Sprintf("%0x", request.Data),
)
requestData := make(map[string]interface{})
requestData["requestId"] = formatRequestId(request.RequestId)
requestData["data"] = fmt.Sprintf("0x%x", request.Data)
meta := make(map[string]interface{})
meta["oracleRequest"] = requestData
vars := pipeline.NewVarsFrom(map[string]interface{}{
"jobSpec": map[string]interface{}{
"databaseID": l.job.ID,
"externalJobID": l.job.ExternalJobID,
"name": l.job.Name.ValueOrZero(),
},
"jobRun": map[string]interface{}{
"meta": meta,
"logBlockHash": request.Raw.BlockHash,
"logBlockNumber": request.Raw.BlockNumber,
"logTxHash": request.Raw.TxHash,
"logAddress": request.Raw.Address,
"logTopics": request.Raw.Topics,
"logData": request.Raw.Data,
"blockReceiptsRoot": lb.ReceiptsRoot(),
"blockTransactionsRoot": lb.TransactionsRoot(),
"blockStateRoot": lb.StateRoot(),
},
})
ctx, cancel := l.getNewHandlerContext()
defer cancel()
run := pipeline.NewRun(*l.job.PipelineSpec, vars)
err := l.pluginORM.CreateRequest(request.RequestId, time.Now(), &request.Raw.TxHash, pg.WithParentCtx(ctx))
if err != nil {
l.logger.Errorw("failed to create a DB entry for new request", "requestID", formatRequestId(request.RequestId), "err", err)
return
}
_, err = l.pipelineRunner.Run(ctx, &run, l.logger, true, func(tx pg.Queryer) error {
l.markLogConsumed(lb, pg.WithQueryer(tx))
return nil
})
if err != nil {
l.logger.Errorw("pipeline run failed", "requestID", formatRequestId(request.RequestId), "err", err)
return
}
computationResult, errResult := l.jobORM.FindTaskResultByRunIDAndTaskName(run.ID, ParseResultTaskName, pg.WithParentCtx(ctx))
if errResult != nil {
// Internal problem: Can't find parsed computation results
if err2 := l.pluginORM.SetError(request.RequestId, run.ID, NODE_EXCEPTION, []byte(errResult.Error()), time.Now(), pg.WithParentCtx(ctx)); err2 != nil {
l.logger.Errorw("call to SetError failed", "requestID", formatRequestId(request.RequestId), "err", err2)
}
return
}
computationResult, errResult = ExtractRawBytes(computationResult)
if errResult != nil {
l.logger.Errorw("failed to extract result", "requestID", formatRequestId(request.RequestId), "err", errResult)
return
}
computationError, errErr := l.jobORM.FindTaskResultByRunIDAndTaskName(run.ID, ParseErrorTaskName, pg.WithParentCtx(ctx))
if errErr != nil {
// Internal problem: Can't find parsed computation error
if err2 := l.pluginORM.SetError(request.RequestId, run.ID, NODE_EXCEPTION, []byte(errErr.Error()), time.Now(), pg.WithParentCtx(ctx)); err2 != nil {
l.logger.Errorw("call to SetError failed", "requestID", formatRequestId(request.RequestId), "err", err2)
}
return
}
computationError, errErr = ExtractRawBytes(computationError)
if errErr != nil {
l.logger.Errorw("failed to extract error", "requestID", formatRequestId(request.RequestId), "err", errErr)
return
}
if len(computationError) != 0 {
if err2 := l.pluginORM.SetError(request.RequestId, run.ID, USER_EXCEPTION, computationError, time.Now(), pg.WithParentCtx(ctx)); err2 != nil {
l.logger.Errorw("call to SetError failed", "requestID", formatRequestId(request.RequestId), "err", err2)
}
} else {
if err2 := l.pluginORM.SetResult(request.RequestId, run.ID, computationResult, time.Now(), pg.WithParentCtx(ctx)); err2 != nil {
l.logger.Errorw("call to SetResult failed", "requestID", formatRequestId(request.RequestId), "err", err2)
}
}
}
func (l *DRListener) handleOracleResponse(responseType string, requestID [32]byte, lb log.Broadcast) {
defer l.shutdownWaitGroup.Done()
l.logger.Infow("oracle response received", "type", responseType, "requestID", formatRequestId(requestID))
ctx, cancel := l.getNewHandlerContext()
defer cancel()
if err := l.pluginORM.SetConfirmed(requestID, pg.WithParentCtx(ctx)); err != nil {
l.logger.Errorw("setting CONFIRMED state failed", "requestID", formatRequestId(requestID), "err", err)
}
l.markLogConsumed(lb)
}
func (l *DRListener) markLogConsumed(lb log.Broadcast, qopts ...pg.QOpt) {
if err := l.logBroadcaster.MarkConsumed(lb, qopts...); err != nil {
l.logger.Errorw("Unable to mark log consumed", "err", err, "log", lb.String())
}
}
func (l *DRListener) timeoutRequests() {
defer l.shutdownWaitGroup.Done()
timeoutSec, freqSec, batchSize := l.pluginConfig.RequestTimeoutSec, l.pluginConfig.RequestTimeoutCheckFrequencySec, l.pluginConfig.RequestTimeoutBatchLookupSize
if timeoutSec == 0 || freqSec == 0 || batchSize == 0 {
l.logger.Warn("request timeout checker not configured - disabling it")
return
}
ticker := time.NewTicker(time.Duration(freqSec) * time.Second)
defer ticker.Stop()
for {
select {
case <-l.chStop:
return
case <-ticker.C:
cutoff := time.Now().Add(-(time.Duration(timeoutSec) * time.Second))
ctx, cancel := l.getNewHandlerContext()
ids, err := l.pluginORM.TimeoutExpiredResults(cutoff, batchSize, pg.WithParentCtx(ctx))
cancel()
if err != nil {
l.logger.Errorw("error when calling FindExpiredResults", "err", err)
break
}
if len(ids) > 0 {
var idStrs []string
for _, id := range ids {
idStrs = append(idStrs, formatRequestId(id))
}
l.logger.Debugw("timed out requests", "requestIDs", idStrs)
} else {
l.logger.Debug("no requests to time out")
}
}
}
}