2020-10-04 03:46:29 +00:00
|
|
|
package server
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"sync"
|
2021-01-10 01:22:39 +00:00
|
|
|
|
|
|
|
"github.com/google/uuid"
|
2020-10-04 03:46:29 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type WebsocketBag struct {
|
2020-11-08 21:52:20 +00:00
|
|
|
mu sync.Mutex
|
2020-10-04 03:46:29 +00:00
|
|
|
conns map[uuid.UUID]*context.CancelFunc
|
|
|
|
}
|
|
|
|
|
2021-08-02 21:07:00 +00:00
|
|
|
// Websockets returns the websocket bag which contains all the currently open websocket connections
|
2020-10-04 03:46:29 +00:00
|
|
|
// for the server instance.
|
|
|
|
func (s *Server) Websockets() *WebsocketBag {
|
|
|
|
s.wsBagLocker.Lock()
|
|
|
|
defer s.wsBagLocker.Unlock()
|
|
|
|
|
|
|
|
if s.wsBag == nil {
|
|
|
|
s.wsBag = &WebsocketBag{}
|
|
|
|
}
|
|
|
|
|
|
|
|
return s.wsBag
|
|
|
|
}
|
|
|
|
|
2021-08-02 21:07:00 +00:00
|
|
|
// Push adds a new websocket connection to the end of the stack.
|
2020-10-04 03:46:29 +00:00
|
|
|
func (w *WebsocketBag) Push(u uuid.UUID, cancel *context.CancelFunc) {
|
|
|
|
w.mu.Lock()
|
|
|
|
defer w.mu.Unlock()
|
|
|
|
|
|
|
|
if w.conns == nil {
|
|
|
|
w.conns = make(map[uuid.UUID]*context.CancelFunc)
|
|
|
|
}
|
|
|
|
|
|
|
|
w.conns[u] = cancel
|
|
|
|
}
|
|
|
|
|
2021-08-02 21:07:00 +00:00
|
|
|
// Remove removes a connection from the stack.
|
2020-10-04 03:46:29 +00:00
|
|
|
func (w *WebsocketBag) Remove(u uuid.UUID) {
|
|
|
|
w.mu.Lock()
|
|
|
|
delete(w.conns, u)
|
|
|
|
w.mu.Unlock()
|
|
|
|
}
|
|
|
|
|
2021-09-12 18:14:00 +00:00
|
|
|
// CancelAll cancels all the stored cancel functions which has the effect of
|
|
|
|
// disconnecting every listening websocket for the server.
|
2020-10-04 03:46:29 +00:00
|
|
|
func (w *WebsocketBag) CancelAll() {
|
|
|
|
w.mu.Lock()
|
2021-09-12 18:14:00 +00:00
|
|
|
defer w.mu.Unlock()
|
2020-10-04 03:46:29 +00:00
|
|
|
|
|
|
|
if w.conns != nil {
|
|
|
|
for _, cancel := range w.conns {
|
2021-10-24 23:14:00 +00:00
|
|
|
(*cancel)()
|
2020-10-04 03:46:29 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Reset the connections.
|
|
|
|
w.conns = make(map[uuid.UUID]*context.CancelFunc)
|
2020-11-08 21:52:20 +00:00
|
|
|
}
|