Interface RaftStateMachine

Users of the RaftController have to implement a RaftStateMachine and provide an instance of it in the RaftControllerOptions when bootstrapping the controller. The provided state machine will be used internally to describe the state shared between all agents with corresponding RaftControllers.

A call to RaftController.propose() will trigger this.processInput() after the input has been committed. After that the state is retrieved with this.getState() and then used to resolve the promise returned by the initial RaftController.propose() call.

A typical RaftStateMachine implementation keeps track of some form of state (e.g. a variable of type Map) and defines how inputs affect this state inside processInput(). getState() and setState() are used to access the tracked state.

An example RaftStateMachine implementation of a key value store looks like this:

class KVStateMachine implements RaftStateMachine {
private _state = new Map<string, string>();

processInput(input: RaftData) {
if (input.type === "set") {
// Add or update key value pair
this._state.set(input.key, input.value);
} else if (input.type === "delete") {
// Delete key value pair
this._state.delete(input.key);
}
}

getState(): RaftData {
// Convert from Map to JSON compatible object
return Array.from(this._state);
}

setState(state: RaftData): void {
// Convert from JSON compatible object to Map
this._state = new Map(state);
}
}

// Propose an input object of this type to set or update a key value pair
type KVSet = { type: "set"; key: string; value: string };

// Propose an input object of this type to delete a key value pair
type KVDelete = { type: "delete"; key: string };

Hierarchy

  • RaftStateMachine

Methods

  • Gets this RaftStateMachines internal state. This function should convert the state tracked inside this state machine (e.g. with one or multiple variables) into RaftData and return it. The returned state is used to resolve the promise returned by RaftController.propose() and to provide the values for RaftController.getState() and RaftController.observeState().

    Returns any

    This RaftStateMachine's internal state. Must be of type RaftData.

    Remark

    getState() and setState() are counterparts. Setting the state of one state machine instance to the state of another one (SM1.setState(SM2.getState())) should result in both state machines representing the exact same state and behaving exactly the same regarding new state machine inputs.

  • Sets this RaftStateMachines internal state. This function should use the provided state to set the state tracked inside this state machine. The structure of the provided state is implicitly defined inside getState(). See remarks of getState().

    Parameters

    • state: any

      The state this state machine should be set to. Is of type RaftData.

    Returns void

Generated using TypeDoc