|
| 1 | +package websocket |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "errors" |
| 6 | + "fmt" |
| 7 | + "net/http" |
| 8 | + "sync" |
| 9 | + "time" |
| 10 | +) |
| 11 | + |
| 12 | +// Grace enables graceful shutdown of accepted WebSocket connections. |
| 13 | +// |
| 14 | +// Use Handler to wrap WebSocket handlers to record accepted connections |
| 15 | +// and then use Close or Shutdown to gracefully close these connections. |
| 16 | +// |
| 17 | +// Grace is intended to be used in harmony with net/http.Server's Shutdown and Close methods. |
| 18 | +type Grace struct { |
| 19 | + mu sync.Mutex |
| 20 | + closing bool |
| 21 | + conns map[*Conn]struct{} |
| 22 | +} |
| 23 | + |
| 24 | +// Handler returns a handler that wraps around h to record |
| 25 | +// all WebSocket connections accepted. |
| 26 | +// |
| 27 | +// Use Close or Shutdown to gracefully close recorded connections. |
| 28 | +func (g *Grace) Handler(h http.Handler) http.Handler { |
| 29 | + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 30 | + ctx := context.WithValue(r.Context(), gracefulContextKey{}, g) |
| 31 | + r = r.WithContext(ctx) |
| 32 | + h.ServeHTTP(w, r) |
| 33 | + }) |
| 34 | +} |
| 35 | + |
| 36 | +func (g *Grace) isClosing() bool { |
| 37 | + g.mu.Lock() |
| 38 | + defer g.mu.Unlock() |
| 39 | + return g.closing |
| 40 | +} |
| 41 | + |
| 42 | +func graceFromRequest(r *http.Request) *Grace { |
| 43 | + g, _ := r.Context().Value(gracefulContextKey{}).(*Grace) |
| 44 | + return g |
| 45 | +} |
| 46 | + |
| 47 | +func (g *Grace) addConn(c *Conn) error { |
| 48 | + g.mu.Lock() |
| 49 | + defer g.mu.Unlock() |
| 50 | + if g.closing { |
| 51 | + c.Close(StatusGoingAway, "server shutting down") |
| 52 | + return errors.New("server shutting down") |
| 53 | + } |
| 54 | + if g.conns == nil { |
| 55 | + g.conns = make(map[*Conn]struct{}) |
| 56 | + } |
| 57 | + g.conns[c] = struct{}{} |
| 58 | + c.g = g |
| 59 | + return nil |
| 60 | +} |
| 61 | + |
| 62 | +func (g *Grace) delConn(c *Conn) { |
| 63 | + g.mu.Lock() |
| 64 | + defer g.mu.Unlock() |
| 65 | + delete(g.conns, c) |
| 66 | +} |
| 67 | + |
| 68 | +type gracefulContextKey struct{} |
| 69 | + |
| 70 | +// Close prevents the acceptance of new connections with |
| 71 | +// http.StatusServiceUnavailable and closes all accepted |
| 72 | +// connections with StatusGoingAway. |
| 73 | +func (g *Grace) Close() error { |
| 74 | + g.mu.Lock() |
| 75 | + g.closing = true |
| 76 | + var wg sync.WaitGroup |
| 77 | + for c := range g.conns { |
| 78 | + wg.Add(1) |
| 79 | + go func(c *Conn) { |
| 80 | + defer wg.Done() |
| 81 | + c.Close(StatusGoingAway, "server shutting down") |
| 82 | + }(c) |
| 83 | + |
| 84 | + delete(g.conns, c) |
| 85 | + } |
| 86 | + g.mu.Unlock() |
| 87 | + |
| 88 | + wg.Wait() |
| 89 | + |
| 90 | + return nil |
| 91 | +} |
| 92 | + |
| 93 | +// Shutdown prevents the acceptance of new connections and waits until |
| 94 | +// all connections close. If the context is cancelled before that, it |
| 95 | +// calls Close to close all connections immediately. |
| 96 | +func (g *Grace) Shutdown(ctx context.Context) error { |
| 97 | + defer g.Close() |
| 98 | + |
| 99 | + g.mu.Lock() |
| 100 | + g.closing = true |
| 101 | + g.mu.Unlock() |
| 102 | + |
| 103 | + // Same poll period used by net/http. |
| 104 | + t := time.NewTicker(500 * time.Millisecond) |
| 105 | + defer t.Stop() |
| 106 | + for { |
| 107 | + if g.zeroConns() { |
| 108 | + return nil |
| 109 | + } |
| 110 | + |
| 111 | + select { |
| 112 | + case <-t.C: |
| 113 | + case <-ctx.Done(): |
| 114 | + return fmt.Errorf("failed to shutdown WebSockets: %w", ctx.Err()) |
| 115 | + } |
| 116 | + } |
| 117 | +} |
| 118 | + |
| 119 | +func (g *Grace) zeroConns() bool { |
| 120 | + g.mu.Lock() |
| 121 | + defer g.mu.Unlock() |
| 122 | + return len(g.conns) == 0 |
| 123 | +} |
0 commit comments