Small example of how you can interrupt the execution of a wasm module to ensure that it doesn't run for too long.
()
| 93 | // Small example of how you can interrupt the execution of a wasm module to |
| 94 | // ensure that it doesn't run for too long. |
| 95 | func ExampleConfig_interrupt() { |
| 96 | // Enable interruptible code via `Config` and then create an interrupt |
| 97 | // handle which we'll use later to interrupt running code. |
| 98 | config := wasmtime.NewConfig() |
| 99 | config.SetEpochInterruption(true) |
| 100 | engine := wasmtime.NewEngineWithConfig(config) |
| 101 | store := wasmtime.NewStore(engine) |
| 102 | store.SetEpochDeadline(1) |
| 103 | |
| 104 | // Compile and instantiate a small example with an infinite loop. |
| 105 | wasm, err := wasmtime.Wat2Wasm(` |
| 106 | (module |
| 107 | (func (export "run") |
| 108 | (loop |
| 109 | br 0) |
| 110 | ) |
| 111 | ) |
| 112 | `) |
| 113 | if err != nil { |
| 114 | log.Fatal(err) |
| 115 | } |
| 116 | module, err := wasmtime.NewModule(store.Engine, wasm) |
| 117 | if err != nil { |
| 118 | log.Fatal(err) |
| 119 | } |
| 120 | instance, err := wasmtime.NewInstance(store, module, []wasmtime.AsExtern{}) |
| 121 | if err != nil { |
| 122 | log.Fatal(err) |
| 123 | } |
| 124 | run := instance.GetFunc(store, "run") |
| 125 | if run == nil { |
| 126 | log.Fatal("Failed to find function export `run`") |
| 127 | } |
| 128 | |
| 129 | // Spin up a goroutine to send us an interrupt in a second |
| 130 | go func() { |
| 131 | time.Sleep(1 * time.Second) |
| 132 | fmt.Println("Interrupting!") |
| 133 | engine.IncrementEpoch() |
| 134 | }() |
| 135 | |
| 136 | fmt.Println("Entering infinite loop ...") |
| 137 | _, err = run.Call(store) |
| 138 | var trap *wasmtime.Trap |
| 139 | if !errors.As(err, &trap) { |
| 140 | log.Fatal("Unexpected error") |
| 141 | } |
| 142 | |
| 143 | fmt.Println("trap received...") |
| 144 | if !strings.Contains(trap.Message(), "wasm trap: interrupt") { |
| 145 | log.Fatalf("Unexpected trap: %s", trap.Message()) |
| 146 | } |
| 147 | // Output: |
| 148 | // Entering infinite loop ... |
| 149 | // Interrupting! |
| 150 | // trap received... |
| 151 | } |
| 152 |
nothing calls this directly
no test coverage detected
searching dependent graphs…