StateManager

server. StateManager

The StateManager allows to create new server.SharedStates, or attach to server.SharedStates created by other nodes (clients or server). It can also track all the server.SharedStates created by other nodes.

An instance of StateManager is automatically created by the soundworks.Server at initialization (cf. server.Server#stateManager).

Compared to the client.StateManager, the server.StateManager can also create and delete schemas, as well as register update hook that are executed when a state is updated.

See server.Server#stateManager

Tutorial: https://soundworks.dev/guide/state-manager.html

// server-side
import { Server } from '@soundworks/server/index.js';

const server = new Server(config);
// declare and register the schema of a shared state.
server.stateManager.registerSchema('some-global-state', {
  myRandom: {
    type: 'float',
    default: 0,
  }
});

await server.start();

// create a global state server-side
const globalState = await server.stateManager.create('some-global-state');
// listen and react to the changes made by the clients
globalState.onUpdate(updates => console.log(updates));
// client-side
import { Client } from '@soundworks/client.index.js';

const client = new Client(config);
await client.start();

// attach to the global state created by the server
const globalState = await client.stateManager.attach('some-global-state');

// update the value of a `myRandom` parameter every seconds
setInterval(() => {
  globalState.set({ myRandom: Math.random() });
}, 1000);

Extends

Methods

(async) attach(schemaName, stateIdopt) → {client.SharedState|server.SharedState}

Description:
  • Attach to an existing SharedState instance.

Source:
Overrides:
See:
Example
const state = await client.stateManager.attach('my-schema');
Parameters:
Name Type Attributes Default Description
schemaName String

Name of the schema as given on registration (cf. ServerStateManager)

stateId Object <optional>
null

Id of the state to attach to. If null, attach to the first state found with the given schema name (usefull for globally shared states owned by the server).

Returns:
Type
client.SharedState | server.SharedState

(async) create(schemaName, initValuesopt) → {client.SharedState|server.SharedState}

Description:
  • Create a SharedState instance from a registered schema.

Source:
Overrides:
See:
Example
const state = await client.stateManager.create('my-schema');
Parameters:
Name Type Attributes Default Description
schemaName String

Name of the schema as given on registration (cf. ServerStateManager)

initValues Object <optional>
{}

Default values for the state.

Returns:
Type
client.SharedState | server.SharedState

deleteSchema(schemaName)

Description:
  • Delete a schema and all associated states.

    When a schema is deleted, all states created from this schema are deleted as well, therefore all attached clients are detached and the onDetach and onDelete callbacks are called on the related states.

Source:
Parameters:
Name Type Description
schemaName string

Name of the schema.

(async) getCollection(schemaName, options) → {server.SharedStateCollection|client.SharedStateCollection}

Description:
  • Returns a collection of all the states created from the schema name.

Source:
Overrides:
Parameters:
Name Type Description
schemaName string

Name of the schema.

options object

Options.

Properties
Name Type Attributes Default Description
excludeLocal boolean <optional>
false

If set to true, exclude states created locallly, i.e. by the same node, from the collection.

Returns:
Type
server.SharedStateCollection | client.SharedStateCollection

(async) getSchema(schemaName)

Description:
  • Return the schema from a given registered schema name

Source:
Overrides:
Example
const schema = await client.stateManager.getSchema('my-schema');
Parameters:
Name Type Description
schemaName String

Name of the schema as given on registration (cf. ServerStateManager)

(async) observe(schemaNameopt, callback, options) → {Promise.<function()>}

Description:
  • Observe all the SharedState instances that are created on the network. This can be usefull for clients with some controller role that might want to track the state of all other clients of the application, to monitor them and/or take control over them from a single point.

    Notes:

    • The order of execution is not guaranted between nodes, i.e. an state attached in the observe callback could be created before the async create method resolves.
    • Filtering, i.e. observedSchemaName and options.excludeLocal are handled on the node side, the server just notify all state creation activity and the node executes the given callbacks according to the different filter rules. Such strategy allows to share the observe notifications between all observers.

    Alternative signatures:

    • .observe(callback)
    • .observe(schemaName, callback)
    • .observe(callback, options)
    • .observe(schemaName, callback, options)
Source:
Overrides:
Example
client.stateManager.observe(async (schemaName, stateId) => {
  if (schemaName === 'something') {
    const state = await this.client.stateManager.attach(schemaName, stateId);
    console.log(state.getValues());
  }
});
Parameters:
Name Type Attributes Description
schemaName string <optional>

optionnal schema name to filter the observed states.

callback server.StateManager~ObserveCallback | client.StateManager~ObserveCallback

Function to be called when a new state is created on the network.

options object

Options.

Properties
Name Type Attributes Default Description
excludeLocal boolean <optional>
false

If set to true, exclude states created locallly, i.e. by the same node, from the collection.

Returns:
  • Returns a Promise that resolves when the given callback as been executed on each existing states. The promise value is a function which allows to stop observing the states on the network.
Type
Promise.<function()>

registerSchema(schemaName, schema)

Description:
  • Register a schema from which shared states (cf. common.SharedState) can be instanciated.

Source:
See:
Example
server.stateManager.registerSchema('my-schema', {
  myBoolean: {
    type: 'boolean'
    default: false,
  },
  myFloat: {
    type: 'float'
    default: 0.1,
    min: -1,
    max: 1
  }
})
Parameters:
Name Type Description
schemaName string

Name of the schema.

schema server.StateManager~schema

Data structure describing the states that will be created from this schema.

registerUpdateHook(schemaName, updateHook) → {Fuction}

Description:
  • Register a function for a given schema (e.g. will be applied on all states created from this schema) that will be executed before the update values are propagated. For example, this could be used to implement a preset system where all the values of the state are updated from e.g. some data stored in filesystem while the consumer of the state only want to update the preset name.

    The hook is associated to every state of its kind (i.e. schemaName) and executed on every update (call of set). Note that the hooks are executed server-side regarless the node on which set has been called and before the "actual" update of the state (e.g. before the call of onUpdate).

Source:
Example
server.stateManager.registerSchema('hooked', {
  name: { type: 'string', default: null, nullable: true },
  name: { numUpdates: 'integer', default: 0 },
});
server.stateManager.registerUpdateHook('hooked', updates => {
  return {
    ...updates
    numUpdates: currentValues.numUpdates + 1,
  };
});

const state = await server.stateManager.create('hooked');

await state.set({ name: 'test' });
const values = state.getValues();
assert.deepEqual(result, { name: 'test', numUpdates: 1 });
Parameters:
Name Type Description
schemaName string

Kind of states on which applying the hook.

updateHook server.StateManager~updateHook

Function called between the set call and the actual update.

Returns:

deleteHook - Handler that deletes the hook when executed.

Type
Fuction

Type Definitions

(async) ObserveCallback(schemaName, stateId, nodeId)

Source:
Parameters:
Name Type Description
schemaName string

name of the schema

stateId number

id of the state

nodeId number

id of the node that created the state

schema

Description:
Source:

Description of a schema to be registered by the server.StateManager#registerSchema

A schema is the blueprint, or definition from which shared states can be created.

It consists of a set of key / value pairs where the key is the name of the parameter, and the value is an object describing the parameter.

The value can be of any of the foolowing types:

Type:
  • object
Example
const mySchema = {
  triggerSound: {
    type: 'boolean',
    event: true,
  },
  volume: {
    type: 'float'
    default: 0,
    min: -80,
    max: 6,
  }
};

server.stateManager.registerSchema('my-schema-name', mySchema);

schemaAnyDefinition

Description:
  • Describe a server.StateManager~schema entry of "any" type.

    Note that the any type always return a shallow copy of the state internal value. Mutating the returned value will therefore not modify the internal state.

Source:
Properties:
Name Type Attributes Default Description
type string <optional>
'any'

Parameter of any type.

default *

Default value of the parameter.

nullable boolean <optional>
false

Define if the parameter is nullable. If set to true the parameter default is set to null.

event boolean <optional>
false

Define if the parameter is a volatile, e.g. set its value back to null after propagation. When true, nullable is automatically set to true and default to null.

filterChange boolean <optional>
true

Setting this option to false forces the propagation of a parameter even when its value do not change. It offers a kind of middle ground between the default bahavior (e.g. where only changed values are propagated) and the behavior of the event option (which has no state per se). As such, setting this options to false if event=true does not make sens.

immediate boolean <optional>
false

Setting this option to true will trigger any change (e.g. call the onUpdate listeners) immediately on the state that generate the update (i.e. calling set), before propagating the change on the network. This option can be usefull in cases the network would introduce a noticeable latency on the client. If for some reason the value is overriden server-side (e.g. in an updateHook) the listeners will be called again on when the "real" / final value will be received.

metas object <optional>
{}

Optionnal metadata of the parameter.

Describe a server.StateManager~schema entry of "any" type.

Note that the any type always return a shallow copy of the state internal value. Mutating the returned value will therefore not modify the internal state.

Type:
  • object

schemaBooleanDefinition

Description:
Source:
Properties:
Name Type Attributes Default Description
type string 'boolean'

Define a boolean parameter.

default boolean

Default value of the parameter.

nullable boolean <optional>
false

Define if the parameter is nullable. If set to true the parameter default is set to null.

event boolean <optional>
false

Define if the parameter is a volatile, e.g. set its value back to null after propagation. When true, nullable is automatically set to true and default to null.

filterChange boolean <optional>
true

Setting this option to false forces the propagation of a parameter even when its value do not change. It offers a kind of middle ground between the default bahavior (e.g. where only changed values are propagated) and the behavior of the event option (which has no state per se). As such, setting this options to false if event=true does not make sens.

immediate boolean <optional>
false

Setting this option to true will trigger any change (e.g. call the onUpdate listeners) immediately on the state that generate the update (i.e. calling set), before propagating the change on the network. This option can be usefull in cases the network would introduce a noticeable latency on the client. If for some reason the value is overriden server-side (e.g. in an updateHook) the listeners will be called again on when the "real" / final value will be received.

metas object <optional>
{}

Optionnal metadata of the parameter.

Describe a server.StateManager~schema entry of "boolean" type.

Type:
  • object

schemaEnumDefinition

Description:
Source:
Properties:
Name Type Attributes Default Description
type string <optional>
'enum'

Enum parameter.

default string

Default value of the parameter.

list Array

Possible values of the parameter.

nullable boolean <optional>
false

Define if the parameter is nullable. If set to true the parameter default is set to null.

event boolean <optional>
false

Define if the parameter is a volatile, e.g. set its value back to null after propagation. When true, nullable is automatically set to true and default to null.

filterChange boolean <optional>
true

Setting this option to false forces the propagation of a parameter even when its value do not change. It offers a kind of middle ground between the default bahavior (e.g. where only changed values are propagated) and the behavior of the event option (which has no state per se). As such, setting this options to false if event=true does not make sens.

immediate boolean <optional>
false

Setting this option to true will trigger any change (e.g. call the onUpdate listeners) immediately on the state that generate the update (i.e. calling set), before propagating the change on the network. This option can be usefull in cases the network would introduce a noticeable latency on the client. If for some reason the value is overriden server-side (e.g. in an updateHook) the listeners will be called again on when the "real" / final value will be received.

metas object <optional>
{}

Optionnal metadata of the parameter.

Describe a server.StateManager~schema entry of "enum" type.

Type:
  • object

schemaFloatDefinition

Description:
Source:
Properties:
Name Type Attributes Default Description
type string <optional>
'float'

Float parameter.

default number

Default value.

min number <optional>
-Infinity

Minimum value.

max number <optional>
+Infinity

Maximum value.

nullable boolean <optional>
false

Define if the parameter is nullable. If set to true the parameter default is set to null.

event boolean <optional>
false

Define if the parameter is a volatile, e.g. set its value back to null after propagation. When true, nullable is automatically set to true and default to null.

filterChange boolean <optional>
true

Setting this option to false forces the propagation of a parameter even when its value do not change. It offers a kind of middle ground between the default bahavior (e.g. where only changed values are propagated) and the behavior of the event option (which has no state per se). As such, setting this options to false if event=true does not make sens.

immediate boolean <optional>
false

Setting this option to true will trigger any change (e.g. call the onUpdate listeners) immediately on the state that generate the update (i.e. calling set), before propagating the change on the network. This option can be usefull in cases the network would introduce a noticeable latency on the client. If for some reason the value is overriden server-side (e.g. in an updateHook) the listeners will be called again on when the "real" / final value will be received.

metas object <optional>
{}

Optionnal metadata of the parameter.

Describe a server.StateManager~schema entry of "float" type.

Type:
  • object

schemaIntegerDefinition

Description:
Source:
Properties:
Name Type Attributes Default Description
type string 'integer'

Define a boolean parameter.

default number

Default value of the parameter.

min number <optional>
-Infinity

Minimum value of the parameter.

max number <optional>
+Infinity

Maximum value of the parameter.

nullable boolean <optional>
false

Define if the parameter is nullable. If set to true the parameter default is set to null.

event boolean <optional>
false

Define if the parameter is a volatile, e.g. set its value back to null after propagation. When true, nullable is automatically set to true and default to null.

filterChange boolean <optional>
true

Setting this option to false forces the propagation of a parameter even when its value do not change. It offers a kind of middle ground between the default bahavior (e.g. where only changed values are propagated) and the behavior of the event option (which has no state per se). As such, setting this options to false if event=true does not make sens.

immediate boolean <optional>
false

Setting this option to true will trigger any change (e.g. call the onUpdate listeners) immediately on the state that generate the update (i.e. calling set), before propagating the change on the network. This option can be usefull in cases the network would introduce a noticeable latency on the client. If for some reason the value is overriden server-side (e.g. in an updateHook) the listeners will be called again on when the "real" / final value will be received.

metas object <optional>
{}

Optionnal metadata of the parameter.

Describe a server.StateManager~schema entry of "integer" type.

Type:
  • object

schemaStringDefinition

Description:
Source:
Properties:
Name Type Attributes Default Description
type string 'string'

Define a boolean parameter.

default string

Default value of the parameter.

nullable boolean <optional>
false

Define if the parameter is nullable. If set to true the parameter default is set to null.

event boolean <optional>
false

Define if the parameter is a volatile, e.g. set its value back to null after propagation. When true, nullable is automatically set to true and default to null.

filterChange boolean <optional>
true

Setting this option to false forces the propagation of a parameter even when its value do not change. It offers a kind of middle ground between the default bahavior (e.g. where only changed values are propagated) and the behavior of the event option (which has no state per se). As such, setting this options to false if event=true does not make sens.

immediate boolean <optional>
false

Setting this option to true will trigger any change (e.g. call the onUpdate listeners) immediately on the state that generate the update (i.e. calling set), before propagating the change on the network. This option can be usefull in cases the network would introduce a noticeable latency on the client. If for some reason the value is overriden server-side (e.g. in an updateHook) the listeners will be called again on when the "real" / final value will be received.

metas object <optional>
{}

Optionnal metadata of the parameter.

Describe a server.StateManager~schema entry of "string" type.

Type:
  • object

(async) updateHook(updates, currentValues, contextopt) → {object}

Source:
Parameters:
Name Type Attributes Default Description
updates object

Update object as given on a set callback, or result of the previous hook

currentValues object

Current values of the state.

context object <optional>
null

Optionnal context passed by the creator of the update.

Returns:

The "real" updates to be applied on the state.

Type
object