-
Notifications
You must be signed in to change notification settings - Fork 1
/
node_fsm.go
60 lines (45 loc) · 1.08 KB
/
node_fsm.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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package rafting
import (
"bytes"
"fmt"
"io"
"github.com/hashicorp/raft"
)
var _ raft.FSM = (*fsm)(nil)
type fsm struct {
state *State
}
func (f *fsm) Apply(log *raft.Log) interface{} {
var cmd command
if err := f.state.unmarshalFn(log.Data, &cmd); err != nil {
return fmt.Errorf(`state.unmarshalFn(...): %w`, err)
}
if handler, ok := f.state.commands[cmd.Name]; ok {
result, err := handler(f.state.data, cmd.Args)
if err != nil {
return err
}
return result
}
return ErrInvalidCommand
}
func (f *fsm) Snapshot() (raft.FSMSnapshot, error) {
return &fsmSnapshot{func() ([]byte, error) {
b, err := f.state.marshalFn(f.state.data)
if err != nil {
return nil, fmt.Errorf(`state.marshalFn(...): %w`, err)
}
return b, nil
}}, nil
}
func (f *fsm) Restore(rc io.ReadCloser) error {
defer rc.Close()
buf := new(bytes.Buffer)
if _, err := buf.ReadFrom(rc); err != nil {
return fmt.Errorf(`buf.ReadFrom(...): %w`, err)
}
if err := f.state.unmarshalFn(buf.Bytes(), &f.state.data); err != nil {
return fmt.Errorf(`state.unmarshalFn(...): %w`, err)
}
return nil
}