...
1 package wazero_test
2
3 import (
4 "context"
5 _ "embed"
6 "fmt"
7 "log"
8 "time"
9
10 "github.com/tetratelabs/wazero"
11 )
12
13
14
15
16 var infiniteLoopWasm []byte
17
18
19
20
21 func ExampleRuntimeConfig_WithCloseOnContextDone_context_timeout() {
22 ctx := context.Background()
23
24 r := wazero.NewRuntimeWithConfig(ctx,
25
26 wazero.NewRuntimeConfig().WithCloseOnContextDone(true))
27 defer r.Close(ctx)
28
29 moduleInstance, err := r.InstantiateWithConfig(ctx, infiniteLoopWasm,
30 wazero.NewModuleConfig().WithName("malicious_wasm"))
31 if err != nil {
32 log.Panicln(err)
33 }
34
35 infiniteLoop := moduleInstance.ExportedFunction("infinite_loop")
36
37
38 ctx, cancel := context.WithTimeout(ctx, time.Second)
39 defer cancel()
40
41
42 _, err = infiniteLoop.Call(ctx)
43
44
45 fmt.Println(err)
46
47
48
49 }
50
51
52
53
54 func ExampleRuntimeConfig_WithCloseOnContextDone_context_cancel() {
55 ctx := context.Background()
56
57 r := wazero.NewRuntimeWithConfig(ctx,
58
59 wazero.NewRuntimeConfig().WithCloseOnContextDone(true))
60 defer r.Close(ctx)
61
62 moduleInstance, err := r.InstantiateWithConfig(ctx, infiniteLoopWasm,
63 wazero.NewModuleConfig().WithName("malicious_wasm"))
64 if err != nil {
65 log.Panicln(err)
66 }
67
68 infiniteLoop := moduleInstance.ExportedFunction("infinite_loop")
69
70
71 ctx, cancel := context.WithCancel(ctx)
72 go func() {
73
74 time.Sleep(2 * time.Second)
75 cancel()
76 }()
77
78
79 _, err = infiniteLoop.Call(ctx)
80
81
82 fmt.Println(err)
83
84
85
86 }
87
88
89
90
91 func ExampleRuntimeConfig_WithCloseOnContextDone_moduleClose() {
92 ctx := context.Background()
93
94 r := wazero.NewRuntimeWithConfig(ctx,
95
96 wazero.NewRuntimeConfig().WithCloseOnContextDone(true))
97 defer r.Close(ctx)
98
99 moduleInstance, err := r.InstantiateWithConfig(ctx, infiniteLoopWasm,
100 wazero.NewModuleConfig().WithName("malicious_wasm"))
101 if err != nil {
102 log.Panicln(err)
103 }
104
105 infiniteLoop := moduleInstance.ExportedFunction("infinite_loop")
106
107 go func() {
108
109
110 time.Sleep(2 * time.Second)
111 if err := moduleInstance.CloseWithExitCode(ctx, 1); err != nil {
112 log.Panicln(err)
113 }
114 }()
115
116
117 _, err = infiniteLoop.Call(ctx)
118
119
120 fmt.Println(err)
121
122
123
124 }
125
View as plain text