forked from topfreegames/pitaya
-
Notifications
You must be signed in to change notification settings - Fork 0
/
agent_remote.go
234 lines (210 loc) · 6.51 KB
/
agent_remote.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
// Copyright (c) nano Author and TFG Co. All Rights Reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
package agent
import (
"context"
"net"
"reflect"
"github.com/golang/protobuf/proto"
"github.com/topfreegames/pitaya/cluster"
"github.com/topfreegames/pitaya/conn/codec"
"github.com/topfreegames/pitaya/conn/message"
"github.com/topfreegames/pitaya/conn/packet"
"github.com/topfreegames/pitaya/constants"
"github.com/topfreegames/pitaya/logger"
"github.com/topfreegames/pitaya/protos"
"github.com/topfreegames/pitaya/route"
"github.com/topfreegames/pitaya/serialize"
"github.com/topfreegames/pitaya/session"
"github.com/topfreegames/pitaya/util"
)
// Remote corresponding to another server
type Remote struct {
Session *session.Session // session
chDie chan struct{} // wait for close
messageEncoder message.Encoder
encoder codec.PacketEncoder // binary encoder
frontendID string // the frontend that sent the request
reply string // nats reply topic
rpcClient cluster.RPCClient // rpc client
serializer serialize.Serializer // message serializer
serviceDiscovery cluster.ServiceDiscovery // service discovery
}
// NewRemote create new Remote instance
func NewRemote(
sess *protos.Session,
reply string,
rpcClient cluster.RPCClient,
encoder codec.PacketEncoder,
serializer serialize.Serializer,
serviceDiscovery cluster.ServiceDiscovery,
frontendID string,
messageEncoder message.Encoder,
) (*Remote, error) {
a := &Remote{
chDie: make(chan struct{}),
reply: reply, // TODO this is totally coupled with NATS
serializer: serializer,
encoder: encoder,
rpcClient: rpcClient,
serviceDiscovery: serviceDiscovery,
frontendID: frontendID,
messageEncoder: messageEncoder,
}
// binding session
s := session.New(a, false, sess.GetUid())
s.SetFrontendData(frontendID, sess.GetId())
err := s.SetDataEncoded(sess.GetData())
if err != nil {
return nil, err
}
a.Session = s
return a, nil
}
// Kick kicks the user
func (a *Remote) Kick(ctx context.Context) error {
if a.Session.UID() == "" {
return constants.ErrNoUIDBind
}
b, err := proto.Marshal(&protos.KickMsg{
UserId: a.Session.UID(),
})
if err != nil {
return err
}
_, err = a.SendRequest(ctx, a.frontendID, constants.KickRoute, b)
return err
}
// Push pushes the message to the user
func (a *Remote) Push(route string, v interface{}) error {
if (reflect.TypeOf(a.rpcClient) == reflect.TypeOf(&cluster.NatsRPCClient{}) &&
a.Session.UID() == "") {
return constants.ErrNoUIDBind
}
switch d := v.(type) {
case []byte:
logger.Log.Debugf("Type=Push, ID=%d, UID=%d, Route=%s, Data=%dbytes",
a.Session.ID(), a.Session.UID(), route, len(d))
default:
logger.Log.Debugf("Type=Push, ID=%d, UID=%d, Route=%s, Data=%+v",
a.Session.ID(), a.Session.UID(), route, v)
}
sv, err := a.serviceDiscovery.GetServer(a.frontendID)
if err != nil {
return err
}
return a.sendPush(
pendingMessage{typ: message.Push, route: route, payload: v},
a.Session.UID(), sv,
)
}
// ResponseMID reponds the message with mid to the user
func (a *Remote) ResponseMID(ctx context.Context, mid uint, v interface{}, isError ...bool) error {
err := false
if len(isError) > 0 {
err = isError[0]
}
if mid <= 0 {
return constants.ErrSessionOnNotify
}
switch d := v.(type) {
case []byte:
logger.Log.Debugf("Type=Response, ID=%d, MID=%d, Data=%dbytes",
a.Session.ID(), mid, len(d))
default:
logger.Log.Infof("Type=Response, ID=%d, MID=%d, Data=%+v",
a.Session.ID(), mid, v)
}
return a.send(pendingMessage{ctx: ctx, typ: message.Response, mid: mid, payload: v, err: err}, a.reply)
}
// Close closes the remote
func (a *Remote) Close() error { return nil }
// RemoteAddr returns the remote address of the user
func (a *Remote) RemoteAddr() net.Addr { return nil }
func (a *Remote) serialize(m pendingMessage) ([]byte, error) {
payload, err := util.SerializeOrRaw(a.serializer, m.payload)
if err != nil {
return nil, err
}
// construct message and encode
msg := &message.Message{
Type: m.typ,
Data: payload,
Route: m.route,
ID: m.mid,
Err: m.err,
}
em, err := a.messageEncoder.Encode(msg)
if err != nil {
return nil, err
}
// packet encode
p, err := a.encoder.Encode(packet.Data, em)
if err != nil {
return nil, err
}
return p, err
}
func (a *Remote) send(m pendingMessage, to string) (err error) {
p, err := a.serialize(m)
if err != nil {
return err
}
res := &protos.Response{
Data: p,
}
bt, err := proto.Marshal(res)
if err != nil {
return err
}
return a.rpcClient.Send(to, bt)
}
func (a *Remote) sendPush(m pendingMessage, userID string, sv *cluster.Server) (err error) {
payload, err := util.SerializeOrRaw(a.serializer, m.payload)
if err != nil {
return err
}
push := &protos.Push{
Route: m.route,
Uid: a.Session.UID(),
Data: payload,
}
return a.rpcClient.SendPush(userID, sv, push)
}
// SendRequest sends a request to a server
func (a *Remote) SendRequest(ctx context.Context, serverID, reqRoute string, v interface{}) (*protos.Response, error) {
r, err := route.Decode(reqRoute)
if err != nil {
return nil, err
}
payload, err := util.SerializeOrRaw(a.serializer, v)
if err != nil {
return nil, err
}
msg := &message.Message{
Route: reqRoute,
Data: payload,
}
server, err := a.serviceDiscovery.GetServer(serverID)
if err != nil {
return nil, err
}
return a.rpcClient.Call(ctx, protos.RPCType_User, r, nil, msg, server)
}