wasmww

package module
v0.0.0-...-1b7b5e5 Latest Latest
Warning

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

Go to latest
Published: Oct 19, 2023 License: Apache-2.0 Imports: 20 Imported by: 3

README

go-wasmww

A Web Worker abstraction Go, compiled to WebAssembly.

This is based on https://github.com/magodo/go-webworkers/ (forked from https://github.com/hack-pad/go-webworkers), which is a plane Web Worker wrapper for Go.

Usage

At its basic, it abstracts the exec.Cmd structure, to allow the main thread (the parent process) to create a web worker (the child process), by specifying the WASM URL, together with any arguments or environment variables, if any.

The main types for this basic usage are:

  • WasmWebWorker: Used in the main thread, for creating a Dedicated Web Worker
  • WasmSharedWebWorker: Used in the main thread, for creating a Shared Web Worker

For the application running inside the worker, users are expected to use the worker.GlobalSelf and sharedworker.GlobalSelf in the package github.com/magodo/go-webworkers.

On top of this basic abstraction, we've added the support for the Web Worker connections. In that it supports initialization sync, controlling the peer (e.g. close the peer), and piping the stdout/stderr from the Web Worker back to the outside.

The main types for the connections are:

  • WasmWebWorkerConn: Used in the main thread, for creating a connected Dedicated Web Worker
  • SelfConn: Used in the Dedicated Web Worker
  • WasmSharedWebWorkerConn: Used in the main thread, for creating a connected Shared Web Worker
  • SelfSharedConn: Used in the Shared Web Worker

Example

See /examples.

Documentation

Rendered for js/wasm

Index

Constants

View Source
const CLOSE_EVENT = "__WASMWW_CLOSE__"
View Source
const STDERR_EVENT = "__WASMWW_STDERR__"
View Source
const STDOUT_EVENT = "__WASMWW_STDOUT__"
View Source
const WRITE_TO_CONSOLE_EVENT = "__WASMWW_WRITE_TO_CONSOLE__"
View Source
const WRITE_TO_CONTROLLER_EVENT = "__WASMWW_WRITE_TO_CONTROLLER"

Variables

View Source
var SharedWorkerJSTpl []byte
View Source
var WorkerJSTpl []byte

Functions

func SetWriteSync

func SetWriteSync(stdoutWriters, stderrWriters []MsgWriter)

SetWriteSync overrides the "writeSync" implementation that will be called by Go. It redirects the message to a slice of `MsgWriterFunc` functions for both the stdout and stderr.

Types

type MessagePoster

type MessagePoster interface {
	PostMessage(message safejs.Value, transfers []safejs.Value) error
}

type MsgWriter

type MsgWriter interface {
	Write(p []byte) (n int, err error)
	// contains filtered or unexported methods
}

func NewMsgWriterToConsole

func NewMsgWriterToConsole() MsgWriter

func NewMsgWriterToIoWriter

func NewMsgWriterToIoWriter(w io.Writer) MsgWriter

type SelfConn

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

func NewSelfConn

func NewSelfConn() (*SelfConn, error)

func (*SelfConn) Close

func (s *SelfConn) Close() error

Close closes the web worker, and close the event channel on the controller side.

func (*SelfConn) Name

func (s *SelfConn) Name() (string, error)

func (*SelfConn) NewMsgWriterToControllerStderr

func (s *SelfConn) NewMsgWriterToControllerStderr() MsgWriter

func (*SelfConn) NewMsgWriterToControllerStdout

func (s *SelfConn) NewMsgWriterToControllerStdout() MsgWriter

func (*SelfConn) PostMessage

func (s *SelfConn) PostMessage(message safejs.Value, transfers []safejs.Value) error

func (*SelfConn) ResetWriteSync

func (s *SelfConn) ResetWriteSync()

func (*SelfConn) SetupConn

func (s *SelfConn) SetupConn() (_ <-chan types.MessageEventMessage, err error)

SetupConn setup the worker for working with the peering WasmWebWorkerConn. The returned eventCh receives the event sent from the peering WasmWebWorkerConn, until the closeFn is called. The closeFn is used to instruct the peering to stop listening to this web worker, and close this web worker.

type SelfSharedConn

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

func NewSelfSharedConn

func NewSelfSharedConn() (*SelfSharedConn, error)

func (*SelfSharedConn) Close

func (s *SelfSharedConn) Close() error

Close closes the web worker, and close the event channels on all the controllers side.

func (*SelfSharedConn) Idle

func (s *SelfSharedConn) Idle() bool

Idle tells whether this Shared Web Worker has no connected port at this point

func (*SelfSharedConn) Location

func (s *SelfSharedConn) Location() (*types.WorkerLocation, error)

func (*SelfSharedConn) Name

func (s *SelfSharedConn) Name() (string, error)

func (*SelfSharedConn) NewMsgWriterToControllerStderr

func (s *SelfSharedConn) NewMsgWriterToControllerStderr() MsgWriter

func (*SelfSharedConn) NewMsgWriterToControllerStdout

func (s *SelfSharedConn) NewMsgWriterToControllerStdout() MsgWriter

func (*SelfSharedConn) ResetWriteSync

func (s *SelfSharedConn) ResetWriteSync()

func (*SelfSharedConn) SetupConn

func (s *SelfSharedConn) SetupConn() (_ <-chan *SelfSharedConnPort, err error)

SetupConn set up the worker for working with the peering WasmSharedWebWorkerConn. The returned eventCh sends the SelfSharedConnPort connected with the peering WasmSharedWebWorkerConn, until the closeFn is called.

type SelfSharedConnPort

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

func (*SelfSharedConnPort) Close

func (p *SelfSharedConnPort) Close() error

Close closes this port, and close the event channel on the controller side.

func (*SelfSharedConnPort) PostMessage

func (p *SelfSharedConnPort) PostMessage(message safejs.Value, transfers []safejs.Value) error

func (*SelfSharedConnPort) SetupConn

func (p *SelfSharedConnPort) SetupConn() (_ <-chan types.MessageEventMessage, err error)

SetupConn set up the worker port for working with the peering WasmSharedWebWorkerConn. The returned eventCh sends the MessageEvent connected with the peering WasmSharedWebWorkerConn, until the closeFn is called.

type WasmSharedWebWorker

type WasmSharedWebWorker struct {
	// Name specifies an identifying name for the Shared Web Worker.
	// If this is not specified, `Start` will create a UUIDv4 for it and populate back.
	//
	// This is required in the Connect().
	Name string

	// Path is the path of the WASM to run as the Web Worker.
	// This can be a relative path on the server, or an abosolute URL.
	//
	// This is ignored in the Connect().
	Path string

	// Args holds command line arguments, including the WASM as Args[0].
	// If the Args field is empty or nil, Run uses {Path}.
	//
	// This is ignored in the Connect().
	Args []string

	// Env specifies the environment of the process.
	// Each entry is of the form "key=value".
	// If Env is nil, the new Web Worker uses the current context's
	// environment.
	// If Env contains duplicate environment keys, only the last
	// value in the slice for each duplicate key is used.
	//
	// This is ignored in the Connect().
	Env []string

	// url represents the web worker script url.
	// This is filled in in the Start(), and is required in the Connect().
	URL string
	// contains filtered or unexported fields
}

func (*WasmSharedWebWorker) Close

func (ww *WasmSharedWebWorker) Close() error

Close closes the message port of this worker.

func (*WasmSharedWebWorker) Connect

func (ww *WasmSharedWebWorker) Connect() error

func (*WasmSharedWebWorker) Listen

Listen sends message events on a channel for events fired by port.postMessage() calls inside the Worker's. Stops the listener and closes the channel when ctx is canceled.

func (*WasmSharedWebWorker) PostMessage

func (ww *WasmSharedWebWorker) PostMessage(data safejs.Value, transfers []safejs.Value) error

PostMessage sends data in a message to the worker, optionally transferring ownership of all items in transfers.

func (*WasmSharedWebWorker) Start

func (ww *WasmSharedWebWorker) Start() error

type WasmSharedWebWorkerConn

type WasmSharedWebWorkerConn struct {
	// Name specifies an identifying name for the Shared Web Worker.
	// If this is not specified, `Start` will create a UUIDv4 for it and populate back.
	Name string

	// Path is the path of the WASM to run as the Web Worker.
	// This can be a relative path on the server, or an abosolute URL.
	Path string

	// Args holds command line arguments, including the WASM as Args[0].
	// If the Args field is empty or nil, Run uses {Path}.
	Args []string

	// Env specifies the environment of the process.
	// Each entry is of the form "key=value".
	// If Env is nil, the new Web Worker uses the current context's
	// environment.
	// If Env contains duplicate environment keys, only the last
	// value in the slice for each duplicate key is used.
	Env []string

	// URL represents the web worker script URL.
	// This is populated in the Start().
	URL string
	// contains filtered or unexported fields
}

WasmSharedWebWorkerConn is a high level wrapper around the WasmSharedWebWorker, which provides a full duplex connection between the web worker. On the web worker, it is expected to call the SelfSharedConn.SetupConn() to build up the connection.

func (*WasmSharedWebWorkerConn) Close

func (conn *WasmSharedWebWorkerConn) Close() error

Close closes this WasmSharedWebWorkerConn at the outside and notify the web worker.

func (*WasmSharedWebWorkerConn) Connect

func (conn *WasmSharedWebWorkerConn) Connect() (err error)

Connect creates a new WasmSharedWebWorkerConn to an active Shared Web Worker. Only the conn.Name and conn.URL matters.

func (*WasmSharedWebWorkerConn) EventChannel

func (conn *WasmSharedWebWorkerConn) EventChannel() <-chan types.MessageEventMessage

EventChannel returns the channel that receives events sent from the Web Worker.

func (*WasmSharedWebWorkerConn) PostMessage

func (conn *WasmSharedWebWorkerConn) PostMessage(data safejs.Value, transfers []safejs.Value) error

PostMessage sends data in a message to the worker, optionally transferring ownership of all items in transfers.

func (*WasmSharedWebWorkerConn) Start

Start starts a new Shared Web Worker. It spins up a goroutine to receive the events from the Web Worker, and exposes a channel for consuming those events, which can be accessed by the `EventChannel()` method. It will fail if the Shared Web Worker already exists. In this case, use Connect() instead. The returned WasmSharedWebWorkerMgmtConn is a special connection, that is used to manage the web worker, or create another WasmSharedWebWorkerConn to this web worker via its Connect() method.

func (*WasmSharedWebWorkerConn) Wait

func (conn *WasmSharedWebWorkerConn) Wait()

Wait waits for the controller's internal event loop to quit. This can be caused by the worker closes itself.

type WasmSharedWebWorkerMgmtConn

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

WasmSharedWebWorkerMgmtConn is a connection to a newly started Shared Web Worker. It is only meant to: - Receive stdout/stderr from the worker, in form of the message event. - Send mgmt message events to the worker, including:

  • Close event to let it close itself
  • SetWriteToConsole event to let it write to console
  • SetWriteToController event to let it write to this port back to the controller

func (*WasmSharedWebWorkerMgmtConn) Close

Close mimics the terminate method of the DedicatedWorkerGlobalScope, but more gracefully. It sends a close message to the shared worker, which will in turn relay the close message back to the outside, and close itself in the meanwhile.

func (*WasmSharedWebWorkerMgmtConn) Connect

func (c *WasmSharedWebWorkerMgmtConn) Connect() (conn *WasmSharedWebWorkerConn, err error)

Connect is a utility function taht creates a new WasmSharedWebWorkerConn and connect it to the active Shared Web Worker.

func (*WasmSharedWebWorkerMgmtConn) SetWriteToConsole

func (c *WasmSharedWebWorkerMgmtConn) SetWriteToConsole() error

SetWriteToConsole instructs the worker to write its stdout/stderr to console

func (*WasmSharedWebWorkerMgmtConn) SetWriteToController

func (c *WasmSharedWebWorkerMgmtConn) SetWriteToController() error

SetWriteToController instructs the worker to write its stdout/stderr to controller, which can be retrieved by Stdout(), Stderr().

func (*WasmSharedWebWorkerMgmtConn) Stderr

Stderr returns an io.ReadCloser that streams out the stderr of the web worker as long as its target write destination implementation is not modified to redirect to other sinks

func (*WasmSharedWebWorkerMgmtConn) Stdout

Stdout returns an io.ReadCloser that streams out the stdout of the web worker as long as its target write destination is not modified to redirect to other sinks

func (*WasmSharedWebWorkerMgmtConn) Wait

func (c *WasmSharedWebWorkerMgmtConn) Wait()

Wait waits for the controller's internal event loop to quit. This can be caused by the worker closes itself.

type WasmWebWorker

type WasmWebWorker struct {
	// Name specifies an identifying name for the DedicatedWorkerGlobalScope representing the scope of the worker, which is mainly useful for debugging purposes.
	// If this is not specified, `Start` will create a UUIDv4 for it and populate back.
	Name string

	// Path is the path of the WASM to run as the Web Worker.
	// This can be a relative path on the server, or an abosolute URL.
	Path string

	// Args holds command line arguments, including the WASM as Args[0].
	// If the Args field is empty or nil, Run uses {Path}.
	Args []string

	// Env specifies the environment of the process.
	// Each entry is of the form "key=value".
	// If Env is nil, the new Web Worker uses the current context's
	// environment.
	// If Env contains duplicate environment keys, only the last
	// value in the slice for each duplicate key is used.
	Env []string
	// contains filtered or unexported fields
}

func (*WasmWebWorker) Listen

func (ww *WasmWebWorker) Listen(ctx context.Context) (<-chan types.MessageEventMessage, error)

Listen sends message events on a channel for events fired by self.postMessage() calls inside the Worker's global scope. Stops the listener and closes the channel when ctx is canceled.

func (*WasmWebWorker) PostMessage

func (ww *WasmWebWorker) PostMessage(data safejs.Value, transfers []safejs.Value) error

PostMessage sends data in a message to the worker, optionally transferring ownership of all items in transfers.

func (*WasmWebWorker) Start

func (ww *WasmWebWorker) Start() error

func (*WasmWebWorker) Terminate

func (ww *WasmWebWorker) Terminate()

Terminate immediately terminates the Worker.

type WasmWebWorkerConn

type WasmWebWorkerConn struct {
	// Name specifies an identifying name for the DedicatedWorkerGlobalScope representing the scope of the worker, which is mainly useful for debugging purposes.
	// If this is not specified, `Start` will create a UUIDv4 for it and populate back.
	Name string

	// Path is the path of the WASM to run as the Web Worker.
	// This can be a relative path on the server, or an abosolute URL.
	Path string

	// Args holds command line arguments, including the WASM as Args[0].
	// If the Args field is empty or nil, Run uses {Path}.
	Args []string

	// Env specifies the environment of the process.
	// Each entry is of the form "key=value".
	// If Env is nil, the new Web Worker uses the current context's
	// environment.
	// If Env contains duplicate environment keys, only the last
	// value in the slice for each duplicate key is used.
	Env []string

	Stdout io.Writer
	Stderr io.Writer
	// contains filtered or unexported fields
}

WasmWebWorkerConn is a high level wrapper around the WasmWebWorker, which provides a full duplex connection between the web worker. On the web worker, it is expected to call the SelfConn.SetupConn() to build up the connection.

func (*WasmWebWorkerConn) EventChannel

func (conn *WasmWebWorkerConn) EventChannel() <-chan types.MessageEventMessage

EventChannel returns the channel that receives events sent from the Web Worker.

func (*WasmWebWorkerConn) PostMessage

func (conn *WasmWebWorkerConn) PostMessage(data safejs.Value, transfers []safejs.Value) error

PostMessage sends data in a message to the worker, optionally transferring ownership of all items in transfers.

func (*WasmWebWorkerConn) Start

func (conn *WasmWebWorkerConn) Start() (err error)

Start starts a new Web Worker. It spins up a goroutine to receive the events from the Web Worker, and exposes a channel for consuming those events, which can be accessed by the `EventChannel()` method.

func (*WasmWebWorkerConn) StderrPipe

func (conn *WasmWebWorkerConn) StderrPipe() (io.ReadCloser, error)

StderrPipe returns a channel that will be connected to the worker's standard error when the worker starts.

Once the worker is exited (no matter closed by itself or terminated), the channel will be closed by the WasmWebWorkerConn. So no need to close the channel themselves.

func (*WasmWebWorkerConn) StdoutPipe

func (conn *WasmWebWorkerConn) StdoutPipe() (io.ReadCloser, error)

StdoutPipe returns a channel that will be connected to the worker's standard output when the worker starts.

Once the worker is exited (no matter closed by itself or terminated), the channel will be closed by the WasmWebWorkerConn. So no need to close the channel themselves.

func (*WasmWebWorkerConn) Terminate

func (conn *WasmWebWorkerConn) Terminate()

Terminate immediately terminates the Worker. Meanwhile, it stops the internal event loop, which makes the `Wait` to return.

func (*WasmWebWorkerConn) Wait

func (conn *WasmWebWorkerConn) Wait()

Wait waits for the controller's internal event loop to quit. This can be caused by either worker closes itself, or controler calls `Terminate`.

type WebWorkerCloseFunc

type WebWorkerCloseFunc func() error

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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