wasify

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 4, 2023 License: MIT Imports: 11 Imported by: 0

README

wasify

wasify-go is a Go library designed to streamline the interaction with WebAssembly (Wasm) modules by providing a developer-friendly API. It abstracts the Wazero runtime.

wasify simplifies communication with the WebAssembly System Interface (WASI), eliminating the need for developers to delve into intricate details or communicate using numbers, which is the standard method of interaction with modules. This library significantly eases the process of running and working with wasm modules, which has traditionally been a less straightforward task.

Installation

go get github.com/wasify-io/wasify-go

Example

main.go
package main

import (
    "context"
    _ "embed"
    "fmt"

    "github.com/wasify-io/wasify-go"
)

//go:embed module/example.wasm
var moduleData []byte

func main() {

    ctx := context.Background()

    runtime, _ := wasify.NewRuntime(ctx, &wasify.RuntimeConfig{
        Runtime:     wasify.RuntimeWazero,
        LogSeverity: wasify.LogInfo,
    })
    defer runtime.Close(ctx)

    module, _ := runtime.NewModule(ctx, &wasify.ModuleConfig{
        Name: "host_all_available_types",
        Wasm: wasify.Wasm{
            Binary: moduleData,
        },
        HostFunctions: []wasify.HostFunction{
            {
                Name: "hostTest",
                Callback: func(ctx context.Context, m *wasify.ModuleProxy, params []wasify.PackedData) wasify.MultiPackedData {

                    bytes, _ := m.Memory.ReadBytesPack(params[0])
                    fmt.Println("Param 1: ", bytes)
                    // ...

                    return m.Memory.WriteMultiPack(
						m.Memory.WriteBytesPack([]byte("Some")),
						m.Memory.WriteBytePack(1),
						m.Memory.WriteUint32Pack(11),
						m.Memory.WriteUint64Pack(2023),
						m.Memory.WriteFloat32Pack(11.1),
						m.Memory.WriteFloat64Pack(11.2023),
						m.Memory.WriteStringPack("Host: Wasify."),
					)

                },
                Params: []wasify.ValueType{
					wasify.ValueTypeBytes,
					wasify.ValueTypeByte,
					wasify.ValueTypeI32,
					wasify.ValueTypeI64,
					wasify.ValueTypeF32,
					wasify.ValueTypeF64,
					wasify.ValueTypeString,
				},
				Results: []wasify.ValueType{
					wasify.ValueTypeBytes,
					wasify.ValueTypeByte,
					wasify.ValueTypeI32,
					wasify.ValueTypeI64,
					wasify.ValueTypeF32,
					wasify.ValueTypeF64,
					wasify.ValueTypeString,
				},
            },
        },
    })

    defer module.Close(ctx)

    // Call guest function
    module.GuestFunction(ctx, "greet").Invoke("example arg", 2023)

}
Wasm Module Example
package main

import (
	"github.com/wasify-io/wasify-go/mdk"
)

func main() {}

//go:wasmimport host_all_available_types hostTest
func hostTest(
	mdk.PackedData,
	mdk.PackedData,
	mdk.PackedData,
	mdk.PackedData,
	mdk.PackedData,
	mdk.PackedData,
	mdk.PackedData,
) mdk.MultiPackedData

//export guestTest
func _guestTest() {
	hostTest(
		mdk.WriteBytesPack([]byte("Guest: Wello Wasify!")),
		mdk.WriteBytePack(byte(1)),
		mdk.WriteUint32Pack(uint32(11)),
		mdk.WriteUint64Pack(uint64(2023)),
		mdk.WriteFloat32Pack(float32(11.1)),
		mdk.WriteFloat64Pack(float64(11.2023)),
		mdk.WriteStringPack("Guest: Wasify."),
	)
}

Build module using TinyGo

tinygo build -o ./module/example.wasm -target wasi ./module/example.go

Run main.go go run .

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

Documentation

Overview

This file provides abstractions and implementations for interacting with different WebAssembly runtimes, specifically focusing on the Wazero runtime.

Index

Constants

View Source
const WASIFY_NAMESPACE = "wasify"

Variables

This section is empty.

Functions

This section is empty.

Types

type FSConfig

type FSConfig struct {
	// Whether to Enabled the directory for WASI access.
	Enabled bool

	// The directory on the host system.
	// Default: "/"
	HostDir string

	// The directory accessible to the WASI module.
	GuestDir string
}

FSConfig configures a directory to be pre-opened for access by the WASI module if Enabled is set to true. If GuestDir is not provided, the default guest directory will be "/". Note: If FSConfig is not provided or Enabled is false, the directory will not be attached to WASI.

type GuestFunction

type GuestFunction interface {
	Invoke(args ...any) (*GuestFunctionResult, error)
	// contains filtered or unexported methods
}

type GuestFunctionResult

type GuestFunctionResult struct {
	// contains filtered or unexported fields
}

func (GuestFunctionResult) ReadPacks

func (r GuestFunctionResult) ReadPacks() ([]PackedData, error)

ReadPacks decodes the packedData from a GuestFunctionResult instance and retrieves a sequence of packed datas. NOTE: Frees multiPackedData, which means ReadPacks should be called once.

type HostFunction

type HostFunction struct {
	// Callback function to execute when the host function is invoked.
	Callback HostFunctionCallback

	// Name of the host function.
	Name string

	// Params specifies the types of parameters that the host function expects.
	//
	// The length of 'Params' should match the expected number of arguments
	// from the host function when called from the guest.
	Params []ValueType

	// Results specifies the types of values that the host function Results.
	//
	// The length of 'Results' should match the expected number of Results
	// from the host function as used in the guest.
	Results []ValueType
	// contains filtered or unexported fields
}

HostFunction defines a host function that can be invoked from a guest module.

type HostFunctionCallback

type HostFunctionCallback func(ctx context.Context, moduleProxy *ModuleProxy, multiPackedData []PackedData) MultiPackedData

HostFunctionCallback is the function signature for the callback executed by a host function.

HostFunctionCallback encapsulates the runtime's internal implementation details. It serves as an intermediary invoked between the processing of function parameters and the final return of the function.

type LogSeverity

type LogSeverity utils.LogSeverity

The log level is initially set to "Info" for runtimes and "zero" (0) for modules. However, modules will adopt the log level from their parent runtime. If you want only "Error" level for a runtime but need to debug specific module(s), you can set those modules to "Debug". This will replace the inherited log level, allowing the module to display debug information.

type Memory

type Memory interface {
	ReadBytes(offset uint32, size uint32) ([]byte, error)
	ReadByte(offset uint32) (byte, error)
	ReadUint32(offset uint32) (uint32, error)
	ReadUint64(offset uint32) (uint64, error)
	ReadFloat32(offset uint32) (float32, error)
	ReadFloat64(offset uint32) (float64, error)
	ReadString(offset uint32, size uint32) (string, error)

	ReadAnyPack(pd PackedData) (any, uint32, uint32, error)
	ReadBytesPack(pd PackedData) ([]byte, error)
	ReadBytePack(pd PackedData) (byte, error)
	ReadUint32Pack(pd PackedData) (uint32, error)
	ReadUint64Pack(pd PackedData) (uint64, error)
	ReadFloat32Pack(pd PackedData) (float32, error)
	ReadFloat64Pack(pd PackedData) (float64, error)
	ReadStringPack(pd PackedData) (string, error)

	WriteAny(offset uint32, v any) error
	WriteBytes(offset uint32, v []byte) error
	WriteByte(offset uint32, v byte) error
	WriteUint32(offset uint32, v uint32) error
	WriteUint64(offset uint32, v uint64) error
	WriteFloat32(offset uint32, v float32) error
	WriteFloat64(offset uint32, v float64) error
	WriteString(offset uint32, v string) error

	WriteBytesPack(v []byte) PackedData
	WriteBytePack(v byte) PackedData
	WriteUint32Pack(v uint32) PackedData
	WriteUint64Pack(v uint64) PackedData
	WriteFloat32Pack(v float32) PackedData
	WriteFloat64Pack(v float64) PackedData
	WriteStringPack(v string) PackedData

	WriteMultiPack(...PackedData) MultiPackedData

	FreePack(...PackedData) error
	Free(...uint32) error

	Size() uint32
	Malloc(size uint32) (uint32, error)
}

type Module

type Module interface {
	Close(ctx context.Context) error
	GuestFunction(ctx context.Context, functionName string) GuestFunction
	Memory() Memory
}

type ModuleConfig

type ModuleConfig struct {
	// Module Namespace. Required.
	Namespace string

	// FSConfig configures a directory to be pre-opened for access by the WASI module if Enabled is set to true.
	// If GuestDir is not provided, the default guest directory will be "/".
	// Note: If FSConfig is not provided or Enabled is false, the directory will not be attached to WASI.
	FSConfig FSConfig

	// WASM configuration. Required.
	Wasm Wasm

	// List of host functions to be registered.
	HostFunctions []HostFunction

	// Set the severity level for a particular module's logs.
	// Note: If LogSeverity isn't specified, the severity is inherited from the parent, like the runtime log severity.
	LogSeverity LogSeverity
	// contains filtered or unexported fields
}

type ModuleProxy

type ModuleProxy struct {
	Memory Memory
}

type MultiPackedData

type MultiPackedData uint64

Param defines the attributes of a function parameter.

type PackedData

type PackedData uint64

type Runtime

type Runtime interface {
	NewModule(context.Context, *ModuleConfig) (Module, error)
	Close(ctx context.Context) error
}

func NewRuntime

func NewRuntime(ctx context.Context, c *RuntimeConfig) (runtime Runtime, err error)

NewRuntime creates and initializes a new runtime based on the provided configuration. It returns the initialized runtime and any error that might occur during the process.

type RuntimeConfig

type RuntimeConfig struct {
	// Specifies the type of runtime being used.
	Runtime RuntimeType
	// Determines the severity level of logging.
	LogSeverity LogSeverity
	// contains filtered or unexported fields
}

The RuntimeConfig struct holds configuration settings for a runtime.

type RuntimeType

type RuntimeType uint8

RuntimeType defines a type of WebAssembly (wasm) runtime.

Currently, the only supported wasm runtime is Wazero. However, in the future, more runtimes could be added. This means that you'll be able to run modules on various wasm runtimes.

const (
	RuntimeWazero RuntimeType = iota
)

func (RuntimeType) String

func (rt RuntimeType) String() (runtimeName string)

type ValueType

type ValueType types.ValueType

ValueType represents the type of value used in function parameters and returns.

supported value types in params and returns

type Wasm

type Wasm struct {
	Binary []byte
	Hash   string
}

Wasm configures a new wasm file. Binay is required. Hash is optional.

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL