-
Notifications
You must be signed in to change notification settings - Fork 4
/
wasm.go
52 lines (45 loc) · 1.25 KB
/
wasm.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
package generator
import (
"context"
"fmt"
"io"
"os"
"path/filepath"
"github.com/tetratelabs/wazero"
"github.com/tetratelabs/wazero/imports/wasi_snapshot_preview1"
)
func evalCodeGeneratorPlugin(ctx context.Context, pluginFile []byte, req io.Reader) error {
runtimeCfg := wazero.NewRuntimeConfig()
if cache := getCompilationCache(); cache != nil {
runtimeCfg = runtimeCfg.WithCompilationCache(cache)
}
r := wazero.NewRuntimeWithConfig(ctx, runtimeCfg)
wasi_snapshot_preview1.MustInstantiate(ctx, r)
modCfg := wazero.NewModuleConfig().
WithFSConfig(wazero.NewFSConfig().WithDirMount(".", "/")).
WithStdin(req).
WithStdout(os.Stderr).
WithStderr(os.Stderr).
WithArgs("wasi")
if _, err := r.InstantiateWithConfig(ctx, pluginFile, modCfg); err != nil {
return fmt.Errorf("grpc-federation: failed to instantiate code-generator plugin: %w", err)
}
return nil
}
func getCompilationCache() wazero.CompilationCache {
tmpDir := os.TempDir()
if tmpDir == "" {
return nil
}
cacheDir := filepath.Join(tmpDir, "grpc-federation")
if _, err := os.Stat(cacheDir); err != nil {
if err := os.Mkdir(cacheDir, 0o755); err != nil {
return nil
}
}
cache, err := wazero.NewCompilationCacheWithDir(cacheDir)
if err != nil {
return nil
}
return cache
}