-
-
Notifications
You must be signed in to change notification settings - Fork 523
/
passivation.go
68 lines (58 loc) · 1.22 KB
/
passivation.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
package plugin
import (
"log"
"time"
"github.com/AsynkronIT/protoactor-go/actor"
)
type PassivationAware interface {
Init(*actor.PID, time.Duration)
Reset(time.Duration)
Cancel()
}
type PassivationHolder struct {
timer *time.Timer
done bool
}
func (state *PassivationHolder) Reset(duration time.Duration) {
if state.timer == nil {
log.Fatalf("Cannot reset passivation of a non-started actor")
}
if !state.done {
state.timer.Reset(duration)
}
}
func (state *PassivationHolder) Init(pid *actor.PID, duration time.Duration) {
state.timer = time.NewTimer(duration)
state.done = false
go func() {
select {
case <-state.timer.C:
pid.Stop()
state.done = true
break
}
}()
}
func (state *PassivationHolder) Cancel() {
if state.timer != nil {
state.timer.Stop()
}
}
type PassivationPlugin struct {
Duration time.Duration
}
func (pp *PassivationPlugin) OnStart(ctx actor.Context) {
if a, ok := ctx.Actor().(PassivationAware); ok {
a.Init(ctx.Self(), pp.Duration)
}
}
func (pp *PassivationPlugin) OnOtherMessage(ctx actor.Context, msg interface{}) {
if p, ok := ctx.Actor().(PassivationAware); ok {
switch msg.(type) {
case *actor.Stopped:
p.Cancel()
default:
p.Reset(pp.Duration)
}
}
}