From 96a8e44773b1311220a4eed2590460da3afdcc63 Mon Sep 17 00:00:00 2001 From: Kevin Lin Date: Sun, 28 Jan 2024 09:58:39 -0800 Subject: [PATCH] backend: Single persistent global ping goroutine instead of per-session ticker --- backend/app/api/handlers/v1/controller.go | 44 ++++++++++------------- 1 file changed, 19 insertions(+), 25 deletions(-) diff --git a/backend/app/api/handlers/v1/controller.go b/backend/app/api/handlers/v1/controller.go index f4b547c..eb60212 100644 --- a/backend/app/api/handlers/v1/controller.go +++ b/backend/app/api/handlers/v1/controller.go @@ -154,31 +154,6 @@ func (ctrl *V1Controller) HandleCacheWS() errchain.HandlerFunc { m.HandleConnect(func(s *melody.Session) { auth := services.NewContext(s.Request.Context()) s.Set("gid", auth.GID) - - // Asynchronous ticker that keeps the websocket connection alive with periodic pings. - go func() { - const interval = 10 * time.Second - - ping := time.NewTicker(interval) - defer ping.Stop() - - for { - select { - case <-s.Request.Context().Done(): - return - - case <-ping.C: - msg := &eventMsg{Event: "ping"} - - pingBytes, err := json.Marshal(msg) - if err != nil { - log.Log().Msgf("error marshaling ping: %v", err) - } else { - _ = m.BroadcastMultiple(pingBytes, []*melody.Session{s}) - } - } - } - }() }) factory := func(e string) func(data any) { @@ -213,6 +188,25 @@ func (ctrl *V1Controller) HandleCacheWS() errchain.HandlerFunc { ctrl.bus.Subscribe(eventbus.EventLocationMutation, factory("location.mutation")) ctrl.bus.Subscribe(eventbus.EventItemMutation, factory("item.mutation")) + // Persistent asynchronous ticker that keeps all websocket connections alive with periodic pings. + go func() { + const interval = 10 * time.Second + + ping := time.NewTicker(interval) + defer ping.Stop() + + for range ping.C { + msg := &eventMsg{Event: "ping"} + + pingBytes, err := json.Marshal(msg) + if err != nil { + log.Log().Msgf("error marshaling ping: %v", err) + } else { + _ = m.Broadcast(pingBytes) + } + } + }() + return func(w http.ResponseWriter, r *http.Request) error { return m.HandleRequest(w, r) }