Code Monkey home page Code Monkey logo

wasmcloud-js's Introduction

Important

This host is experimental and does not implement all features or security settings. As a result, this host should not be used in production. For deploying wasmCloud to production, use the primary host runtime.

wasmCloud Host in JavaScript/Browser

This is the JavaScript implementation of the wasmCloud host for the browser (NodeJS support in progress). The library runs a host inside a web browser/application that connects to a remote lattice via NATS and can run wasmCloud actors in the browser. The host will automatically listen for actor start/stop from NATS and will initialize the actor using wapcJS. Any invocations will be handled by the browser actor and returned to the requesting host via NATS. Users can pass callbacks to handle invocation and event data.

Demonstration Video

In this demonstration video we will demonstration the following:

  • Load an HTTP Server capability into a wasmCloud Host running on a machine
  • Load an the wasmcloud-js host into a web browser
  • Load an 'echo' actor into the web browser
  • seamlessly bind the actor to the capability provider through Lattice
  • Access the webserver, which in turn delivers the request to the actor, processes it, and returns it to the requestion client via the capability
  • Unload the actor
wasmcloud-javascript-browser-host-quick-demonstration_2.mp4

Prerequisities

  • NATS with WebSockets enabled

  • wasmCloud lattice (OTP Version)

  • (OPTIONAL) Docker Registry with CORS configured

    • If launching actors from remote registries in the browser host, CORS must be configured on the registry server

Development Prerequisities

  • NodeJS, npm

  • rust, cargo, wasm-pack

    • Used to port the rust versions of wascap, nkeys to JS

Installation

$ npm install @wasmcloud/wasmcloud-js

Usage

More examples can be found in the examples directory, including sample webpack and esbuild configurations

Browser

<script src="https://unpkg.com/@wasmcloud/wasmcloud-js@<VERSION>/dist/wasmcloud.js"></script>
<script>
  (async () => {
    // Start the host passing the name, registry tls enabled, a list of nats ws/wss hosts or the natsConnection object, and an optional host heartbeat interval (default is 30 seconds)
    const host = await wasmcloudjs.startHost("default", false, ["ws://localhost:4222"], 30000);
    // The host will automatically listen for actors start & stop messages, to manually listen for these messages the following methods are exposed
    // only call these methods if your host is not listening for actor start/stop
    // actor invocations are automatically returned to the host. if a user wants to handle the data, they can pass a map of callbacks using the actor ref/wasm file name as the key with a callback(data, result) function. The data contains the invocation data and the result contains the invocation result
    // (async() => {
    //     await host.listenLaunchActor(
    //         {
    //             "localhost:5000/echo:0.2.2": (data, result) => console.log(data.operation, result);
    //         }
    //     );
    //     await host.listenStopActor();
    // })();
    // To launch an actor manually from the library from a registry, optionally a callback can be passed to handle the invocation results. In addition, a hostCall callback and writer can be passed.
    // The hostCallback format is as follows:
    // ```
    // (binding, namespace, operation, payload) => {
    //    return Uint8Array(payload);
    // })
    // ```
    await host.launchActor("registry.com/actor:0.1.1", (data) => { /* handle data */})
    // Launch an actor with the hostCallback
    await host.launchActor("registry.com/actor:0.1.1", (data) => { /* handle data */}, (binding, namespace, operation, payload) => {
        // decode payload via messagepack
        // const decoded = decode(payload);
        return new Uint8Array(payload);
    })
    // To launch an actrom manually from local disk (note the .wasm is required)
    await host.launchActor("./actor.wasm");
    // To listen for events, you can call the subscribeToEvents and pass an optional callback to handle the event data
    await host.subscribeToEvents((eventData) => console.log(eventData, eventData.source));
    // To unsubscribe, call the unsubscribeEvents
    await host.unsubscribeEvents();
    // To start & stop the heartbeat events
    await host.startHeartbeat();
    await host.stopHeartbeat();
    // The host will automatically connect to nats on start. to connect/reconnect to nats
    await host.connectNATS();
    // To close/drain all connections from nats, call the disconnectNATS() method
    await host.disconnectNATS();
    // Stop the host
    await host.stopHost();
    // Restart the host (this only needs to be called if the host is stopped, it is automatically called on the constructor)
    await host.startHost();
  })();
</script>

With a bundler

There are some caveats to using with a bundler:

  • The module contains .wasm files that need to be present alongside the final build output. Using webpack-copy-plugin (or fs.copyFile with other bundlers) can solve this issue.

  • If using with create-react-app, the webpack config will need to be ejected via npm run eject OR an npm library like react-app-rewired can handle the config injection.

// as esm -- this will grant you access to the types/params
import { startHost } from '@wasmcloud/wasmcloud-js';
// as cjs
// const wasmcloudjs = require('@wasmcloud/wasmcloud-js);

async function cjsHost() {
    const host = await wasmcloudjs.startHost('default', false, ['ws://localhost:4222'])
    console.log(host);
}

async function esmHost() {
    const host = await startHost('default', false, ['ws://localhost:4222'])
    console.log(host);
}

cjsHost();
esmHost();
// webpack config, add this to the plugin section
plugins: [
    new CopyPlugin({
        patterns: [
            {
                from: 'node_modules/@wasmcloud/wasmcloud-js/dist/wasmcloud-rs-js/pkg/*.wasm',
                to: '[name].wasm'
            }
        ]
    }),
]

Node

IN PROGRESS - NodeJS does not support WebSockets natively (required by nats.ws)

Contributing

Running tests

$ npm run test

Building

$ npm run build

wasmcloud-js's People

Contributors

autodidaddict avatar brooksmtownsend avatar connorsmith256 avatar ks2211 avatar liamrandall avatar snyk-bot avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

wasmcloud-js's Issues

NodeJS build

Build only supports web browsers, need to use the wasm-pack bundler option to build for both node and browsers

Fix import/cjs build

Code transpiles and publishes. End users can import the methods/classes but their code will NOT run/compile due to the wasmcloud-rs-js/pkg references (the dist/src code looks for it in the parent directory)

actor-to-actor

  • monitoring the distributed cache in order to obtain call alias information
  • supporting host calls via call alias
  • properly encoding the claims on the invocation (can't copy claims from an actor)

Problems trying to reproduce the demo

Hi, I have a few random questions and comments.

First, from my experimentation I'm not sure you can listen for regular NATS and websocket NATS on the same port? In test/infra/nats.conf, I changed the websocket port to e.g. 5222 and removed the listen line, and only then can the container start up correctly. (If you run docker-compose up as it is now you'll see an address already in use error.)

On the wasmcloud_host web UI, I see the JS host show up in the host list after about a minute. I was hoping a could start an actor in it from there, but when I try to use the default remote echo actor, it hangs for about 30s and then shows no actor started, with no error message.

Next, I saw in the demo video that you start the actor from the JS console from a registry at localhost:5000. I wanted to pull the echo actor from the remote registry and push it to the local one, but I found docker can't pull the image. I found a comment on Slack about using wash reg pull and that does work, I get echo.wasm. Now I'm not sure how to push it into the local registry. Does it still work to use a local Docker registry like this?

Build broken

Build is currently broke due to npm token missing

Tests

Need to use the wasm-pack bundler option in order to use the output for teste

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.