forked from valyala/fastrpc
-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.go
401 lines (346 loc) · 10.1 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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
package fastrpc
import (
"bufio"
"fmt"
"github.com/valyala/fasthttp"
"io"
"log"
"net"
"os"
"strings"
"sync"
"sync/atomic"
"time"
)
// HandlerCtx is an interface implementing context passed to Server.Handler
type HandlerCtx interface {
// ConcurrencyLimitError must set the response
// to 'concurrency limit exceeded' error.
ConcurrencyLimitError(concurrency int)
// Init must prepare ctx for reading the next request.
Init(conn net.Conn, logger fasthttp.Logger)
// ReadRequest must read request from br.
ReadRequest(br *bufio.Reader) error
// WriteResponse must write response to bw.
WriteResponse(bw *bufio.Writer) error
}
// Server accepts rpc requests from Client.
type Server struct {
// NewHandlerCtx must return new HandlerCtx
NewHandlerCtx func() HandlerCtx
// Handler must process incoming requests.
//
// The handler must return either ctx passed to the call
// or new non-nil ctx.
//
// The handler may return ctx passed to the call only if the ctx
// is no longer used after returning from the handler.
// Otherwise new ctx must be returned.
Handler func(ctx HandlerCtx) HandlerCtx
Handshake func(conn net.Conn) (net.Conn, error)
HandshakeTimeout time.Duration
// Concurrency is the maximum number of concurrent goroutines
// with Server.Handler the server may run.
//
// DefaultConcurrency is used by default.
Concurrency int
// MaxBatchDelay is the maximum duration before ready responses
// are sent to the client.
//
// Responses' batching may reduce network bandwidth usage and CPU usage.
//
// By default responses are sent immediately to the client.
MaxBatchDelay time.Duration
// Maximum duration for reading the full request (including body).
//
// This also limits the maximum lifetime for idle connections.
//
// By default request read timeout is unlimited.
ReadTimeout time.Duration
// Maximum duration for writing the full response (including body).
//
// By default response write timeout is unlimited.
WriteTimeout time.Duration
// ReadBufferSize is the size for read buffer.
//
// DefaultReadBufferSize is used by default.
ReadBufferSize int
// WriteBufferSize is the size for write buffer.
//
// DefaultWriteBufferSize is used by default.
WriteBufferSize int
// Logger, which is used by the Server.
//
// Standard logger from log package is used by default.
Logger fasthttp.Logger
// PipelineRequests enables requests' pipelining.
//
// Requests from a single client are processed serially
// if is set to true.
//
// Enabling requests' pipelining may be useful in the following cases:
//
// - if requests from a single client must be processed serially;
// - if the Server.Handler doesn't block and maximum throughput
// must be achieved for requests' processing.
//
// By default requests from a single client are processed concurrently.
PipelineRequests bool
workItemPool sync.Pool
concurrencyCount uint32
}
func (s *Server) concurrency() int {
concurrency := s.Concurrency
if concurrency <= 0 {
concurrency = DefaultConcurrency
}
return concurrency
}
// Serve serves rpc requests accepted from the given listener.
func (s *Server) Serve(ln net.Listener) error {
if s.Handler == nil {
panic("BUG: Server.Handler must be set")
}
concurrency := s.concurrency()
pipelineRequests := s.PipelineRequests
for {
conn, err := ln.Accept()
if err != nil {
if conn != nil {
panic("BUG: net.Listener returned non-nil conn and non-nil error")
}
if netErr, ok := err.(net.Error); ok && netErr.Temporary() {
s.logger().Printf("fastrpc.Server: temporary error when accepting new connections: %s", netErr)
time.Sleep(time.Second)
continue
}
if err != io.EOF && !strings.Contains(err.Error(), "use of closed network connection") {
s.logger().Printf("fastrpc.Server: permanent error when accepting new connections: %s", err)
return err
}
return nil
}
if conn == nil {
panic("BUG: net.Listener returned (nil, nil)")
}
if pipelineRequests {
n := int(atomic.AddUint32(&s.concurrencyCount, 1))
if n > concurrency {
atomic.AddUint32(&s.concurrencyCount, ^uint32(0))
s.logger().Printf("fastrpc.Server: concurrency limit exceeded: %d", concurrency)
continue
}
}
go func() {
laddr := conn.LocalAddr().String()
raddr := conn.RemoteAddr().String()
if err := s.serveConn(conn); err != nil {
s.logger().Printf("fastrpc.Server: error on connection %q<->%q: %s", laddr, raddr, err)
}
if pipelineRequests {
atomic.AddUint32(&s.concurrencyCount, ^uint32(0))
}
}()
}
}
func (s *Server) serveConn(conn net.Conn) error {
realConn, br, bw, err := newBufioConn(conn, s.ReadBufferSize, s.WriteBufferSize, s.Handshake, s.HandshakeTimeout)
if err != nil {
conn.Close()
return err
}
conn = realConn
stopCh := make(chan struct{})
pendingResponses := make(chan *serverWorkItem, s.concurrency())
readerDone := make(chan error, 1)
go func() {
readerDone <- s.connReader(br, conn, pendingResponses, stopCh)
}()
writerDone := make(chan error, 1)
go func() {
writerDone <- s.connWriter(bw, conn, pendingResponses, stopCh)
}()
select {
case err = <-readerDone:
conn.Close()
close(stopCh)
<-writerDone
case err = <-writerDone:
conn.Close()
close(stopCh)
<-readerDone
}
return err
}
func (s *Server) connReader(br *bufio.Reader, conn net.Conn, pendingResponses chan<- *serverWorkItem, stopCh <-chan struct{}) error {
logger := s.logger()
concurrency := s.concurrency()
pipelineRequests := s.PipelineRequests
readTimeout := s.ReadTimeout
var lastReadDeadline time.Time
for {
wi := s.acquireWorkItem()
if readTimeout > 0 {
// Optimization: update read deadline only if more than 25%
// of the last read deadline exceeded.
// See https://github.com/golang/go/issues/15133 for details.
t := coarseTimeNow()
if t.Sub(lastReadDeadline) > (readTimeout >> 2) {
if err := conn.SetReadDeadline(t.Add(readTimeout)); err != nil {
// do not panic here, since the error may
// indicate that the connection is already closed
return fmt.Errorf("cannot update read deadline: %s", err)
}
lastReadDeadline = t
}
}
if n, err := io.ReadFull(br, wi.nonce[:]); err != nil {
if n == 0 {
// Ignore error if no bytes are read, since
// the client may just close the connection.
return nil
}
return fmt.Errorf("cannot read request ID: %s", err)
}
wi.ctx.Init(conn, logger)
if err := wi.ctx.ReadRequest(br); err != nil {
return fmt.Errorf("cannot read request: %s", err)
}
if pipelineRequests {
s.handleRequest(wi, pendingResponses, stopCh)
} else {
n := int(atomic.AddUint32(&s.concurrencyCount, 1))
if n > concurrency {
atomic.AddUint32(&s.concurrencyCount, ^uint32(0))
wi.ctx.ConcurrencyLimitError(concurrency)
if !pushPendingResponse(pendingResponses, wi, stopCh) {
return nil
}
continue
}
go func(wi *serverWorkItem) {
s.handleRequest(wi, pendingResponses, stopCh)
atomic.AddUint32(&s.concurrencyCount, ^uint32(0))
}(wi)
}
}
}
func (s *Server) handleRequest(wi *serverWorkItem, pendingResponses chan<- *serverWorkItem, stopCh <-chan struct{}) {
nonce, ctxNew := wi.nonce, s.Handler(wi.ctx)
if isZeroNonce(nonce) {
if ctxNew == wi.ctx {
s.releaseWorkItem(wi)
}
return
}
if ctxNew != wi.ctx {
if ctxNew == nil {
panic("BUG: Server.Handler mustn't return nil")
}
wi = s.acquireWorkItem()
wi.nonce = nonce
wi.ctx = ctxNew
}
pushPendingResponse(pendingResponses, wi, stopCh)
}
func pushPendingResponse(pendingResponses chan<- *serverWorkItem, wi *serverWorkItem, stopCh <-chan struct{}) bool {
select {
case pendingResponses <- wi:
default:
select {
case pendingResponses <- wi:
case <-stopCh:
return false
}
}
return true
}
func (s *Server) connWriter(bw *bufio.Writer, conn net.Conn, pendingResponses <-chan *serverWorkItem, stopCh <-chan struct{}) error {
var wi *serverWorkItem
var (
flushTimer = getFlushTimer()
flushCh <-chan time.Time
flushAlwaysCh = make(chan time.Time)
)
defer putFlushTimer(flushTimer)
close(flushAlwaysCh)
maxBatchDelay := s.MaxBatchDelay
if maxBatchDelay < 0 {
maxBatchDelay = 0
}
writeTimeout := s.WriteTimeout
var lastWriteDeadline time.Time
for {
select {
case wi = <-pendingResponses:
default:
select {
case wi = <-pendingResponses:
case <-stopCh:
return nil
case <-flushCh:
if err := bw.Flush(); err != nil {
return fmt.Errorf("cannot flush response data to client: %s", err)
}
flushCh = nil
continue
}
}
if writeTimeout > 0 {
// Optimization: update write deadline only if more than 25%
// of the last write deadline exceeded.
// See https://github.com/golang/go/issues/15133 for details.
t := coarseTimeNow()
if t.Sub(lastWriteDeadline) > (writeTimeout >> 2) {
if err := conn.SetWriteDeadline(t.Add(writeTimeout)); err != nil {
// do not panic here, since the error may
// indicate that the connection is already closed
return fmt.Errorf("cannot update write deadline: %s", err)
}
lastWriteDeadline = t
}
}
if _, err := bw.Write(wi.nonce[:]); err != nil {
return fmt.Errorf("cannot write response ID: %s", err)
}
if err := wi.ctx.WriteResponse(bw); err != nil {
return fmt.Errorf("cannot write response: %s", err)
}
s.releaseWorkItem(wi)
// re-arm flush channel
if flushCh == nil && len(pendingResponses) == 0 {
if maxBatchDelay > 0 {
resetFlushTimer(flushTimer, maxBatchDelay)
flushCh = flushTimer.C
} else {
flushCh = flushAlwaysCh
}
}
}
}
type serverWorkItem struct {
ctx HandlerCtx
nonce [4]byte
}
func (s *Server) acquireWorkItem() *serverWorkItem {
v := s.workItemPool.Get()
if v == nil {
return &serverWorkItem{
ctx: s.NewHandlerCtx(),
}
}
return v.(*serverWorkItem)
}
func (s *Server) releaseWorkItem(wi *serverWorkItem) {
s.workItemPool.Put(wi)
}
var defaultLogger = log.New(os.Stderr, "", log.LstdFlags)
func (s *Server) logger() fasthttp.Logger {
if s.Logger != nil {
return s.Logger
}
return defaultLogger
}
func isZeroNonce(nonce [4]byte) bool {
return nonce[0] == 0 && nonce[1] == 0 && nonce[2] == 0 && nonce[3] == 0
}