-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathmodule.go
More file actions
1324 lines (1118 loc) · 39.4 KB
/
module.go
File metadata and controls
1324 lines (1118 loc) · 39.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
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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package host
import (
"bytes"
"context"
"encoding/base64"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"hash/fnv"
"io"
"math"
"math/rand"
"regexp"
"strings"
"sync"
"time"
"github.com/andybalholm/brotli"
"github.com/bytecodealliance/wasmtime-go/v28"
"google.golang.org/protobuf/proto"
"github.com/smartcontractkit/chainlink-common/pkg/config"
"github.com/smartcontractkit/chainlink-common/pkg/custmsg"
"github.com/smartcontractkit/chainlink-common/pkg/logger"
"github.com/smartcontractkit/chainlink-common/pkg/settings"
"github.com/smartcontractkit/chainlink-common/pkg/settings/limits"
dagsdk "github.com/smartcontractkit/chainlink-common/pkg/workflows/sdk"
"github.com/smartcontractkit/chainlink-common/pkg/workflows/wasm"
wasmdagpb "github.com/smartcontractkit/chainlink-common/pkg/workflows/wasm/pb"
sdkpb "github.com/smartcontractkit/chainlink-protos/cre/go/sdk"
"github.com/smartcontractkit/chainlink-protos/cre/go/values"
wfpb "github.com/smartcontractkit/chainlink-protos/workflows/go/v2"
)
const v2ImportPrefix = "version_v2"
var (
defaultTickInterval = 100 * time.Millisecond
defaultTimeout = 10 * time.Minute
defaultMinMemoryMBs = uint64(128)
DefaultInitialFuel = uint64(100_000_000)
defaultMaxFetchRequests = 5
defaultMaxCompressedBinarySize = 20 * 1024 * 1024 // 20 MB
defaultMaxDecompressedBinarySize = 100 * 1024 * 1024 // 100 MB
defaultMaxResponseSizeBytes = 5 * 1024 * 1024 // 5 MB
defaultMaxLogLenBytes = 1024 * 1024 // 1 MB
defaultMaxLogCountDONMode = 10_000
defaultMaxLogCountNodeMode = 10_000
ResponseBufferTooSmall = "response buffer too small"
defaultMaxUserMetricPayloadBytes = uint32(4096) // 4 KB
defaultMaxUserMetricNameLength = uint32(128)
defaultMaxUserMetricLabelsPerMetric = uint32(10)
defaultMaxUserMetricLabelValueLength = uint32(256)
)
type DeterminismConfig struct {
// Seed is the seed used to generate cryptographically insecure random numbers in the module.
Seed int64
}
type ModuleConfig struct {
TickInterval time.Duration
Timeout *time.Duration
MaxMemoryMBs uint64
MinMemoryMBs uint64
MemoryLimiter limits.BoundLimiter[config.Size] // supersedes Max/MinMemoryMBs if set
InitialFuel uint64
Logger logger.Logger
IsUncompressed bool
Fetch func(ctx context.Context, req *FetchRequest) (*FetchResponse, error)
MaxFetchRequests int
MaxCompressedBinarySize uint64
MaxCompressedBinaryLimiter limits.BoundLimiter[config.Size] // supersedes MaxCompressedBinarySize if set
MaxDecompressedBinarySize uint64
MaxDecompressedBinaryLimiter limits.BoundLimiter[config.Size] // supersedes MaxDecompressedBinarySize if set
MaxResponseSizeBytes uint64
MaxResponseSizeLimiter limits.BoundLimiter[config.Size] // supersedes MaxResponseSizeBytes if set
MaxLogLenBytes uint32
MaxLogCountDONMode uint32
MaxLogCountNodeMode uint32
EnableUserMetricsLimiter limits.GateLimiter
MaxUserMetricPayloadBytes uint32
MaxUserMetricPayloadLimiter limits.BoundLimiter[config.Size] // supersedes MaxUserMetricPayloadBytes if set
MaxUserMetricNameLength uint32
MaxUserMetricNameLengthLimiter limits.BoundLimiter[int] // supersedes MaxUserMetricNameLength if set
MaxUserMetricLabelsPerMetric uint32
MaxUserMetricLabelsPerMetricLimiter limits.BoundLimiter[int] // supersedes MaxUserMetricLabelsPerMetric if set
MaxUserMetricLabelValueLength uint32
MaxUserMetricLabelValueLengthLimiter limits.BoundLimiter[int] // supersedes MaxUserMetricLabelValueLength if set
// Labeler is used to emit messages from the module.
Labeler custmsg.MessageEmitter
// SdkLabeler is called with the discovered v2 import name after module creation.
// If nil, it defaults to a no-op. Used to add metrics labels (e.g. sdk=name).
SdkLabeler func(string)
// If Determinism is set, the module will override the random_get function in the WASI API with
// the provided seed to ensure deterministic behavior.
Determinism *DeterminismConfig
}
type ModuleBase interface {
Start()
Close()
IsLegacyDAG() bool
}
type ModuleV1 interface {
ModuleBase
// V1/Legacy API - request either the Workflow Spec or Custom-Compute execution
Run(ctx context.Context, request *wasmdagpb.Request) (*wasmdagpb.Response, error)
}
type ModuleV2 interface {
ModuleBase
// V2/"NoDAG" API - request either the list of Trigger Subscriptions or launch workflow execution
Execute(ctx context.Context, request *sdkpb.ExecuteRequest, handler ExecutionHelper) (*sdkpb.ExecutionResult, error)
}
// ExecutionHelper Implemented by those running the host, for example the Workflow Engine
type ExecutionHelper interface {
// CallCapability blocking call to the Workflow Engine
CallCapability(ctx context.Context, request *sdkpb.CapabilityRequest) (*sdkpb.CapabilityResponse, error)
GetSecrets(ctx context.Context, request *sdkpb.GetSecretsRequest) ([]*sdkpb.SecretResponse, error)
GetWorkflowExecutionID() string
GetNodeTime() time.Time
GetDONTime() (time.Time, error)
EmitUserLog(log string) error
EmitUserMetric(ctx context.Context, metric *wfpb.WorkflowUserMetric) error
}
type module struct {
engine *wasmtime.Engine
module *wasmtime.Module
wconfig *wasmtime.Config
cfg *ModuleConfig
wg sync.WaitGroup
stopCh chan struct{}
v2ImportName string
}
var _ ModuleV1 = (*module)(nil)
type linkFn[T any] func(m *module, store *wasmtime.Store, exec *execution[T]) (*wasmtime.Instance, error)
// WithDeterminism sets the Determinism field to a deterministic seed from a known time.
//
// "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks"
func WithDeterminism() func(*ModuleConfig) {
return func(cfg *ModuleConfig) {
t, err := time.Parse(time.RFC3339Nano, "2009-01-03T00:00:00Z")
if err != nil {
panic(err)
}
cfg.Determinism = &DeterminismConfig{Seed: t.Unix()}
}
}
func NewModule(ctx context.Context, modCfg *ModuleConfig, binary []byte, opts ...func(*ModuleConfig)) (*module, error) {
// Apply options to the module config.
for _, opt := range opts {
opt(modCfg)
}
if modCfg.Logger == nil {
return nil, errors.New("must provide logger")
}
if modCfg.Fetch == nil {
modCfg.Fetch = func(context.Context, *FetchRequest) (*FetchResponse, error) {
return nil, fmt.Errorf("fetch not implemented")
}
}
if modCfg.MaxFetchRequests == 0 {
modCfg.MaxFetchRequests = defaultMaxFetchRequests
}
if modCfg.Labeler == nil {
modCfg.Labeler = &unimplementedMessageEmitter{}
}
if modCfg.SdkLabeler == nil {
modCfg.SdkLabeler = func(string) {}
}
if modCfg.TickInterval == 0 {
modCfg.TickInterval = defaultTickInterval
}
if modCfg.Timeout == nil {
modCfg.Timeout = &defaultTimeout
}
if modCfg.MinMemoryMBs == 0 {
modCfg.MinMemoryMBs = defaultMinMemoryMBs
}
if modCfg.MaxCompressedBinarySize == 0 {
modCfg.MaxCompressedBinarySize = uint64(defaultMaxCompressedBinarySize)
}
if modCfg.MaxDecompressedBinarySize == 0 {
modCfg.MaxDecompressedBinarySize = uint64(defaultMaxDecompressedBinarySize)
}
if modCfg.MaxResponseSizeBytes == 0 {
modCfg.MaxResponseSizeBytes = uint64(defaultMaxResponseSizeBytes)
}
if modCfg.MaxLogLenBytes == 0 {
modCfg.MaxLogLenBytes = uint32(defaultMaxLogLenBytes)
}
if modCfg.MaxLogCountDONMode == 0 {
modCfg.MaxLogCountDONMode = uint32(defaultMaxLogCountDONMode)
}
if modCfg.MaxLogCountNodeMode == 0 {
modCfg.MaxLogCountNodeMode = uint32(defaultMaxLogCountNodeMode)
}
if modCfg.MaxUserMetricPayloadBytes == 0 {
modCfg.MaxUserMetricPayloadBytes = defaultMaxUserMetricPayloadBytes
}
if modCfg.MaxUserMetricNameLength == 0 {
modCfg.MaxUserMetricNameLength = defaultMaxUserMetricNameLength
}
if modCfg.MaxUserMetricLabelsPerMetric == 0 {
modCfg.MaxUserMetricLabelsPerMetric = defaultMaxUserMetricLabelsPerMetric
}
if modCfg.MaxUserMetricLabelValueLength == 0 {
modCfg.MaxUserMetricLabelValueLength = defaultMaxUserMetricLabelValueLength
}
lf := limits.Factory{Logger: modCfg.Logger}
if modCfg.EnableUserMetricsLimiter == nil {
modCfg.EnableUserMetricsLimiter = limits.NewGateLimiter(false)
}
if modCfg.MaxUserMetricPayloadLimiter == nil {
limit := settings.Size(config.Size(modCfg.MaxUserMetricPayloadBytes))
var err error
modCfg.MaxUserMetricPayloadLimiter, err = limits.MakeUpperBoundLimiter(lf, limit)
if err != nil {
return nil, fmt.Errorf("failed to make metric payload size limiter: %w", err)
}
}
if modCfg.MaxUserMetricNameLengthLimiter == nil {
limit := settings.Int(int(modCfg.MaxUserMetricNameLength))
var err error
modCfg.MaxUserMetricNameLengthLimiter, err = limits.MakeUpperBoundLimiter(lf, limit)
if err != nil {
return nil, fmt.Errorf("failed to make metric name length limiter: %w", err)
}
}
if modCfg.MaxUserMetricLabelsPerMetricLimiter == nil {
limit := settings.Int(int(modCfg.MaxUserMetricLabelsPerMetric))
var err error
modCfg.MaxUserMetricLabelsPerMetricLimiter, err = limits.MakeUpperBoundLimiter(lf, limit)
if err != nil {
return nil, fmt.Errorf("failed to make labels per metric limiter: %w", err)
}
}
if modCfg.MaxUserMetricLabelValueLengthLimiter == nil {
limit := settings.Int(int(modCfg.MaxUserMetricLabelValueLength))
var err error
modCfg.MaxUserMetricLabelValueLengthLimiter, err = limits.MakeUpperBoundLimiter(lf, limit)
if err != nil {
return nil, fmt.Errorf("failed to make label value length limiter: %w", err)
}
}
if modCfg.MemoryLimiter == nil {
// Take the max of the min and the configured max memory mbs.
// We do this because Go requires a minimum of 16 megabytes to run,
// and local testing has shown that with less than the min, some
// binaries may error sporadically.
modCfg.MaxMemoryMBs = uint64(math.Max(float64(modCfg.MinMemoryMBs), float64(modCfg.MaxMemoryMBs)))
limit := settings.Size(config.Size(modCfg.MaxMemoryMBs) * config.MByte)
var err error
modCfg.MemoryLimiter, err = limits.MakeUpperBoundLimiter(lf, limit)
if err != nil {
return nil, fmt.Errorf("failed to make memory limiter: %w", err)
}
}
if modCfg.MaxCompressedBinaryLimiter == nil {
limit := settings.Size(config.Size(modCfg.MaxCompressedBinarySize))
var err error
modCfg.MaxCompressedBinaryLimiter, err = limits.MakeUpperBoundLimiter(lf, limit)
if err != nil {
return nil, fmt.Errorf("failed to make compressed binary size limiter: %w", err)
}
}
if modCfg.MaxDecompressedBinaryLimiter == nil {
limit := settings.Size(config.Size(modCfg.MaxDecompressedBinarySize))
var err error
modCfg.MaxDecompressedBinaryLimiter, err = limits.MakeUpperBoundLimiter(lf, limit)
if err != nil {
return nil, fmt.Errorf("failed to make decompressed binary size limiter: %w", err)
}
}
if modCfg.MaxResponseSizeLimiter == nil {
limit := settings.Size(config.Size(modCfg.MaxResponseSizeBytes))
var err error
modCfg.MaxResponseSizeLimiter, err = limits.MakeUpperBoundLimiter(lf, limit)
if err != nil {
return nil, fmt.Errorf("failed to make response size limiter: %w", err)
}
}
if !modCfg.IsUncompressed {
// validate the binary size before decompressing
// this is to prevent decompression bombs
if err := modCfg.MaxCompressedBinaryLimiter.Check(ctx, config.SizeOf(binary)); err != nil {
if errors.Is(err, limits.ErrorBoundLimited[config.Size]{}) {
return nil, fmt.Errorf("compressed binary size exceeds the maximum allowed size: %w", err)
}
return nil, fmt.Errorf("failed to check compressed binary size limit: %w", err)
}
maxDecompressedBinarySize, err := modCfg.MaxDecompressedBinaryLimiter.Limit(ctx)
if err != nil {
return nil, fmt.Errorf("failed to get decompressed binary size limit: %w", err)
}
rdr := io.LimitReader(brotli.NewReader(bytes.NewBuffer(binary)), int64(maxDecompressedBinarySize+1))
decompedBinary, err := io.ReadAll(rdr)
if err != nil {
return nil, fmt.Errorf("failed to decompress binary: %w", err)
}
binary = decompedBinary
}
// Validate the decompressed binary size.
// io.LimitReader prevents decompression bombs by reading up to a set limit, but it will not return an error if the limit is reached.
// The Read() method will return io.EOF, and ReadAll will gracefully handle it and return nil.
if err := modCfg.MaxDecompressedBinaryLimiter.Check(ctx, config.SizeOf(binary)); err != nil {
if errors.Is(err, limits.ErrorBoundLimited[config.Size]{}) {
return nil, fmt.Errorf("decompressed binary size reached the maximum allowed size: %w", err)
}
return nil, fmt.Errorf("failed to check decompressed binary size limit: %w", err)
}
return newModule(modCfg, binary)
}
func newModule(modCfg *ModuleConfig, binary []byte) (*module, error) {
cfg := wasmtime.NewConfig()
cfg.SetEpochInterruption(true)
if modCfg.InitialFuel > 0 {
cfg.SetConsumeFuel(true)
}
cfg.CacheConfigLoadDefault()
cfg.SetCraneliftOptLevel(wasmtime.OptLevelSpeedAndSize)
SetUnwinding(cfg) // Handled differenty based on host OS.
engine := wasmtime.NewEngineWithConfig(cfg)
mod, err := wasmtime.NewModule(engine, binary)
if err != nil {
return nil, fmt.Errorf("error creating wasmtime module: %w", err)
}
v2ImportName := ""
for _, modImport := range mod.Imports() {
name := modImport.Name()
if modImport.Module() == "env" && name != nil && strings.HasPrefix(*name, v2ImportPrefix) {
v2ImportName = *name
break
}
}
modCfg.SdkLabeler(v2ImportName)
return &module{
engine: engine,
module: mod,
wconfig: cfg,
cfg: modCfg,
stopCh: make(chan struct{}),
v2ImportName: v2ImportName,
}, nil
}
func linkNoDAG(m *module, store *wasmtime.Store, exec *execution[*sdkpb.ExecutionResult]) (*wasmtime.Instance, error) {
linker, err := newWasiLinker(exec, m.engine)
if err != nil {
return nil, err
}
if err = linker.FuncWrap(
"env",
m.v2ImportName,
func(caller *wasmtime.Caller) {}); err != nil {
return nil, fmt.Errorf("error wrapping log func: %w", err)
}
logger := m.cfg.Logger
if err = linker.FuncWrap(
"env",
"send_response",
createSendResponseFn(logger, exec, func() *sdkpb.ExecutionResult {
return &sdkpb.ExecutionResult{}
}),
); err != nil {
return nil, fmt.Errorf("error wrapping sendResponse func: %w", err)
}
if err = linker.FuncWrap(
"env",
"call_capability",
createCallCapFn(logger, exec),
); err != nil {
return nil, fmt.Errorf("error wrapping callcap func: %w", err)
}
if err = linker.FuncWrap(
"env",
"await_capabilities",
createAwaitCapsFn(logger, exec),
); err != nil {
return nil, fmt.Errorf("error wrapping awaitcaps func: %w", err)
}
if err = linker.FuncWrap(
"env",
"get_secrets",
createGetSecretsFn(logger, exec),
); err != nil {
return nil, fmt.Errorf("error wrapping get_secrets func: %w", err)
}
if err = linker.FuncWrap(
"env",
"await_secrets",
createAwaitSecretsFn(logger, exec),
); err != nil {
return nil, fmt.Errorf("error wrapping await_secrets func: %w", err)
}
if err := linker.FuncWrap(
"env",
"log",
exec.log,
); err != nil {
return nil, fmt.Errorf("error wrapping log func: %w", err)
}
if err := linker.FuncWrap(
"env",
"emit_metric",
exec.emitMetric,
); err != nil {
return nil, fmt.Errorf("error wrapping emit_metric func: %w", err)
}
if err = linker.FuncWrap(
"env",
"switch_modes",
exec.switchModes); err != nil {
return nil, fmt.Errorf("error wrapping switchModes func: %w", err)
}
if err = linker.FuncWrap(
"env",
"random_seed",
exec.getSeed); err != nil {
return nil, fmt.Errorf("error wrapping getSeed func: %w", err)
}
if err = linker.FuncWrap(
"env",
"now",
exec.now); err != nil {
return nil, fmt.Errorf("error wrapping get_time func: %w", err)
}
return linker.Instantiate(store, m.module)
}
func linkLegacyDAG(m *module, store *wasmtime.Store, exec *execution[*wasmdagpb.Response]) (*wasmtime.Instance, error) {
linker, err := newDagWasiLinker(m.cfg, m.engine)
if err != nil {
return nil, err
}
logger := m.cfg.Logger
if err = linker.FuncWrap(
"env",
"sendResponse",
createSendResponseFn(logger, exec, func() *wasmdagpb.Response {
return &wasmdagpb.Response{}
}),
); err != nil {
return nil, fmt.Errorf("error wrapping sendResponse func: %w", err)
}
err = linker.FuncWrap(
"env",
"fetch",
createFetchFn(logger, wasmRead, wasmWrite, wasmWriteUInt32, m.cfg, exec),
)
if err != nil {
return nil, fmt.Errorf("error wrapping fetch func: %w", err)
}
err = linker.FuncWrap(
"env",
"emit",
createEmitFn(logger, exec, m.cfg.Labeler, wasmRead, wasmWrite, wasmWriteUInt32),
)
if err != nil {
return nil, fmt.Errorf("error wrapping emit func: %w", err)
}
if err := linker.FuncWrap(
"env",
"log",
createLogFn(logger),
); err != nil {
return nil, fmt.Errorf("error wrapping log func: %w", err)
}
return linker.Instantiate(store, m.module)
}
func (m *module) Start() {
m.wg.Go(func() {
ticker := time.NewTicker(m.cfg.TickInterval)
for {
select {
case <-m.stopCh:
return
case <-ticker.C:
m.engine.IncrementEpoch()
}
}
})
}
func (m *module) Close() {
close(m.stopCh)
m.wg.Wait()
m.engine.Close()
m.module.Close()
m.wconfig.Close()
}
func (m *module) IsLegacyDAG() bool {
return m.v2ImportName == ""
}
func (m *module) Execute(ctx context.Context, req *sdkpb.ExecuteRequest, executor ExecutionHelper) (*sdkpb.ExecutionResult, error) {
if m.IsLegacyDAG() {
return nil, errors.New("cannot execute a legacy dag workflow")
}
if executor == nil {
return nil, fmt.Errorf("invalid capability executor: can't be nil")
}
if req == nil {
return nil, fmt.Errorf("invalid request: can't be nil")
}
setMaxResponseSize := func(r *sdkpb.ExecuteRequest, maxSize uint64) {
r.MaxResponseSize = maxSize
}
return runWasm(ctx, m, req, setMaxResponseSize, linkNoDAG, executor)
}
// Run is deprecated, use execute instead
func (m *module) Run(ctx context.Context, request *wasmdagpb.Request) (*wasmdagpb.Response, error) {
if request == nil {
return nil, fmt.Errorf("invalid request: can't be nil")
}
if request.Id == "" {
return nil, fmt.Errorf("invalid request: can't be empty")
}
if !m.IsLegacyDAG() {
return nil, errors.New("cannot use Run on a non-legacy dag workflow, use Execute instead")
}
setMaxResponseSize := func(r *wasmdagpb.Request, maxSize uint64) {
computeRequest := r.GetComputeRequest()
if computeRequest != nil {
computeRequest.RuntimeConfig = &wasmdagpb.RuntimeConfig{
MaxResponseSizeBytes: int64(maxSize),
}
}
}
return runWasm(ctx, m, request, setMaxResponseSize, linkLegacyDAG, nil)
}
func runWasm[I, O proto.Message](
ctx context.Context,
m *module,
request I,
setMaxResponseSize func(i I, maxSize uint64),
linkWasm linkFn[O],
helper ExecutionHelper) (O, error) {
var o O
ctxWithTimeout, cancel := context.WithTimeout(ctx, *m.cfg.Timeout)
defer cancel()
store := wasmtime.NewStore(m.engine)
defer store.Close()
maxResponseSizeBytes, err := m.cfg.MaxResponseSizeLimiter.Limit(ctx)
if err != nil {
return o, fmt.Errorf("failed to get response size limit: %w", err)
}
setMaxResponseSize(request, uint64(maxResponseSizeBytes))
reqpb, err := proto.Marshal(request)
if err != nil {
return o, err
}
reqstr := base64.StdEncoding.EncodeToString(reqpb)
wasi := wasmtime.NewWasiConfig()
wasi.InheritStdout()
defer wasi.Close()
wasi.SetArgv([]string{"wasi", reqstr})
store.SetWasi(wasi)
if m.cfg.InitialFuel > 0 {
err = store.SetFuel(m.cfg.InitialFuel)
if err != nil {
return o, fmt.Errorf("error setting fuel: %w", err)
}
}
// Limit memory to max memory megabytes per instance.
maxMemoryBytes, err := m.cfg.MemoryLimiter.Limit(ctx)
if err != nil {
return o, fmt.Errorf("failed to get memory limit: %w", err)
}
store.Limiter(
int64(maxMemoryBytes/config.MByte)*int64(math.Pow(10, 6)),
-1, // tableElements, -1 == default
1, // instances
1, // tables
1, // memories
)
deadline := *m.cfg.Timeout / m.cfg.TickInterval
store.SetEpochDeadline(uint64(deadline))
h := fnv.New64a()
if helper != nil {
executionId := helper.GetWorkflowExecutionID()
_, _ = h.Write([]byte(executionId))
}
donSeed := int64(h.Sum64())
exec := &execution[O]{
ctx: ctxWithTimeout,
capabilityResponses: map[int32]<-chan *sdkpb.CapabilityResponse{},
secretsResponses: map[int32]<-chan *secretsResponse{},
module: m,
executor: helper,
donSeed: donSeed,
nodeSeed: int64(rand.Uint64()),
}
instance, err := linkWasm(m, store, exec)
if err != nil {
return o, fmt.Errorf("error linking wasm: %w", err)
}
start := instance.GetFunc(store, "_start")
if start == nil {
return o, errors.New("could not get start function")
}
startTime := time.Now()
_, err = start.Call(store)
executionDuration := time.Since(startTime)
// The error codes below are only returned by the v1 legacy DAG workflow.
switch {
case containsCode(err, wasm.CodeSuccess):
if any(exec.response) == nil {
return o, errors.New("could not find response for execution")
}
return exec.response, nil
case containsCode(err, wasm.CodeInvalidResponse):
return o, fmt.Errorf("invariant violation: error marshaling response")
case containsCode(err, wasm.CodeInvalidRequest):
return o, fmt.Errorf("invariant violation: invalid request to runner")
case containsCode(err, wasm.CodeRunnerErr):
// legacy DAG captured all errors, since the function didn't return an error
resp, ok := any(exec).(*execution[*wasmdagpb.Response])
if ok && resp.response != nil {
return o, fmt.Errorf("error executing runner: %s: %w", resp.response.ErrMsg, err)
}
return o, fmt.Errorf("error executing runner")
case containsCode(err, wasm.CodeHostErr):
return o, fmt.Errorf("invariant violation: host errored during sendResponse")
}
// If an error has occurred and the deadline has been reached or exceeded, return a deadline exceeded error.
// Note - there is no other reliable signal on the error that can be used to infer it is due to epoch deadline
// being reached, so if an error is returned after the deadline it is assumed it is due to that and return
// context.DeadlineExceeded.
if err != nil && executionDuration >= *m.cfg.Timeout-m.cfg.TickInterval { // As start could be called just before epoch update 1 tick interval is deducted to account for this
m.cfg.Logger.Errorw("start function returned error after deadline reached, returning deadline exceeded error", "errFromStartFunction", err)
return o, context.DeadlineExceeded
}
return o, err
}
func containsCode(err error, code int) bool {
if err == nil {
return false
}
return strings.Contains(err.Error(), fmt.Sprintf("exit status %d", code))
}
// createSendResponseFn injects the dependency required by a WASM guest to
// send a response back to the host.
func createSendResponseFn[T proto.Message](
logger logger.Logger,
exec *execution[T],
newT func() T) func(caller *wasmtime.Caller, ptr int32, ptrlen int32) int32 {
return func(caller *wasmtime.Caller, ptr int32, ptrlen int32) int32 {
b, innerErr := wasmRead(caller, ptr, ptrlen)
if innerErr != nil {
logger.Errorf("error calling sendResponse: %s", innerErr)
return ErrnoFault
}
resp := newT()
innerErr = proto.Unmarshal(b, resp)
if innerErr != nil {
logger.Errorf("error calling sendResponse: %s", innerErr)
return ErrnoFault
}
exec.lock.Lock()
exec.response = resp
exec.lock.Unlock()
return ErrnoSuccess
}
}
func toSdkReq(req *wasmdagpb.FetchRequest) *FetchRequest {
h := map[string]string{}
for k, v := range req.Headers.GetFields() {
h[k] = v.GetStringValue()
}
md := FetchRequestMetadata{}
if req.Metadata != nil {
md = FetchRequestMetadata{
WorkflowID: req.Metadata.WorkflowId,
WorkflowName: req.Metadata.WorkflowName,
WorkflowOwner: req.Metadata.WorkflowOwner,
WorkflowExecutionID: req.Metadata.WorkflowExecutionId,
DecodedWorkflowName: req.Metadata.DecodedWorkflowName,
}
}
return &FetchRequest{
FetchRequest: dagsdk.FetchRequest{
URL: req.Url,
Method: req.Method,
Headers: h,
Body: req.Body,
TimeoutMs: req.TimeoutMs,
MaxRetries: req.MaxRetries,
},
Metadata: md,
}
}
func fromSdkResp(resp *dagsdk.FetchResponse) (*wasmdagpb.FetchResponse, error) {
h := map[string]any{}
if resp.Headers != nil {
for k, v := range resp.Headers {
h[k] = v
}
}
m, err := values.WrapMap(h)
if err != nil {
return nil, err
}
return &wasmdagpb.FetchResponse{
ExecutionError: resp.ExecutionError,
ErrorMessage: resp.ErrorMessage,
StatusCode: resp.StatusCode,
Headers: values.ProtoMap(m),
Body: resp.Body,
}, nil
}
type FetchRequestMetadata struct {
WorkflowID string
WorkflowName string
WorkflowOwner string
WorkflowExecutionID string
DecodedWorkflowName string
}
type FetchRequest struct {
dagsdk.FetchRequest
Metadata FetchRequestMetadata
}
// Use an alias here to allow extending the FetchResponse with additional
// metadata in the future, as with the FetchRequest above.
type FetchResponse = dagsdk.FetchResponse
func createFetchFn(
logger logger.Logger,
reader unsafeReaderFunc,
writer unsafeWriterFunc,
sizeWriter unsafeFixedLengthWriterFunc,
modCfg *ModuleConfig,
exec *execution[*wasmdagpb.Response],
) func(caller *wasmtime.Caller, respptr int32, resplenptr int32, reqptr int32, reqptrlen int32) int32 {
return func(caller *wasmtime.Caller, respptr int32, resplenptr int32, reqptr int32, reqptrlen int32) int32 {
const errFetchSfx = "error calling fetch"
// writeErr marshals and writes an error response to wasm
writeErr := func(err error) int32 {
resp := &wasmdagpb.FetchResponse{
ExecutionError: true,
ErrorMessage: err.Error(),
}
respBytes, perr := proto.Marshal(resp)
if perr != nil {
logger.Errorf("%s: %s", errFetchSfx, perr)
return ErrnoFault
}
if size := writer(caller, respBytes, respptr, int32(len(respBytes))); size == -1 {
logger.Errorf("%s: %s", errFetchSfx, errors.New("failed to write error response"))
return ErrnoFault
}
if size := sizeWriter(caller, resplenptr, uint32(len(respBytes))); size == -1 {
logger.Errorf("%s: %s", errFetchSfx, errors.New("failed to write error response length"))
return ErrnoFault
}
return ErrnoSuccess
}
b, innerErr := reader(caller, reqptr, reqptrlen)
if innerErr != nil {
logger.Errorf("%s: %s", errFetchSfx, innerErr)
return writeErr(innerErr)
}
req := &wasmdagpb.FetchRequest{}
innerErr = proto.Unmarshal(b, req)
if innerErr != nil {
logger.Errorf("%s: %s", errFetchSfx, innerErr)
return writeErr(innerErr)
}
// limit the number of fetch calls we can make per request
if exec.fetchRequestsCounter >= modCfg.MaxFetchRequests {
logger.Errorf("%s: max number of fetch request %d exceeded", errFetchSfx, modCfg.MaxFetchRequests)
return writeErr(errors.New("max number of fetch requests exceeded"))
}
exec.fetchRequestsCounter++
fetchResp, innerErr := modCfg.Fetch(exec.ctx, toSdkReq(req))
if innerErr != nil {
logger.Errorf("%s: %s", errFetchSfx, innerErr)
return writeErr(innerErr)
}
protoResp, innerErr := fromSdkResp(fetchResp)
if innerErr != nil {
logger.Errorf("%s: %s", errFetchSfx, innerErr)
return writeErr(innerErr)
}
// convert struct to proto
respBytes, innerErr := proto.Marshal(protoResp)
if innerErr != nil {
logger.Errorf("%s: %s", errFetchSfx, innerErr)
return writeErr(innerErr)
}
if size := writer(caller, respBytes, respptr, int32(len(respBytes))); size == -1 {
return writeErr(errors.New("failed to write response"))
}
if size := sizeWriter(caller, resplenptr, uint32(len(respBytes))); size == -1 {
return writeErr(errors.New("failed to write response length"))
}
return ErrnoSuccess
}
}
// createEmitFn injects dependencies and builds the emit function exposed by the WASM. Errors in
// Emit, if any, are returned in the Error Message of the response.
func createEmitFn(
l logger.Logger,
exec *execution[*wasmdagpb.Response],
e custmsg.MessageEmitter,
reader unsafeReaderFunc,
writer unsafeWriterFunc,
sizeWriter unsafeFixedLengthWriterFunc,
) func(caller *wasmtime.Caller, respptr, resplenptr, msgptr, msglen int32) int32 {
logErr := func(err error) {
l.Errorf("error emitting message: %s", err)
}
return func(caller *wasmtime.Caller, respptr, resplenptr, msgptr, msglen int32) int32 {
// writeErr marshals and writes an error response to wasm
writeErr := func(err error) int32 {
logErr(err)
resp := &wasmdagpb.EmitMessageResponse{
Error: &wasmdagpb.Error{
Message: err.Error(),
},
}
respBytes, perr := proto.Marshal(resp)
if perr != nil {
logErr(perr)
return ErrnoFault
}
if size := writer(caller, respBytes, respptr, int32(len(respBytes))); size == -1 {
logErr(errors.New("failed to write response"))
return ErrnoFault
}
if size := sizeWriter(caller, resplenptr, uint32(len(respBytes))); size == -1 {
logErr(errors.New("failed to write response length"))
return ErrnoFault
}
return ErrnoSuccess
}
b, err := reader(caller, msgptr, msglen)
if err != nil {
return writeErr(err)
}
_, msg, labels, err := toEmissible(b)
if err != nil {
return writeErr(err)
}
if err := e.WithMapLabels(labels).Emit(exec.ctx, msg); err != nil {
return writeErr(err)
}
return ErrnoSuccess
}
}
// createLogFn injects dependencies and builds the log function exposed by the WASM.
func createLogFn(logger logger.Logger) func(caller *wasmtime.Caller, ptr int32, ptrlen int32) {
return func(caller *wasmtime.Caller, ptr int32, ptrlen int32) {
b, innerErr := wasmRead(caller, ptr, ptrlen)
if innerErr != nil {
logger.Errorf("error calling log: %s", innerErr)
return
}