-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathexecution.go
More file actions
383 lines (322 loc) · 10.4 KB
/
execution.go
File metadata and controls
383 lines (322 loc) · 10.4 KB
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
package host
import (
"context"
"encoding/binary"
"fmt"
"sync"
"time"
"github.com/bytecodealliance/wasmtime-go/v28"
"google.golang.org/protobuf/proto"
"github.com/smartcontractkit/chainlink-common/pkg/config"
sdkpb "github.com/smartcontractkit/chainlink-protos/cre/go/sdk"
wfpb "github.com/smartcontractkit/chainlink-protos/workflows/go/v2"
)
type execution[T any] struct {
fetchRequestsCounter int
response T
ctx context.Context
capabilityResponses map[int32]<-chan *sdkpb.CapabilityResponse
secretsResponses map[int32]<-chan *secretsResponse
lock sync.RWMutex
module *module
executor ExecutionHelper
timeFetcher *timeFetcher
baseTime *time.Time
hasRun bool
mode sdkpb.Mode
donSeed int64
nodeSeed int64
donLogCount uint32
nodeLogCount uint32
}
// callCapAsync async calls a capability by placing execution results onto a
// channel and storing each channel with a unique identifier for future
// retrieval on await.
func (e *execution[T]) callCapAsync(ctx context.Context, req *sdkpb.CapabilityRequest) error {
ch := make(chan *sdkpb.CapabilityResponse, 1)
e.lock.Lock()
defer e.lock.Unlock()
e.capabilityResponses[req.CallbackId] = ch
go func() {
resp, err := e.executor.CallCapability(ctx, req)
if err != nil {
resp = &sdkpb.CapabilityResponse{
Response: &sdkpb.CapabilityResponse_Error{
Error: err.Error(),
},
}
}
select {
case <-ctx.Done():
case ch <- resp:
}
}()
return nil
}
func (e *execution[T]) awaitCapabilities(ctx context.Context, acr *sdkpb.AwaitCapabilitiesRequest) (*sdkpb.AwaitCapabilitiesResponse, error) {
responses := make(map[int32]*sdkpb.CapabilityResponse, len(acr.Ids))
e.lock.Lock()
defer e.lock.Unlock()
for _, callId := range acr.Ids {
ch, ok := e.capabilityResponses[callId]
if !ok {
return nil, fmt.Errorf("failed to get call from store : %d", callId)
}
select {
case <-ctx.Done():
return nil, fmt.Errorf("failed to wait for capability response %d : %w", callId, ctx.Err())
case resp := <-ch:
responses[callId] = resp
}
delete(e.capabilityResponses, callId)
}
return &sdkpb.AwaitCapabilitiesResponse{
Responses: responses,
}, nil
}
type secretsResponse struct {
responses []*sdkpb.SecretResponse
err error
}
func (e *execution[T]) getSecretsAsync(ctx context.Context, req *sdkpb.GetSecretsRequest) error {
ch := make(chan *secretsResponse, 1)
e.lock.Lock()
defer e.lock.Unlock()
e.secretsResponses[req.CallbackId] = ch
go func() {
resp, err := e.executor.GetSecrets(ctx, req)
sr := &secretsResponse{responses: resp, err: err}
select {
case <-ctx.Done():
case ch <- sr:
}
}()
return nil
}
func (e *execution[T]) awaitSecrets(ctx context.Context, acr *sdkpb.AwaitSecretsRequest) (*sdkpb.AwaitSecretsResponse, error) {
responses := make(map[int32]*sdkpb.SecretResponses, len(acr.Ids))
e.lock.Lock()
defer e.lock.Unlock()
for _, callId := range acr.Ids {
ch, ok := e.secretsResponses[callId]
if !ok {
return nil, fmt.Errorf("failed to get call from store : %d", callId)
}
select {
case <-ctx.Done():
return nil, fmt.Errorf("failed to wait for capability response %d : %w", callId, ctx.Err())
case resp := <-ch:
if resp.err != nil {
return nil, fmt.Errorf("failed to get secrets for call %d: %w", callId, resp.err)
}
responses[callId] = &sdkpb.SecretResponses{Responses: resp.responses}
}
delete(e.secretsResponses, callId)
}
return &sdkpb.AwaitSecretsResponse{
Responses: responses,
}, nil
}
func (e *execution[T]) log(caller *wasmtime.Caller, ptr int32, ptrlen int32) {
switch e.mode {
case sdkpb.Mode_MODE_DON:
e.donLogCount++
if e.donLogCount == e.module.cfg.MaxLogCountDONMode {
e.module.cfg.Logger.Warnf("max log count for don mode reached: %d - all subsequent logs will be dropped", e.donLogCount)
}
if e.donLogCount > e.module.cfg.MaxLogCountDONMode {
// silently drop to avoid spamming logs
return
}
case sdkpb.Mode_MODE_NODE:
e.nodeLogCount++
if e.nodeLogCount == e.module.cfg.MaxLogCountNodeMode {
e.module.cfg.Logger.Warnf("max log count for node mode reached: %d - all subsequent logs will be dropped", e.nodeLogCount)
}
if e.nodeLogCount > e.module.cfg.MaxLogCountNodeMode {
// silently drop to avoid spamming logs
return
}
default:
// unexpected / malicious
return
}
if ptrlen > int32(e.module.cfg.MaxLogLenBytes) {
e.module.cfg.Logger.Warnf("log message too long: %d - dropping", ptrlen)
return
}
b, innerErr := wasmRead(caller, ptr, ptrlen)
if innerErr != nil {
e.module.cfg.Logger.Errorf("error calling log: %s", innerErr)
return
}
innerErr = e.executor.EmitUserLog(string(b))
if innerErr != nil {
e.module.cfg.Logger.Errorf("error emitting user log: %s", innerErr)
return
}
}
func (e *execution[T]) emitMetric(caller *wasmtime.Caller, ptr int32, ptrlen int32) int32 {
if err := e.module.cfg.EnableUserMetricsLimiter.AllowErr(e.ctx); err != nil {
return -1
}
if ptrlen <= 0 {
return -1
}
if err := e.module.cfg.MaxUserMetricPayloadLimiter.Check(e.ctx, config.Size(ptrlen)); err != nil {
e.module.cfg.Logger.Warnf("metric payload too large: %d bytes - dropping: %s", ptrlen, err)
return -1
}
b, err := wasmRead(caller, ptr, ptrlen)
if err != nil {
e.module.cfg.Logger.Errorf("error reading metric payload: %s", err)
return -1
}
metric := &wfpb.WorkflowUserMetric{}
if err := proto.Unmarshal(b, metric); err != nil {
e.module.cfg.Logger.Errorf("error unmarshaling metric: %s", err)
return -1
}
if metric.Name == "" {
e.module.cfg.Logger.Warnf("metric name cannot be empty - dropping")
return -1
}
if err := e.module.cfg.MaxUserMetricNameLengthLimiter.Check(e.ctx, len(metric.Name)); err != nil {
e.module.cfg.Logger.Warnf("metric name too long: %d chars - dropping: %s", len(metric.Name), err)
return -1
}
if err := e.module.cfg.MaxUserMetricLabelsPerMetricLimiter.Check(e.ctx, len(metric.Labels)); err != nil {
e.module.cfg.Logger.Warnf("too many labels on metric %q: %d - dropping: %s", metric.Name, len(metric.Labels), err)
return -1
}
for k, v := range metric.Labels {
if err := e.module.cfg.MaxUserMetricLabelValueLengthLimiter.Check(e.ctx, len(v)); err != nil {
e.module.cfg.Logger.Warnf("label value too long for key %q on metric %q: %d chars - dropping: %s", k, metric.Name, len(v), err)
return -1
}
}
if err := e.executor.EmitUserMetric(e.ctx, metric); err != nil {
e.module.cfg.Logger.Errorf("error emitting user metric: %s", err)
return -1
}
return 0
}
func (e *execution[T]) getSeed(mode int32) int64 {
switch sdkpb.Mode(mode) {
case sdkpb.Mode_MODE_DON:
return e.donSeed
case sdkpb.Mode_MODE_NODE:
return e.nodeSeed
}
return -1
}
func (e *execution[T]) switchModes(_ *wasmtime.Caller, mode int32) {
e.hasRun = true
e.mode = sdkpb.Mode(mode)
}
// clockTimeGet is the default time.Now() which is also called by Go many times.
// This implementation uses Node Mode to not have to wait for OCR rounds.
func (e *execution[T]) clockTimeGet(caller *wasmtime.Caller, id int32, precision int64, resultTimestamp int32) int32 {
donTime, err := e.timeFetcher.GetTime(sdkpb.Mode_MODE_NODE)
if err != nil {
return ErrnoInval
}
if e.baseTime == nil {
// baseTime must be before the first poll or Go panics
t := donTime.Add(-time.Nanosecond)
e.baseTime = &t
}
var val int64
switch id {
case clockIDMonotonic:
val = donTime.Sub(*e.baseTime).Nanoseconds()
case clockIDRealtime:
val = donTime.UnixNano()
default:
return ErrnoInval
}
uint64Size := int32(8)
trg := make([]byte, uint64Size)
binary.LittleEndian.PutUint64(trg, uint64(val))
wasmWrite(caller, trg, resultTimestamp, uint64Size)
return ErrnoSuccess
}
// now is used by rawsdk for Workflows and should be called instead of Go's time.Now().
func (e *execution[T]) now(caller *wasmtime.Caller, resultTimestamp int32) int32 {
donTime, err := e.timeFetcher.GetTime(e.mode)
if err != nil {
return ErrnoInval
}
val := donTime.UnixNano()
uint64Size := int32(8)
trg := make([]byte, uint64Size)
binary.LittleEndian.PutUint64(trg, uint64(val))
wasmWrite(caller, trg, resultTimestamp, uint64Size)
return ErrnoSuccess
}
// Loosely based off the implementation here:
// https://github.com/tetratelabs/wazero/blob/main/imports/wasi_snapshot_preview1/poll.go#L52
// For an overview of the spec, including the datatypes being referred to, see:
// https://github.com/WebAssembly/WASI/blob/snapshot-01/phases/snapshot/docs.md
// This implementation only responds to clock events, not to file descriptor notifications.
// It sleeps based on the largest timeout
func (e *execution[T]) pollOneoff(caller *wasmtime.Caller, subscriptionptr int32, eventsptr int32, nsubscriptions int32, resultNevents int32) int32 {
if nsubscriptions == 0 {
return ErrnoInval
}
subs, err := wasmRead(caller, subscriptionptr, nsubscriptions*subscriptionLen)
if err != nil {
return ErrnoFault
}
events := make([]byte, nsubscriptions*eventsLen)
timeout := time.Duration(0)
for i := range nsubscriptions {
inOffset := i * subscriptionLen
userData := subs[inOffset : inOffset+8]
eventType := subs[inOffset+8]
argBuf := subs[inOffset+8+8:]
slot, err := getSlot(events, i)
if err != nil {
return ErrnoFault
}
switch eventType {
case eventTypeClock:
newTimeout := binary.LittleEndian.Uint64(argBuf[8:16])
flag := binary.LittleEndian.Uint16(argBuf[24:32])
var errno Errno
switch flag {
case 0: // relative
errno = ErrnoSuccess
if timeout < time.Duration(newTimeout) {
timeout = time.Duration(newTimeout)
}
default:
errno = ErrnoNotsup
}
writeEvent(slot, userData, errno, eventTypeClock)
case eventTypeFDRead, eventTypeFDWrite:
writeEvent(slot, userData, ErrnoBadf, int(eventType))
default:
writeEvent(slot, userData, ErrnoInval, int(eventType))
}
}
if timeout > 0 {
select {
case <-time.After(timeout):
case <-e.ctx.Done():
// If context was cancelled, there will be a trap from the engine
// which will halt execution, therefore the return value isn't read
return 0
}
}
uint32Size := int32(4)
rne := make([]byte, uint32Size)
binary.LittleEndian.PutUint32(rne, uint32(nsubscriptions))
if wasmWrite(caller, rne, resultNevents, uint32Size) == -1 {
return ErrnoFault
}
if wasmWrite(caller, events, eventsptr, nsubscriptions*eventsLen) == -1 {
return ErrnoFault
}
return ErrnoSuccess
}