forked from porthos-rpc/porthos-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
283 lines (224 loc) · 6.16 KB
/
server.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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
package porthos
import (
"sync"
"time"
"github.com/porthos-rpc/porthos-go/log"
"github.com/streadway/amqp"
)
// MethodHandler represents a rpc method handler.
type MethodHandler func(req Request, res Response)
// Server is used to register procedures to be invoked remotely.
type Server interface {
// Register a method and its handler.
Register(method string, handler MethodHandler)
// Register a method and its handler.
RegisterWithSpec(method string, handler MethodHandler, spec Spec)
// AddExtension adds extensions to the server instance.
// Extensions can be used to add custom actions to incoming and outgoing RPC calls.
AddExtension(ext Extension)
// ListenAndServe start serving RPC requests.
ListenAndServe()
// GetServiceName returns the name of this service.
GetServiceName() string
// GetSpecs returns all registered specs.
GetSpecs() map[string]Spec
// Close the client and AMQP channel.
// This method returns right after the AMQP channel is closed.
// In order to give time to the current request to finish (if there's one)
// it's up to you to wait using the NotifyClose.
Close()
// Shutdown shuts down the client and AMQP channel.
// It provider graceful shutdown, since it will wait the result
// of <-s.NotifyClose().
Shutdown()
// NotifyClose returns a channel to be notified then this server closes.
NotifyClose() <-chan bool
}
type server struct {
m sync.Mutex
broker *Broker
serviceName string
channel *amqp.Channel
requestChannel <-chan amqp.Delivery
methods map[string]MethodHandler
specs map[string]Spec
autoAck bool
extensions []Extension
topologySet bool
closed bool
closes []chan bool
}
// Options represent all the options supported by the server.
type Options struct {
AutoAck bool
}
var servePollInterval = 500 * time.Millisecond
// NewServer creates a new instance of Server, responsible for executing remote calls.
func NewServer(b *Broker, serviceName string, options Options) (Server, error) {
s := &server{
broker: b,
serviceName: serviceName,
methods: make(map[string]MethodHandler),
specs: make(map[string]Spec),
autoAck: options.AutoAck,
}
err := s.setupTopology()
if err != nil {
return nil, err
}
go s.handleReestablishedConnnection()
return s, nil
}
func (s *server) setupTopology() error {
s.m.Lock()
defer s.m.Unlock()
var err error
s.channel, err = s.broker.openChannel()
if err != nil {
return err
}
// create the response queue (let the amqp server to pick a name for us)
_, err = s.channel.QueueDeclare(
s.serviceName, // name
true, // durable
false, // delete when usused
false, // exclusive
false, // noWait
nil, // arguments
)
if err != nil {
s.channel.Close()
return err
}
s.requestChannel, err = s.channel.Consume(
s.serviceName, // queue
"", // consumer
s.autoAck, // auto-ack
false, // exclusive
false, // no-local
false, // no-wait
nil, // args
)
if err != nil {
s.channel.Close()
return err
}
s.topologySet = true
return nil
}
func (s *server) handleReestablishedConnnection() {
notifyCh := s.broker.NotifyReestablish()
for !s.closed {
<-notifyCh
err := s.setupTopology()
if err != nil {
log.Error("Error setting up topology after reconnection [%s]", err)
}
}
}
func (s *server) serve() {
for !s.closed {
if s.topologySet {
s.pipeThroughServerListeningExtensions()
s.printRegisteredMethods()
log.Info("Connected to the broker and waiting for incoming rpc requests...")
for d := range s.requestChannel {
go s.processRequest(d)
}
s.topologySet = false
} else {
time.Sleep(servePollInterval)
}
}
for _, c := range s.closes {
c <- true
}
}
func (s *server) printRegisteredMethods() {
log.Info("[%s]", s.serviceName)
for method := range s.methods {
log.Info(". %s", method)
}
}
func (s *server) processRequest(d amqp.Delivery) {
methodName := d.Headers["X-Method"].(string)
if method, ok := s.methods[methodName]; ok {
req := &request{s.serviceName, methodName, d.ContentType, d.Body}
ch, err := s.broker.openChannel()
if err != nil {
log.Error("Error opening channel for response: '%s'", err)
}
defer ch.Close()
resWriter := &responseWriter{delivery: d, channel: ch, autoAck: s.autoAck}
res := newResponse()
method(req, res)
err = resWriter.Write(res)
if err != nil {
log.Error("Error writing response: '%s'", err.Error())
}
} else {
log.Error("Method '%s' not found.", methodName)
if !s.autoAck {
d.Reject(false)
}
}
}
func (s *server) pipeThroughServerListeningExtensions() {
for _, ext := range s.extensions {
ext.ServerListening(s)
}
}
func (s *server) pipeThroughIncomingExtensions(req Request) {
for _, ext := range s.extensions {
ext.IncomingRequest(req)
}
}
func (s *server) pipeThroughOutgoingExtensions(req Request, res Response, responseTime time.Duration) {
for _, ext := range s.extensions {
ext.OutgoingResponse(req, res, responseTime, res.GetStatusCode())
}
}
func (s *server) Register(method string, handler MethodHandler) {
s.methods[method] = func(req Request, res Response) {
s.pipeThroughIncomingExtensions(req)
started := time.Now()
// invoke the registered function.
handler(req, res)
s.pipeThroughOutgoingExtensions(req, res, time.Since(started))
}
}
func (s *server) RegisterWithSpec(method string, handler MethodHandler, spec Spec) {
s.Register(method, handler)
s.specs[method] = spec
}
// GetServiceName returns the name of this service.
func (s *server) GetServiceName() string {
return s.serviceName
}
// GetSpecs returns all registered specs.
func (s *server) GetSpecs() map[string]Spec {
return s.specs
}
func (s *server) AddExtension(ext Extension) {
s.extensions = append(s.extensions, ext)
}
func (s *server) ListenAndServe() {
s.serve()
}
func (s *server) Close() {
s.closed = true
s.channel.Close()
}
func (s *server) Shutdown() {
ch := make(chan bool)
go func() {
ch <- <-s.NotifyClose()
}()
s.Close()
<-ch
}
func (s *server) NotifyClose() <-chan bool {
receiver := make(chan bool)
s.closes = append(s.closes, receiver)
return receiver
}