-
Notifications
You must be signed in to change notification settings - Fork 1
/
node_state.go
39 lines (29 loc) · 893 Bytes
/
node_state.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package rafting
import (
"encoding/json"
"github.com/hashicorp/raft"
)
type stateCommandFunc = func(data interface{}, args map[string]interface{}) (interface{}, error)
type State struct {
data interface{}
commands map[string]stateCommandFunc
marshalFn func(interface{}) ([]byte, error)
unmarshalFn func([]byte, interface{}) error
}
func NewState(data interface{}) *State {
return NewStateWithSerializer(data, json.Marshal, json.Unmarshal)
}
func NewStateWithSerializer(data interface{}, marshalFn func(interface{}) ([]byte, error), unmarshalFn func([]byte, interface{}) error) *State {
return &State{
data: data,
commands: make(map[string]stateCommandFunc),
marshalFn: marshalFn,
unmarshalFn: unmarshalFn,
}
}
func (s *State) Command(cmd string, handler stateCommandFunc) {
s.commands[cmd] = handler
}
func (s *State) FSM() raft.FSM {
return &fsm{s}
}