wasi-module-sdk-go/context.go

86 lines
1.6 KiB
Go
Raw Normal View History

2023-05-08 13:21:31 +00:00
package sdk
import (
"context"
"crypto/md5"
"golang.org/x/exp/slog"
"io"
"os"
)
var _ ExecutionContext = (*wasiExecutionContext)(nil)
func newWasiExecutionContext(
ctx context.Context,
logger *slog.Logger,
modName string,
mod Module,
repoRoot, binDir, outDir string,
) *wasiExecutionContext {
return &wasiExecutionContext{
Context: ctx,
logger: logger,
modName: modName,
mod: mod,
repoRoot: repoRoot,
outDir: outDir,
binDir: binDir,
}
}
type wasiExecutionContext struct {
context.Context
stateProxy StateProxy
logger *slog.Logger
mod Module
modName string
repoRoot string
outDir string
binDir string
}
func (w wasiExecutionContext) WorkingDir() string {
return w.repoRoot
}
func (w wasiExecutionContext) OutDir() string {
return w.outDir
}
func (w wasiExecutionContext) BinariesDir() string {
return w.binDir
}
func (w wasiExecutionContext) StdOut() io.Writer {
return os.Stdout
}
func (w wasiExecutionContext) StdErr() io.Writer {
return os.Stderr
}
func (w wasiExecutionContext) Logger() *slog.Logger {
return w.logger
}
func (w wasiExecutionContext) GetState(_ context.Context, key string) ([]byte, StateMetadata, error) {
return w.stateProxy.Get(w.keyBytes(w.mod.Category().String(), w.modName, key))
}
func (w wasiExecutionContext) SetState(_ context.Context, key string, value []byte) error {
return w.stateProxy.Set(w.keyBytes(w.mod.Category().String(), w.modName, key), value)
}
func (w wasiExecutionContext) keyBytes(parts ...string) []byte {
if len(parts) == 0 {
return nil
}
h := md5.New()
for i := range parts {
_, _ = h.Write([]byte(parts[i]))
}
return h.Sum(nil)
}