-
Notifications
You must be signed in to change notification settings - Fork 0
/
actor.go
56 lines (50 loc) · 1.29 KB
/
actor.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
package chat
import (
"github.com/charlesderek/actor-model/actor"
"github.com/charlesderek/actor-model/examples/mdns/chat/types"
"github.com/charlesderek/actor-model/examples/mdns/discovery"
"github.com/charlesderek/actor-model/log"
)
type server struct {
eventStream *actor.EventStream
subscription *actor.EventSub
ctx *actor.Context
}
func New(e *actor.EventStream) actor.Producer {
return func() actor.Receiver {
ret := &server{
eventStream: e,
}
return ret
}
}
func (s *server) Receive(ctx *actor.Context) {
switch msg := ctx.Message().(type) {
case actor.Initialized:
s.ctx = ctx
s.subscription = s.eventStream.Subscribe(s.onMessage)
case actor.Started:
_ = msg
case actor.Stopped:
s.shutdown()
case *types.Message:
s.handleMessage(ctx, msg)
}
}
func (s *server) onMessage(event any) {
switch evt := event.(type) {
case *discovery.DiscoveryEvent:
pid := actor.NewPID(evt.Addr[0], "chat")
s.ctx.Engine().Send(pid, &types.Message{
Username: evt.ID,
Msg: "hello",
})
}
}
func (s *server) shutdown() {
s.eventStream.Unsubscribe(s.subscription)
}
// handle the incoming message by broadcasting it to all connected clients.
func (s *server) handleMessage(ctx *actor.Context, msg *types.Message) {
log.Infow("new message", log.M{"msg": msg.Msg})
}