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.
This commit is contained in:
Erik Brakkee 2024-08-18 11:44:16 +02:00
parent 9a5aaf56eb
commit 57c77e7d07

View File

@ -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"
@ -25,6 +26,7 @@ type WebSession struct {
func NewWebSessions(notifications chan *models.State) *WebSessions {
websessions := &WebSessions{
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()