Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 31 additions & 12 deletions server/websocket.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,9 @@ import (
)

type wsConnection struct {
conn *websocket.Conn
writeMu sync.Mutex
conn *websocket.Conn
writeMu sync.Mutex
handlerSem chan struct{}
}

type validationError struct {
Expand All @@ -24,10 +25,11 @@ type validationError struct {
}

const (
wsMaxMessageSize = 64 * 1024
wsWriteWait = 10 * time.Second
wsPongWait = 60 * time.Second
wsPingPeriod = (wsPongWait * 9) / 10
wsMaxMessageSize = 64 * 1024
wsWriteWait = 10 * time.Second
wsPongWait = 60 * time.Second
wsPingPeriod = (wsPongWait * 9) / 10
wsMaxConcurrentHandlers = 4

jsonRPCVersion = "2.0"
errMsgParseError = "expecting jsonrpc payload"
Expand Down Expand Up @@ -131,7 +133,7 @@ func NewWebSocketHandler(enableCORS bool) http.HandlerFunc {
}
defer conn.Close()

wsConn := &wsConnection{conn: conn}
wsConn := &wsConnection{conn: conn, handlerSem: make(chan struct{}, wsMaxConcurrentHandlers)}
configureConnection(conn)
stopPing := startPingRoutine(wsConn)
defer stopPing()
Expand Down Expand Up @@ -207,14 +209,28 @@ func handleWSMethodCall(wsConn *wsConnection, req JSONRPCRequest) {
return
}

result, err := handler(req.Params)
if err != nil {
log.Printf("Error executing method %s: %v", req.Method, err)
wsConn.sendError(req.ID, ErrCodeServerError, "Server error", err.Error())
// non-blocking acquire; reject immediately when all slots are taken
select {
case wsConn.handlerSem <- struct{}{}:
default:
wsConn.sendError(req.ID, ErrCodeServerError, "Server error", "too many concurrent requests")
return
}

wsConn.sendResponse(req.ID, result)
// run in a goroutine so the read loop stays unblocked and can process
// pong frames — without this, long-running handlers cause the read
// deadline to expire and the connection closes with 1006
go func() {
defer func() { <-wsConn.handlerSem }()
result, err := handler(req.Params)
if err != nil {
log.Printf("Error executing method %s: %v", req.Method, err)
wsConn.sendError(req.ID, ErrCodeServerError, "Server error", err.Error())
return
}

wsConn.sendResponse(req.ID, result)
}()
Comment thread
coderabbitai[bot] marked this conversation as resolved.
}

func (wsc *wsConnection) sendResponse(id any, result any) error {
Expand Down Expand Up @@ -242,5 +258,8 @@ func (wsc *wsConnection) sendError(id any, code int, message string, data any) e
func (wsc *wsConnection) sendJSON(v any) error {
wsc.writeMu.Lock()
defer wsc.writeMu.Unlock()
if err := wsc.conn.SetWriteDeadline(time.Now().Add(wsWriteWait)); err != nil {
return err
}
return wsc.conn.WriteJSON(v)
}
Loading