/
persistence.go
78 lines (60 loc) · 1.58 KB
/
persistence.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package timer
import (
"bytes"
"context"
"encoding/gob"
"github.com/0xa1-red/empires-of-avalon/persistence/encoding"
"github.com/0xa1-red/empires-of-avalon/protobuf"
"github.com/asynkron/protoactor-go/cluster"
"google.golang.org/protobuf/types/known/structpb"
)
func (g *Grain) Encode() ([]byte, error) {
if g.timer.Amount == 0 {
return nil, nil
}
encode := make(map[string]interface{})
data := make(map[string]interface{})
data["timer"] = g.timer
encode["data"] = data
encode["identity"] = g.ctx.Identity()
buf := bytes.NewBuffer([]byte(""))
if err := encoding.Encode(data, buf); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func (g *Grain) Decode(b []byte) error {
m := make(map[string]interface{})
if err := encoding.Decode(b, m); err != nil {
return err
}
if m["timer"].(*Timer).Amount > 0 {
g.timer = m["timer"].(*Timer)
}
return nil
}
func (g *Grain) Kind() string {
return "timer"
}
func (g *Grain) Identity() string {
return g.ctx.Identity()
}
func (g *Grain) Restore(req *protobuf.RestoreRequest, ctx cluster.GrainContext) (*protobuf.RestoreResponse, error) {
if err := g.Decode(req.Data); err != nil {
return &protobuf.RestoreResponse{
Status: protobuf.Status_Error,
Error: err.Error(),
}, nil
}
g.startBuildingTimer(context.TODO())
g.startGenerateTimer(context.TODO())
g.startTransformTimer(context.TODO())
return &protobuf.RestoreResponse{
Status: protobuf.Status_OK,
Error: "",
}, nil
}
func init() {
gob.Register(&Timer{}) // nolint
gob.Register(&structpb.Value_StringValue{}) // nolint
}