From 57c77e7d0790725367ea2db15130ad71485b90a8 Mon Sep 17 00:00:00 2001 From: Erik Brakkee Date: Sun, 18 Aug 2024 11:44:16 +0200 Subject: [PATCH] initial state is now sent again when the websocket connection is established. Also throttling based on user input. When browser sends multiple messages per second the user will still only get one notification per second at most. --- pkg/server/ui/websessions.go | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/pkg/server/ui/websessions.go b/pkg/server/ui/websessions.go index 8fac497..0075ee8 100644 --- a/pkg/server/ui/websessions.go +++ b/pkg/server/ui/websessions.go @@ -3,6 +3,7 @@ package ui import ( "context" "git.wamblee.org/converge/pkg/models" + "git.wamblee.org/converge/pkg/support/throttling" "log" "net" "net/http" @@ -24,7 +25,8 @@ type WebSession struct { func NewWebSessions(notifications chan *models.State) *WebSessions { websessions := &WebSessions{ - sessions: make(map[*WebSession]bool), + sessions: make(map[*WebSession]bool), + lastNotification: models.NewState(), } go func() { @@ -76,7 +78,16 @@ func (sessions *WebSessions) NewSession(wsConnection net.Conn, ctx context.Conte conn: wsConnection, ctx: ctx, } + + // initial notification as soon as client connects. go func() { + session.notifications <- sessions.lastNotification + }() + + go func() { + throttler := throttling.NewAsyncThrottler(func(state *models.State) { + session.notifications <- state + }, time.Second, time.Second) for { // the web app opens one websocket connection and sends a hello // message asking for the latest state when a page is loaded that requires this. @@ -84,7 +95,7 @@ func (sessions *WebSessions) NewSession(wsConnection net.Conn, ctx context.Conte p := make([]byte, 1024) _, err := wsConnection.Read(p) if err == nil { - session.notifications <- sessions.lastNotification + throttler.Notify(sessions.lastNotification) } else { log.Printf("Got error reading %v", err) cancel()