-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
438 lines (371 loc) · 9.99 KB
/
server.go
File metadata and controls
438 lines (371 loc) · 9.99 KB
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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
package redkit
import (
"bufio"
"context"
"crypto/tls"
"fmt"
"io"
"net"
"strings"
"sync"
"time"
)
func NewServer(address string) *Server {
config := DefaultServerConfig()
config.Address = address
return NewServerWithConfig(config)
}
func NewServerWithConfig(config *ServerConfig) *Server {
if config == nil {
config = DefaultServerConfig()
}
ctx, cancel := context.WithCancel(context.Background())
if config.Logger == nil {
config.Logger = NewDefaultLogger(nil, LogLevelInfo)
}
server := &Server{
Address: config.Address,
TLSConfig: config.TLSConfig,
ReadTimeout: config.ReadTimeout,
WriteTimeout: config.WriteTimeout,
IdleTimeout: config.IdleTimeout,
IdleCheckFrequency: config.IdleCheckFrequency,
MaxConnections: config.MaxConnections,
Logger: config.Logger,
ConnStateHook: config.ConnStateHook,
handlers: &sync.Map{},
middlewareChain: NewMiddlewareChain(),
activeConns: &sync.Map{},
ctx: ctx,
cancel: cancel,
}
server.registerDefaultHandlers()
server.startIdleChecker()
return server
}
// RegisterCommand registers a command handler
func (s *Server) RegisterCommand(name string, handler CommandHandler) error {
if name == "" {
return fmt.Errorf("empty command name")
}
if handler == nil {
return fmt.Errorf("nil handler for command '%s'", name)
}
s.handlers.Store(strings.ToUpper(name), handler)
return nil
}
// RegisterCommandFunc registers a function as a command handler
func (s *Server) RegisterCommandFunc(name string, handler func(*Connection, *Command) RedisValue) error {
if name == "" {
return fmt.Errorf("empty command name")
}
if handler == nil {
return fmt.Errorf("nil handler function for command '%s'", name)
}
return s.RegisterCommand(name, CommandHandlerFunc(handler))
}
// Use adds a middleware to the server's middleware chain
func (s *Server) Use(middleware Middleware) {
s.middlewareChain.Add(middleware)
}
// UseFunc adds a middleware function to the server's middleware chain
func (s *Server) UseFunc(fn func(*Connection, *Command, CommandHandler) RedisValue) {
s.Use(MiddlewareFunc(fn))
}
// Listen starts listening on the configured address
func (s *Server) Listen() error {
var err error
if s.TLSConfig != nil {
s.listener, err = tls.Listen("tcp", s.Address, s.TLSConfig)
} else {
s.listener, err = net.Listen("tcp", s.Address)
}
if err != nil {
return fmt.Errorf("failed to listen on %s: %w", s.Address, err)
}
s.Logger.Info("Server listening on %s", s.Address)
return nil
}
// Serve starts accepting connections (blocking)
func (s *Server) Serve() error {
if s.listener == nil {
if err := s.Listen(); err != nil {
return err
}
}
defer s.listener.Close()
for {
// Check shutdown before accepting
if s.inShutdown.Load() {
return nil
}
conn, err := s.listener.Accept()
if err != nil {
if s.inShutdown.Load() {
return nil
}
s.Logger.Error("Accept error: %v", err)
continue
}
shouldHandle := true
if s.MaxConnections > 0 {
for {
current := s.connCount.Load()
if current >= int64(s.MaxConnections) {
conn.Close()
s.Logger.Warn("Connection limit reached, rejecting connection from %s", conn.RemoteAddr())
shouldHandle = false
break
}
if s.connCount.CompareAndSwap(current, current+1) {
break
}
}
} else {
s.connCount.Add(1)
}
if shouldHandle {
s.wg.Add(1)
go func(netConn net.Conn) {
defer func() {
s.wg.Done()
s.connCount.Add(-1)
}()
s.handleConnectionInternal(netConn)
}(conn)
}
}
}
// Shutdown gracefully shuts down the server
func (s *Server) Shutdown(ctx context.Context) error {
s.inShutdown.Store(true)
s.cancel()
// Close listener
if s.listener != nil {
err := s.listener.Close()
if err != nil {
return err
}
}
// Close all active connections
var conns []*Connection
s.activeConns.Range(func(key, value interface{}) bool {
if conn, ok := key.(*Connection); ok {
conns = append(conns, conn)
}
return true
})
var firstErr error
for _, conn := range conns {
if err := conn.Close(); err != nil && firstErr == nil {
firstErr = err
s.Logger.Warn("Error closing connection during shutdown: %v", err)
}
}
// Run shutdown hooks
s.mu.Lock()
for _, fn := range s.onShutdown {
fn()
}
s.mu.Unlock()
// Wait for all connections to finish
done := make(chan struct{})
go func() {
s.wg.Wait()
close(done)
}()
select {
case <-ctx.Done():
return ctx.Err()
case <-done:
return firstErr
}
}
// handleConnectionInternal handles a single client connection
func (s *Server) handleConnectionInternal(netConn net.Conn) {
defer func() {
if r := recover(); r != nil {
s.Logger.Error("PANIC in connection handler: %v", r)
}
}()
ctx, cancel := context.WithCancel(s.ctx)
defer cancel()
conn := &Connection{
conn: netConn,
reader: bufio.NewReader(netConn),
writer: bufio.NewWriter(netConn),
server: s,
ctx: ctx,
cancel: cancel,
}
conn.lastUsed.Store(time.Now().UnixNano())
conn.setState(StateNew)
s.activeConns.Store(conn, struct{}{})
defer func() {
conn.Close()
s.activeConns.Delete(conn)
}()
conn.setState(StateActive)
s.Logger.Debug("New connection from %s", netConn.RemoteAddr())
for {
select {
case <-ctx.Done():
return
default:
}
if s.ReadTimeout > 0 {
if err := netConn.SetReadDeadline(time.Now().Add(s.ReadTimeout)); err != nil {
s.Logger.Error("Failed to set read deadline: %v", err)
return
}
}
cmd, err := conn.readCommand()
if err != nil {
errStr := err.Error()
if err == io.EOF || strings.Contains(errStr, "use of closed network connection") {
s.Logger.Debug("Connection closed by %s", netConn.RemoteAddr())
} else {
s.Logger.Error("Error reading command from %s: %v", netConn.RemoteAddr(), err)
}
return
}
conn.UpdateLastUsed()
s.Logger.Debug("Command from %s: %s %v", netConn.RemoteAddr(), cmd.Name, cmd.Args)
conn.setState(StateProcessing)
response := s.handleCommand(conn, cmd)
conn.setState(StateActive)
if s.WriteTimeout > 0 {
err := netConn.SetWriteDeadline(time.Now().Add(s.WriteTimeout))
if err != nil {
return
}
}
if err := conn.writeValue(response); err != nil {
if strings.Contains(err.Error(), "use of closed network connection") {
s.Logger.Debug("Connection closed while writing to %s", netConn.RemoteAddr())
} else {
s.Logger.Error("Error writing response to %s: %v", netConn.RemoteAddr(), err)
}
return
}
if err := conn.writer.Flush(); err != nil {
if strings.Contains(err.Error(), "use of closed network connection") {
s.Logger.Debug("Connection closed while flushing to %s", netConn.RemoteAddr())
} else {
s.Logger.Error("Error flushing response to %s: %v", netConn.RemoteAddr(), err)
}
return
}
// Check if connection should be closed after response (e.g., QUIT command)
if conn.ShouldClose() {
s.Logger.Debug("Closing connection as requested by %s", netConn.RemoteAddr())
return
}
}
}
// handleCommand processes a Redis command
func (s *Server) handleCommand(conn *Connection, cmd *Command) (result RedisValue) {
defer func() {
if r := recover(); r != nil {
s.Logger.Error("PANIC in command handler '%s': %v", cmd.Name, r)
result = RedisValue{
Type: ErrorReply,
Str: fmt.Sprintf("ERR internal error: panic in handler '%s'", cmd.Name),
}
}
}()
if cmd == nil || cmd.Name == "" {
return RedisValue{
Type: ErrorReply,
Str: "ERR empty command",
}
}
handlerVal, exists := s.handlers.Load(strings.ToUpper(cmd.Name))
if !exists {
return RedisValue{
Type: ErrorReply,
Str: fmt.Sprintf("ERR unknown command '%s'", cmd.Name),
}
}
handler, ok := handlerVal.(CommandHandler)
if !ok {
return RedisValue{
Type: ErrorReply,
Str: fmt.Sprintf("ERR invalid handler for command '%s'", cmd.Name),
}
}
// Execute through middleware chain
return s.middlewareChain.Execute(conn, cmd, handler)
}
// OnShutdown registers a function to call on shutdown
func (s *Server) OnShutdown(f func()) {
s.mu.Lock()
defer s.mu.Unlock()
s.onShutdown = append(s.onShutdown, f)
}
// GetActiveConnections returns the number of active connections
func (s *Server) GetActiveConnections() int64 {
return s.connCount.Load()
}
// IsShutdown returns whether the server is shutting down
func (s *Server) IsShutdown() bool {
return s.inShutdown.Load()
}
// TriggerIdleCheck manually triggers idle connection checking
func (s *Server) TriggerIdleCheck() {
s.checkIdleConnections()
}
// startIdleChecker starts a background goroutine to check for idle connections
func (s *Server) startIdleChecker() {
go func() {
checkInterval := s.IdleCheckFrequency
if checkInterval <= 0 {
checkInterval = 30 * time.Second
}
ticker := time.NewTicker(checkInterval)
defer ticker.Stop()
for {
select {
case <-s.ctx.Done():
return
case <-ticker.C:
s.checkIdleConnections()
}
}
}()
}
// checkIdleConnections checks all active connections for idle timeout
func (s *Server) checkIdleConnections() {
if s.IdleTimeout <= 0 {
return // Idle timeout disabled
}
now := time.Now()
idleThreshold := now.Add(-s.IdleTimeout)
var connsToCheck []*Connection
s.activeConns.Range(func(key, value interface{}) bool {
if conn, ok := key.(*Connection); ok {
connsToCheck = append(connsToCheck, conn)
}
return true
})
// Check each connection for idle timeout
var idleConns []*Connection
for _, conn := range connsToCheck {
lastUsed := conn.GetLastUsed()
currentState := ConnState(conn.state.Load())
if (currentState == StateActive || currentState == StateIdle) && lastUsed.Before(idleThreshold) {
idleConns = append(idleConns, conn)
}
}
for _, conn := range idleConns {
s.Logger.Info("Closing idle connection %s", conn.RemoteAddr())
conn.Close()
}
}
// setConnectionActive sets a connection to active state
func (s *Server) setConnectionActive(conn *Connection) {
currentState := ConnState(conn.state.Load())
if currentState == StateIdle {
conn.setState(StateActive)
}
}