wa-lang.org/wazero@v1.0.2/experimental/compilation_cache.go (about)

     1  package experimental
     2  
     3  import (
     4  	"context"
     5  	"errors"
     6  	"fmt"
     7  	"os"
     8  
     9  	"wa-lang.org/wazero/internal/compilationcache"
    10  )
    11  
    12  // WithCompilationCacheDirName configures the destination directory of the compilation cache.
    13  // Regardless of the usage of this, the compiled functions are cached in memory, but its lifetime is
    14  // bound to the lifetime of wazero.Runtime or wazero.CompiledModule.
    15  //
    16  // If the dirname doesn't exist, this creates the directory.
    17  //
    18  // With the given non-empty directory, wazero persists the cache into the directory and that cache
    19  // will be used as long as the running wazero version match the version of compilation wazero.
    20  //
    21  // A cache is only valid for use in one wazero.Runtime at a time. Concurrent use
    22  // of a wazero.Runtime is supported, but multiple runtimes must not share the
    23  // same directory.
    24  //
    25  // Note: The embedder must safeguard this directory from external changes.
    26  //
    27  // Usage:
    28  //
    29  //	ctx, _ := experimental.WithCompilationCacheDirName(context.Background(), "/home/me/.cache/wazero")
    30  //	r := wazero.NewRuntimeWithConfig(ctx, wazero.NewRuntimeConfigCompiler())
    31  func WithCompilationCacheDirName(ctx context.Context, dirname string) (context.Context, error) {
    32  	if st, err := os.Stat(dirname); errors.Is(err, os.ErrNotExist) {
    33  		// If the directory not found, create the cache dir.
    34  		if err = os.MkdirAll(dirname, 0o700); err != nil {
    35  			return nil, fmt.Errorf("create diretory %s: %v", dirname, err)
    36  		}
    37  	} else if err != nil {
    38  		return nil, err
    39  	} else if !st.IsDir() {
    40  		return nil, fmt.Errorf("%s is not dir", dirname)
    41  	}
    42  
    43  	ctx = context.WithValue(ctx, compilationcache.FileCachePathKey{}, dirname)
    44  	return ctx, nil
    45  }