forked from asynkron/protoactor-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
88 lines (74 loc) · 2.25 KB
/
main.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
79
80
81
82
83
84
85
86
87
88
package main
import (
"log"
"strconv"
"github.com/AsynkronIT/goconsole"
"github.com/AsynkronIT/protoactor-go/actor"
"github.com/AsynkronIT/protoactor-go/persistence"
)
type Provider struct {
providerState persistence.ProviderState
}
func NewProvider(snapshotInterval int) *Provider {
return &Provider{
providerState: persistence.NewInMemoryProvider(snapshotInterval),
}
}
func (p *Provider) InitState(actorName string, eventNum, eventIndexAfterSnapshot int) {
for i := 0; i < eventNum; i++ {
p.providerState.PersistEvent(
actorName,
i,
&Message{protoMsg: protoMsg{state: "state" + strconv.Itoa(i)}},
)
}
p.providerState.PersistSnapshot(
actorName,
eventIndexAfterSnapshot,
&Snapshot{protoMsg: protoMsg{state: "state" + strconv.Itoa(eventIndexAfterSnapshot-1)}},
)
}
func (p *Provider) GetState() persistence.ProviderState {
return p.providerState
}
type protoMsg struct{ state string }
func (p *protoMsg) Reset() {}
func (p *protoMsg) String() string { return p.state }
func (p *protoMsg) ProtoMessage() {}
type Message struct{ protoMsg }
type Snapshot struct{ protoMsg }
type Actor struct {
persistence.Mixin
state string
}
func (a *Actor) Receive(ctx actor.Context) {
switch msg := ctx.Message().(type) {
case *actor.Started:
log.Println("actor started")
case *persistence.RequestSnapshot:
log.Printf("snapshot internal state '%v'", a.state)
a.PersistSnapshot(&Snapshot{protoMsg: protoMsg{state: a.state}})
case *Snapshot:
a.state = msg.state
log.Printf("recovered from snapshot, internal state changed to '%v'", a.state)
case *persistence.ReplayComplete:
log.Printf("replay completed, internal state changed to '%v'", a.state)
case *Message:
scenario := "received replayed event"
if !a.Recovering() {
a.PersistReceive(msg)
scenario = "received new message"
}
a.state = msg.state
log.Printf("%s, internal state changed to '%v'\n", scenario, a.state)
}
}
func main() {
provider := NewProvider(3)
provider.InitState("persistent", 4, 3)
props := actor.FromInstance(&Actor{}).WithMiddleware(persistence.Using(provider))
pid, _ := actor.SpawnNamed(props, "persistent")
pid.Tell(&Message{protoMsg: protoMsg{state: "state4"}})
pid.Tell(&Message{protoMsg: protoMsg{state: "state5"}})
console.ReadLine()
}