Server

Server

The Server class is the main entry point for the server-side of a soundworks application.

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

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

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

await server.start();

According to the clients definitions provided in config.app.clients, the server will automatically create a dedicated route for each browser client role. For example, given the config object of the example above that defines two different client roles for browser targets (i.e. player and controller):

config.app.clients = {
  player: { target: 'browser', default: true },
  controller: { target: 'browser' },
}

The server will listen to the following URLs:

  • http://127.0.0.1:8000/ for the player role, which is defined as the default client.
  • http://127.0.0.1:8000/controller for the controller role.

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,
    subpath: '',
    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:
  • Raw Node.js http or https instance

Source:
See:

Raw Node.js http or https instance

(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 express router.

    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:
See:

Instance of the express router.

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 express from 'express';

// create the soundworks server instance
const server = new Server(config);

// 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

(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 informations 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:

    • create the audit state
    • prepapre http(s) server and routing according to the informations declared in config.app.clients
    • initialize all registered plugins

    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 implicitely

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 Number

Ip of the client

token String

Token to be tested

Returns:
Type
Boolean

onStatusChange(callback)

Description:
  • Register a callback to execute when status change

Source:
Parameters:
Name Type Description
callback function

setCustomApplicationTemplateOptions()

Description:
  • Define custom template path, template engine, and clientConfig function. This method is proposed for very advanced use-cases and should very probably be improved. If you consider using this for some reason, please get in touch first to explain your use-case :)

Source:

(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:

    • implicitely 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 usefull 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()

Description:
  • Configure the server to work out-of-the-box within the soundworks application template provided by `@soundworks/create.

    • uses template-literal package as html templateEngine
    • define .build/server/tmpl as the directory in which html template can be found
    • define the clientConfigFunction function that return client compliant config object to be injected in the html template.

    Also expose two public directory:

    • the public directory which is exposed behind the root path
    • the ./.build/public directory which is exposed behind the build path

    Note: except in very rare cases (so rare that they are quite difficult to imagine), you should rely on these defaults.

Source: