worker

package
v0.3.18 Latest Latest
Warning

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

Go to latest
Published: Feb 20, 2024 License: BSD-2-Clause Imports: 12 Imported by: 0

README

Web Worker API

This package allows you to create a Javascript Web Worker from WASM and facilitates communication between the web worker and the main thread using a messaging system.

Creating a Worker

Web workers have two sides. There is the main side that creates the worker thread and the thread itself. The thread needs to be compiled into its own WASM binary and must have a corresponding Javascript file to launch it.

Example main.go:

package main

import (
	"fmt"
	"gitlab.com/elixxir/xxdk-wasm/worker"
)

func main() {
	fmt.Println("Starting WebAssembly Worker.")
	tm := worker.NewThreadManager("exampleWebWorker", true)
	tm.SignalReady()
	<-make(chan bool)
}

Example WASM start file:

importScripts('wasm_exec.js');

const go = new Go();
const binPath = 'xxdk-exampleWebWorker.wasm'
WebAssembly.instantiateStreaming(fetch(binPath), go.importObject).then((result) => {
    go.run(result.instance);
}).catch((err) => {
    console.error(err);
});

To start the worker, call worker.NewManager with the Javascript file to launch the worker.

m, err := worker.NewManager("workerWasm.js", "exampleWebWorker", true)
if err != nil {
return nil, err
}

Documentation

Rendered for js/wasm

Index

Constants

View Source
const (
	Channel1LogMsgChanName = "Channel1Logger"
	LoggerTag              = "logger"
)

Variables

This section is empty.

Functions

func CreateMessageChannel added in v0.3.4

func CreateMessageChannel(w1, w2 *Manager, channelName, key string) error

CreateMessageChannel creates a new Javascript MessageChannel between two workers. The [Channel] tag will be used as the prefix in the name of the MessageChannel when printing to logs. The key is used to look up the callback registered on the worker to handle the MessageChannel creation.

Doc: https://developer.mozilla.org/en-US/docs/Web/API/MessageChannel

Types

type Manager

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

Manager manages the handling of messages received from the worker.

func NewManager

func NewManager(aURL, name string, messageLogging bool) (*Manager, error)

NewManager generates a new Manager. This functions will only return once communication with the worker has been established.

func NewManagerFromScript added in v0.3.4

func NewManagerFromScript(
	jsScript, name string, messageLogging bool) (*Manager, error)

NewManagerFromScript generates a new Manager. This functions will only return once communication with the worker has been established. TODO: test or remove

func (*Manager) GetWorker

func (m *Manager) GetWorker() js.Value

GetWorker returns the Worker wrapper for the Worker Javascript object. This is returned so the worker object can be returned to the Javascript layer for it to communicate with the worker thread.

func (*Manager) Name

func (m *Manager) Name() string

Name returns the name of the web worker object.

func (*Manager) RegisterCallback

func (m *Manager) RegisterCallback(tag Tag, receiverCB ReceiverCallback)

RegisterCallback registers the callback for the given tag. Previous tags are overwritten. This function is thread safe.

func (*Manager) SendMessage

func (m *Manager) SendMessage(tag Tag, data []byte) (response []byte, err error)

SendMessage sends a message to the worker with the given tag and waits for a response. An error is returned on failure to send or on timeout.

func (*Manager) SendNoResponse added in v0.3.4

func (m *Manager) SendNoResponse(tag Tag, data []byte) error

SendNoResponse sends a message to the worker with the given tag. It returns immediately and does not wait for a response.

func (*Manager) SendTimeout added in v0.3.4

func (m *Manager) SendTimeout(
	tag Tag, data []byte, timeout time.Duration) (response []byte, err error)

SendTimeout sends a message to the worker with the given tag and waits for a response. An error is returned on failure to send or on the specified timeout.

func (*Manager) Stop added in v0.3.3

func (m *Manager) Stop() error

Stop closes the worker manager and terminates the worker.

type Message

type Message struct {
	Tag      Tag    `json:"tag"`
	ID       uint64 `json:"id"`
	Response bool   `json:"response"`
	Data     []byte `json:"data"`
}

Message is the outer message that contains the contents of each message sent to the worker. It is transmitted as JSON.

type MessageChannel added in v0.3.4

type MessageChannel struct {
	safejs.Value
}

MessageChannel wraps a Javascript MessageChannel object.

Doc: https://developer.mozilla.org/en-US/docs/Web/API/MessageChannel

func NewMessageChannel added in v0.3.4

func NewMessageChannel() (MessageChannel, error)

NewMessageChannel returns a new MessageChannel object with two new MessagePort objects.

Doc: https://developer.mozilla.org/en-US/docs/Web/API/MessageChannel/MessageChannel

func (MessageChannel) Port1 added in v0.3.4

func (mc MessageChannel) Port1() (MessagePort, error)

Port1 returns the first port of the message channel — the port attached to the context that originated the channel.

Doc: https://developer.mozilla.org/en-US/docs/Web/API/MessageChannel/port1

func (MessageChannel) Port2 added in v0.3.4

func (mc MessageChannel) Port2() (MessagePort, error)

Port2 returns the second port of the message channel — the port attached to the context at the other end of the channel, which the message is initially sent to.

Doc: https://developer.mozilla.org/en-US/docs/Web/API/MessageChannel/port2

type MessageEvent added in v0.3.4

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

MessageEvent is received from the channel returned by Listen(). Represents a JS MessageEvent.

func (MessageEvent) Data added in v0.3.4

func (e MessageEvent) Data() (safejs.Value, error)

Data returns this event's data or a parse error

type MessageManager added in v0.3.4

type MessageManager struct {
	Params
	// contains filtered or unexported fields
}

MessageManager manages the sending and receiving of messages to a remote browser context (e.g., Worker and MessagePort)

func NewMessageManager added in v0.3.4

func NewMessageManager(
	v safejs.Value, name string, p Params) (*MessageManager, error)

NewMessageManager generates a new MessageManager. This functions will only return once communication with the remote thread has been established. TODO: test

func (*MessageManager) RegisterCallback added in v0.3.4

func (mm *MessageManager) RegisterCallback(tag Tag, receiverCB ReceiverCallback)

RegisterCallback registers the callback for the given tag. Previous tags are overwritten. This function is thread safe.

func (*MessageManager) RegisterMessageChannelCallback added in v0.3.4

func (mm *MessageManager) RegisterMessageChannelCallback(
	key string, fn NewPortCallback)

RegisterMessageChannelCallback registers a callback that will be called when a MessagePort with the given Channel is received.

func (*MessageManager) Send added in v0.3.4

func (mm *MessageManager) Send(tag Tag, data []byte) (response []byte, err error)

Send sends the data to the remote thread with the given tag and waits for a response. Returns an error if calling postMessage throws an exception, marshalling the message to send fails, or if receiving a response times out.

It is preferable to use [Send] over [SendNoResponse] as it will report a timeout when the remote thread crashes and [SendNoResponse] will not. TODO: test

func (*MessageManager) SendNoResponse added in v0.3.4

func (mm *MessageManager) SendNoResponse(tag Tag, data []byte) error

SendNoResponse sends the data to the remote thread with the given tag; however, unlike [Send], it returns immediately and does not wait for a response. Returns an error if calling postMessage throws an exception, marshalling the message to send fails, or if receiving a response times out.

It is preferable to use [Send] over [SendNoResponse] as it will report a timeout when the remote thread crashes and [SendNoResponse] will not. TODO: test

func (*MessageManager) SendTimeout added in v0.3.4

func (mm *MessageManager) SendTimeout(
	tag Tag, data []byte, timeout time.Duration) (response []byte, err error)

SendTimeout sends the data to the remote thread with a custom timeout. Refer to [Send] for more information. TODO: test

func (*MessageManager) Stop added in v0.3.4

func (mm *MessageManager) Stop()

Stop closes the message reception thread and closes the port. TODO: test

type MessagePort added in v0.3.4

type MessagePort struct {
	safejs.Value
}

MessagePort wraps a Javascript MessagePort object.

Doc: https://developer.mozilla.org/en-US/docs/Web/API/MessagePort

func NewMessagePort added in v0.3.4

func NewMessagePort(v safejs.Value) (MessagePort, error)

NewMessagePort wraps the given MessagePort.

func (MessagePort) Listen added in v0.3.4

func (mp MessagePort) Listen(
	ctx context.Context) (_ <-chan MessageEvent, err error)

Listen registers listeners on the MessagePort and returns all events on the returned channel.

func (MessagePort) PostMessage added in v0.3.4

func (mp MessagePort) PostMessage(message any) error

PostMessage sends a message from the port.

func (MessagePort) PostMessageTransfer added in v0.3.4

func (mp MessagePort) PostMessageTransfer(message any, transfer ...any) error

PostMessageTransfer sends a message from the port and transfers ownership of objects to other browsing contexts.

func (MessagePort) PostMessageTransferBytes added in v0.3.4

func (mp MessagePort) PostMessageTransferBytes(message []byte) error

PostMessageTransferBytes sends the message bytes from the port via transfer.

type NewPortCallback added in v0.3.4

type NewPortCallback func(port js.Value, channelName string)

NewPortCallback is called with a MessagePort Javascript object when received.

type Params added in v0.3.4

type Params struct {
	// MessageLogging indicates if a DEBUG message should be printed every time
	// a message is sent or received.
	MessageLogging bool

	// ResponseTimeout is the default timeout to wait for a response before
	// timing out and returning an error.
	ResponseTimeout time.Duration
}

Params are parameters used in the MessageManager.

func DefaultParams added in v0.3.4

func DefaultParams() Params

DefaultParams returns the default parameters.

type ReceiverCallback added in v0.3.4

type ReceiverCallback func(message []byte, reply func(message []byte))

ReceiverCallback is called when receiving a message from the sender. Reply can optionally be used to send a response to the caller, triggering the SenderCallback.

type SenderCallback added in v0.3.4

type SenderCallback func(message []byte)

SenderCallback is called when the sender of a message gets a response. The message is the response from the receiver.

type Tag

type Tag string

Tag describes how a message sent to or from the worker should be handled.

type Thread added in v0.3.4

type Thread struct {
	MessagePort
}

Thread has the methods of the Javascript DedicatedWorkerGlobalScope.

Doc: https://developer.mozilla.org/en-US/docs/Web/API/DedicatedWorkerGlobalScope

func NewThread added in v0.3.4

func NewThread() (Thread, error)

NewThread creates a new Thread from Global.

func (*Thread) Close added in v0.3.4

func (t *Thread) Close() error

Close discards any tasks queued in the worker's event loop, effectively closing this particular scope.

Doc: https://developer.mozilla.org/en-US/docs/Web/API/DedicatedWorkerGlobalScope/close

func (*Thread) Name added in v0.3.4

func (t *Thread) Name() string

Name returns the name that the Worker was (optionally) given when it was created.

Doc: https://developer.mozilla.org/en-US/docs/Web/API/DedicatedWorkerGlobalScope/name

type ThreadManager

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

ThreadManager queues incoming messages from the main thread and handles them based on their tag.

func NewThreadManager

func NewThreadManager(name string, messageLogging bool) (*ThreadManager, error)

NewThreadManager initialises a new ThreadManager.

func (*ThreadManager) GetWorker added in v0.3.4

func (tm *ThreadManager) GetWorker() js.Value

func (*ThreadManager) Name added in v0.3.4

func (tm *ThreadManager) Name() string

Name returns the name of the web worker.

func (*ThreadManager) RegisterCallback

func (tm *ThreadManager) RegisterCallback(tag Tag, receiverCB ReceiverCallback)

RegisterCallback registers the callback for the given tag. Previous tags are overwritten. This function is thread safe.

func (*ThreadManager) RegisterMessageChannelCallback added in v0.3.4

func (tm *ThreadManager) RegisterMessageChannelCallback(
	tag string, fn NewPortCallback)

RegisterMessageChannelCallback registers a callback that will be called when a MessagePort with the given Channel is received.

func (*ThreadManager) SendMessage

func (tm *ThreadManager) SendMessage(
	tag Tag, data []byte) (response []byte, err error)

SendMessage sends a message to the main thread with the given tag and waits for a response. An error is returned on failure to send or on timeout.

func (*ThreadManager) SendNoResponse added in v0.3.4

func (tm *ThreadManager) SendNoResponse(tag Tag, data []byte) error

SendNoResponse sends a message to the main thread with the given tag. It returns immediately and does not wait for a response.

func (*ThreadManager) SendTimeout added in v0.3.4

func (tm *ThreadManager) SendTimeout(
	tag Tag, data []byte, timeout time.Duration) (response []byte, err error)

SendTimeout sends a message to the main thread with the given tag and waits for a response. An error is returned on failure to send or on the specified timeout.

func (*ThreadManager) SignalReady

func (tm *ThreadManager) SignalReady()

SignalReady sends a signal to the main thread indicating that the worker is ready. Once the main thread receives this, it will initiate communication. Therefore, this should only be run once all listeners are ready.

func (*ThreadManager) Stop added in v0.3.3

func (tm *ThreadManager) Stop() error

Stop closes the thread manager and stops the worker.

type ThreadReceptionCallback

type ThreadReceptionCallback func(message []byte, reply func(message []byte))

ThreadReceptionCallback is called with a message received from the main thread. Any bytes returned are sent as a response back to the main thread. Any returned errors are printed to the log.

type Worker added in v0.3.4

type Worker struct {
	MessagePort
}

Worker wraps a Javascript Worker object.

Doc: https://developer.mozilla.org/en-US/docs/Web/API/Worker

func NewWorker added in v0.3.4

func NewWorker(aURL string, options map[string]any) (w Worker, err error)

NewWorker creates a Javascript Worker object that executes the script at the specified URL.

It returns any thrown exceptions as errors.

Doc: https://developer.mozilla.org/en-US/docs/Web/API/Worker/Worker

func (Worker) Terminate added in v0.3.4

func (w Worker) Terminate() error

Terminate immediately terminates the Worker. This does not offer the worker an opportunity to finish its operations; it is stopped at once.

Doc: https://developer.mozilla.org/en-US/docs/Web/API/Worker/terminate

Jump to

Keyboard shortcuts

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