Server

Server

The Server class is the main entry point for soundworks server-side project.

The Server instance allows to access soundworks components such as ServerStateManager, ServerPluginManager, ServerSocket or ServerContextManager. Its is also responsible for handling the initialization lifecycle of the different soundworks components.

import { Server } from '@soundworks/core/server';

const server = new Server({
  app: {
    name: 'my-example-app',
    clients: {
      player: { runtime: 'browser', default: true },
      controller: { runtime: 'browser' },
      thing: { runtime: 'node' }
    },
  },
  env: {
    port: 8000,
  },
});

await server.start();

Constructor

new Server(config)

Source:
Parameters:
Name Type Description
config ServerConfig

Configuration object for the server.

Throws:
  • If config.app.clients is empty.
  • If a node client is defined but config.env.serverAddress is not defined.
  • if config.env.useHttps is true and config.env.httpsInfos is not null (which generates self signed certificated), config.env.httpsInfos.cert and config.env.httpsInfos.key should point to valid cert files.

Members

config :ServerConfig

Description:
  • Given config object merged with the following defaults:

Source:

Given config object merged with the following defaults:

Type:
Example
{
  env: {
    type: 'development',
    port: 8000,
    serverAddress: null,
    baseUrl: '',
    useHttps: false,
    httpsInfos: null,
    crossOriginIsolated: true,
    verbose: true,
  },
  app: {
    name: 'soundworks',
    clients: {},
  }
}

contextManager :ServerContextManager

Description:
Source:

Instance of the ServerContextManager class.

Type:

db

Description:
Source:

Simple key / value filesystem database with Promise based Map API.

Basically a tiny wrapper around the https://github.com/lukechilds/keyv package.

httpServer

Description:
  • Instance of the Node.js http.Server or https.Server

Source:
See:

Instance of the Node.js http.Server or https.Server

(readonly) id :number

Description:
  • Id of the server, a constant set to -1

Source:

Id of the server, a constant set to -1

Type:
  • number

pluginManager :ServerPluginManager

Description:
Source:

Instance of the ServerPluginManager class.

Type:

router

Description:
  • Instance of the router if any.

    The router can be used to open new route, for example to expose a directory of static assets (in default soundworks applications only the public is exposed).

Source:

Instance of the router if any.

The router can be used to open new route, for example to expose a directory of static assets (in default soundworks applications only the public is exposed).

Example
import { Server } from '@soundworks/core/server.js';
import { loadConfig, configureHttpRouter } from '@soundworks/helpers/server.js';

// create the server instance
const server = new Server(loadConfig());
// configure the express router provided by the helpers
configureHttpRouter(server);

// expose assets located in the `soundfiles` directory on the network
server.router.use('/soundfiles', express.static('soundfiles')));

sockets :ServerSockets

Description:
Source:

Instance of the ServerSockets class.

Type:

stateManager :ServerStateManager

Description:
Source:

Instance of the ServerStateManager class.

Type:

status :'idle'|'inited'|'started'|'errored'

Description:
  • Status of the server.

Source:

Status of the server.

Type:
  • 'idle' | 'inited' | 'started' | 'errored'

version :string

Description:
  • Package version.

Source:

Package version.

Type:
  • string

Methods

generateAuthToken()

Description:
  • Generate a token to secure client connection.

    The token should be passed to the client-side Client config object, it will be internally used to check the WebSocket connection and reject it if the token is invalid.

Source:

(async) getAuditState() → {Promise.<SharedState>}

Description:
  • Attach and retrieve the global audit state of the application.

    The audit state is a SharedState instance that keeps track of global information about the application such as, the number of connected clients, network latency estimation, etc.

    The audit state is created by the server on start up.

Source:
Example
const auditState = await server.getAuditState();
auditState.onUpdate(() => console.log(auditState.getValues()), true);
Throws:

Will throw if called before server.init()

Returns:
Type
Promise.<SharedState>

(async) init()

Description:
  • The init method is part of the initialization lifecycle of the soundworks server. Most of the time, the init method will be implicitly called by the Server#start method.

    In some situations you might want to call this method manually, in such cases the method should be called before the Server#start method.

    What it does:

    1. Create the audit state
    2. Create the HTTP(s) server
    3. Initialize registered plugins

    Between steps 2 and 3, the 'http-server-ready' event status is dispatched so that consumer code can register its router before plugin initialization:

    server.onStatusChange(status => {
      if (status === 'http-server-ready') {
        server.httpServer.on('request', router);
      }
    });
    

    After await server.init() is fulfilled, the Server#stateManager and all registered plugins can be safely used.

Source:
Example
const server = new Server(config);
await server.init();
await server.start();
// or implicitly called by start
const server = new Server(config);
await server.start(); // init is called implicitly

isTrustedClient(client) → {boolean}

Description:
  • Check if the given client is trusted, i.e. config.env.type == 'production' and the client is protected behind a password.

Source:
Parameters:
Name Type Description
client ServerClient

Client to be tested

Returns:
Type
boolean

isTrustedToken(clientId, clientIp, token) → {boolean}

Description:
  • Check if the token from a client is trusted, i.e. config.env.type == 'production' and the client is protected behind a password.

Source:
Parameters:
Name Type Description
clientId number

Id of the client

clientIp string

Ip of the client

token string

Token to be tested

Returns:
Type
boolean

onStatusChange(callback)

Description:
  • Register a callback to execute when status change.

    Status are dispatched in the following order:

    • 'http-server-ready'
    • 'inited'
    • 'started'
    • 'stopped' during the lifecycle of the server. If an error occurs the 'errored' status is propagated.
Source:
Parameters:
Name Type Description
callback function

(async) start()

Description:
  • The start method is part of the initialization lifecycle of the soundworks server. The start method will implicitly call the Server#init method if it has not been called manually.

    What it does:

    • implicitly call Server#init if not done manually
    • launch the HTTP and WebSocket servers
    • start all created contexts. To this end, you will have to call server.init manually and instantiate the contexts between server.init() and server.start()

    After await server.start() the server is ready to accept incoming connections

Source:
Example
import { Server } from '@soundworks/core/server.js'

const server = new Server(config);
await server.start();

(async) stop()

Description:
  • Stops all started contexts, plugins, close all the socket connections and the http(s) server.

    In most situations, you might not need to call this method. However, it can be useful for unit testing or similar situations where you want to create and delete several servers in the same process.

Source:
Example
import { Server } from '@soundworks/core/server.js'

const server = new Server(config);
await server.start();

await new Promise(resolve => setTimeout(resolve, 1000));
await server.stop();

useDefaultApplicationTemplate()

Source:
Deprecated:
  • Yes