github.com/bananabytelabs/wazero@v0.0.0-20240105073314-54b22a776da8/cache_example_test.go (about) 1 package wazero_test 2 3 import ( 4 "context" 5 _ "embed" 6 "log" 7 "os" 8 9 "github.com/bananabytelabs/wazero" 10 ) 11 12 // This is a basic example of using the file system compilation cache via wazero.NewCompilationCacheWithDir. 13 // The main goal is to show how it is configured. 14 func Example_compileCache() { 15 // Prepare a cache directory. 16 cacheDir, err := os.MkdirTemp("", "example") 17 if err != nil { 18 log.Panicln(err) 19 } 20 defer os.RemoveAll(cacheDir) 21 22 ctx := context.Background() 23 24 // Create a runtime config which shares a compilation cache directory. 25 cache := newCompilationCacheWithDir(cacheDir) 26 defer cache.Close(ctx) 27 config := wazero.NewRuntimeConfig().WithCompilationCache(cache) 28 29 // Using the same wazero.CompilationCache instance allows the in-memory cache sharing. 30 newRuntimeCompileClose(ctx, config) 31 newRuntimeCompileClose(ctx, config) 32 33 // Since the above stored compiled functions to disk as well, below won't compile from scratch. 34 // Instead, compilation result stored in the directory is re-used. 35 newRuntimeCompileClose(ctx, config.WithCompilationCache(newCompilationCacheWithDir(cacheDir))) 36 newRuntimeCompileClose(ctx, config.WithCompilationCache(newCompilationCacheWithDir(cacheDir))) 37 38 // Output: 39 // 40 } 41 42 func newCompilationCacheWithDir(cacheDir string) wazero.CompilationCache { 43 cache, err := wazero.NewCompilationCacheWithDir(cacheDir) 44 if err != nil { 45 log.Panicln(err) 46 } 47 return cache 48 } 49 50 // newRuntimeCompileDestroy creates a new wazero.Runtime, compile a binary, and then delete the runtime. 51 func newRuntimeCompileClose(ctx context.Context, config wazero.RuntimeConfig) { 52 r := wazero.NewRuntimeWithConfig(ctx, config) 53 defer r.Close(ctx) // This closes everything this Runtime created except the file system cache. 54 55 _, err := r.CompileModule(ctx, addWasm) 56 if err != nil { 57 log.Panicln(err) 58 } 59 }