package systems
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/blang/semver"
"github.com/fxamacker/cbor/v2"
"github.com/henrygd/beszel/internal/common"
esystem "github.com/henrygd/beszel/internal/entities/system"
"github.com/henrygd/beszel/internal/hub/ws"
"github.com/lxzan/gws"
"github.com/stretchr/testify/require"
)
type slowDataClient struct {
gws.BuiltinEventHandler
release chan struct{}
}
func (c *slowDataClient) OnMessage(conn *gws.Conn, message *gws.Message) {
defer message.Close()
var req common.HubRequest[cbor.RawMessage]
if err := cbor.Unmarshal(message.Bytes(), &req); err != nil || req.Action != common.GetData {
return
}
<-c.release
response, _ := cbor.Marshal(common.AgentResponse{Id: req.Id, SystemData: &esystem.CombinedData{}})
_ = conn.WriteMessage(gws.OpcodeBinary, response)
}
func TestFetchDataTimeoutKeepsWebSocketOpen(t *testing.T) {
originalTimeout := wsDataRequestTimeout
wsDataRequestTimeout = 50 * time.Millisecond
t.Cleanup(func() { wsDataRequestTimeout = originalTimeout })
connections := make(chan *ws.WsConn, 1)
upgrader := gws.NewUpgrader(&monitorSyncServer{}, nil)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r)
if err != nil {
t.Error(err)
return
}
wsConn := ws.NewWsConnection(conn, semver.MustParse("0.20.0"))
conn.Session().Store("wsConn", wsConn)
connections <- wsConn
conn.ReadLoop()
}))
t.Cleanup(server.Close)
client := &slowDataClient{release: make(chan struct{})}
conn, _, err := gws.NewClient(client, &gws.ClientOption{Addr: "ws" + strings.TrimPrefix(server.URL, "http")})
require.NoError(t, err)
t.Cleanup(func() { _ = conn.NetConn().Close() })
go conn.ReadLoop()
var sys *System
select {
case wsConn := <-connections:
sys = &System{WsConn: wsConn}
case <-time.After(3 * time.Second):
t.Fatal("websocket connection was not established")
}
_, err = sys.fetchDataFromAgent(common.DataRequestOptions{})
require.ErrorIs(t, err, context.DeadlineExceeded)
require.True(t, sys.WsConn.IsConnected(), "a slow collection must not close the connection")
close(client.release)
_, err = sys.fetchDataFromAgent(common.DataRequestOptions{})
require.NoError(t, err)
}
type pingCountingClient struct {
gws.BuiltinEventHandler
pings chan struct{}
}
func (c *pingCountingClient) OnPing(conn *gws.Conn, payload []byte) {
_ = conn.WritePong(payload)
select {
case c.pings <- struct{}{}:
default:
}
}
func (c *pingCountingClient) OnMessage(conn *gws.Conn, message *gws.Message) {
message.Close()
}
func TestUpdatePingsAgentAfterFailedFetch(t *testing.T) {
originalTimeout := wsDataRequestTimeout
wsDataRequestTimeout = 50 * time.Millisecond
t.Cleanup(func() { wsDataRequestTimeout = originalTimeout })
connections := make(chan *ws.WsConn, 1)
upgrader := gws.NewUpgrader(&monitorSyncServer{}, nil)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r)
if err != nil {
t.Error(err)
return
}
wsConn := ws.NewWsConnection(conn, semver.MustParse("0.20.0"))
conn.Session().Store("wsConn", wsConn)
connections <- wsConn
conn.ReadLoop()
}))
t.Cleanup(server.Close)
client := &pingCountingClient{pings: make(chan struct{}, 4)}
conn, _, err := gws.NewClient(client, &gws.ClientOption{Addr: "ws" + strings.TrimPrefix(server.URL, "http")})
require.NoError(t, err)
t.Cleanup(func() { _ = conn.NetConn().Close() })
go conn.ReadLoop()
var sys *System
select {
case wsConn := <-connections:
sys = &System{WsConn: wsConn}
case <-time.After(3 * time.Second):
t.Fatal("websocket connection was not established")
}
err = sys.update()
require.ErrorIs(t, err, context.DeadlineExceeded, "the fetch is expected to time out")
select {
case <-client.pings:
case <-time.After(3 * time.Second):
t.Fatal("a failed fetch must ping the agent to keep the connection alive")
}
require.True(t, sys.WsConn.IsConnected(), "the connection must survive a failed fetch")
}
type silentAfterFirstPollAgent struct {
gws.BuiltinEventHandler
answered atomic.Bool
}
func (c *silentAfterFirstPollAgent) OnPing(*gws.Conn, []byte) {}
func (c *silentAfterFirstPollAgent) OnMessage(conn *gws.Conn, message *gws.Message) {
defer message.Close()
var req common.HubRequest[cbor.RawMessage]
if err := cbor.Unmarshal(message.Bytes(), &req); err != nil || req.Action != common.GetData {
return
}
if c.answered.CompareAndSwap(false, true) {
response, _ := cbor.Marshal(common.AgentResponse{Id: req.Id, SystemData: &esystem.CombinedData{}})
_ = conn.WriteMessage(gws.OpcodeBinary, response)
}
}
const timelineScale = 100
func TestSlowAgentKeepsConnectionAcrossPolls(t *testing.T) {
tick := time.Duration(interval) * time.Millisecond / timelineScale
tests := []struct {
name string
deadline time.Duration
polls int
wantConnected bool
}{
{"production deadline outlasts a failed poll", ws.Deadline() / timelineScale, 2, true},
{"deadline below interval plus request timeout", 70 * time.Second / timelineScale, 2, false},
{"agent silent past maxAgentSilence", ws.Deadline() / timelineScale, 5, false},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
previousDeadline := ws.SetDeadline(tc.deadline)
t.Cleanup(func() { ws.SetDeadline(previousDeadline) })
previousTimeout := wsDataRequestTimeout
wsDataRequestTimeout = 30 * time.Second / timelineScale
t.Cleanup(func() { wsDataRequestTimeout = previousTimeout })
previousSilence := maxAgentSilence
maxAgentSilence = 3 * time.Minute / timelineScale
t.Cleanup(func() { maxAgentSilence = previousSilence })
connections := make(chan *ws.WsConn, 1)
upgrader := gws.NewUpgrader(&ws.Handler{}, &gws.ServerOption{})
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r)
if err != nil {
t.Error(err)
return
}
wsConn := ws.NewWsConnection(conn, semver.MustParse("0.20.0"))
conn.Session().Store("wsConn", wsConn)
connections <- wsConn
conn.ReadLoop()
}))
t.Cleanup(server.Close)
client := &silentAfterFirstPollAgent{}
conn, _, err := gws.NewClient(client, &gws.ClientOption{Addr: "ws" + strings.TrimPrefix(server.URL, "http")})
require.NoError(t, err)
t.Cleanup(func() { _ = conn.NetConn().Close() })
go conn.ReadLoop()
var sys *System
select {
case wsConn := <-connections:
sys = &System{WsConn: wsConn}
case <-time.After(3 * time.Second):
t.Fatal("websocket connection was not established")
}
_, err = sys.fetchDataFromAgent(common.DataRequestOptions{})
require.NoError(t, err, "the first poll must succeed")
pollZero := time.Now()
for poll := 1; poll <= tc.polls; poll++ {
time.Sleep(time.Until(pollZero.Add(time.Duration(poll) * tick)))
if !sys.WsConn.IsConnected() {
break
}
require.Error(t, sys.update(), "a silent agent must fail the poll")
}
require.Equal(t, tc.wantConnected, sys.WsConn.IsConnected())
})
}
}