-
Notifications
You must be signed in to change notification settings - Fork 1
/
keeper.go
68 lines (57 loc) · 1.09 KB
/
keeper.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 etp
import (
"context"
"github.com/txix-open/etp/v4/internal"
"github.com/txix-open/etp/v4/msg"
)
type keeper struct {
conn *Conn
mux *mux
}
func newKeeper(conn *Conn, mux *mux) *keeper {
return &keeper{
conn: conn,
mux: mux,
}
}
func (k *keeper) Serve(ctx context.Context) {
k.mux.handleConnect(k.conn)
for {
err := k.readAndHandleMessage(ctx)
if err != nil {
k.mux.handleDisconnect(k.conn, err)
return
}
}
}
func (k *keeper) readAndHandleMessage(ctx context.Context) error {
_, data, err := k.conn.ws.Read(ctx)
if err != nil {
return err
}
event, err := msg.UnmarshalEvent(data)
if err != nil {
k.mux.onError(k.conn, err)
return nil
}
if internal.IsAckEvent(event.Name) {
k.conn.notifyAck(event.AckId, event.Data)
return nil
}
go func() {
response := k.mux.handle(ctx, k.conn, event)
if !event.IsAckRequired() {
return
}
message := msg.Event{
Name: internal.ToAckEvent(event.Name),
AckId: event.AckId,
Data: response,
}
err := k.conn.emit(ctx, message)
if err != nil {
k.mux.onError(k.conn, err)
}
}()
return nil
}