-
Notifications
You must be signed in to change notification settings - Fork 44
websocket disconnections #66
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
2 changes: 1 addition & 1 deletion
2
images/chromium-headful/supervisor/services/kernel-images-api.conf
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
2 changes: 1 addition & 1 deletion
2
images/chromium-headless/image/supervisor/services/kernel-images-api.conf
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -10,6 +10,7 @@ import ( | |
| "net/url" | ||
| "os/exec" | ||
| "regexp" | ||
| "strconv" | ||
| "strings" | ||
| "sync" | ||
| "sync/atomic" | ||
|
|
@@ -145,8 +146,8 @@ func (u *UpstreamManager) runTailOnce(ctx context.Context) { | |
|
|
||
| // WebSocketProxyHandler returns an http.Handler that upgrades incoming connections and | ||
| // proxies them to the current upstream websocket URL. It expects only websocket requests. | ||
| func WebSocketProxyHandler(mgr *UpstreamManager, logger *slog.Logger) http.Handler { | ||
| upgrader := websocket.Upgrader{CheckOrigin: func(r *http.Request) bool { return true }} | ||
| // If logCDPMessages is true, all CDP messages will be logged with their direction. | ||
| func WebSocketProxyHandler(mgr *UpstreamManager, logger *slog.Logger, logCDPMessages bool) http.Handler { | ||
| return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
| upstreamCurrent := mgr.Current() | ||
| if upstreamCurrent == "" { | ||
|
|
@@ -160,17 +161,41 @@ func WebSocketProxyHandler(mgr *UpstreamManager, logger *slog.Logger) http.Handl | |
| } | ||
| // Always use the full upstream path and query, ignoring the client's request path/query | ||
| upstreamURL := (&url.URL{Scheme: parsed.Scheme, Host: parsed.Host, Path: parsed.Path, RawQuery: parsed.RawQuery}).String() | ||
| upgrader := websocket.Upgrader{ | ||
| ReadBufferSize: 65536, | ||
| WriteBufferSize: 65536, | ||
| EnableCompression: true, | ||
| CheckOrigin: func(r *http.Request) bool { return true }, | ||
| } | ||
| logger.Info("upgrader config", slog.Any("upgrader", upgrader)) | ||
| clientConn, err := upgrader.Upgrade(w, r, nil) | ||
| if err != nil { | ||
| logger.Error("websocket upgrade failed", slog.String("err", err.Error())) | ||
| return | ||
| } | ||
| upstreamConn, _, err := websocket.DefaultDialer.Dial(upstreamURL, nil) | ||
| clientConn.SetReadDeadline(time.Time{}) // No timeout--hold on to connections for dear life | ||
| clientConn.SetWriteDeadline(time.Time{}) // No timeout--hold on to connections for dear life | ||
| clientConn.SetReadLimit(100 * 1024 * 1024) // 100 MB. Effectively no maximum size of message from client | ||
| clientConn.EnableWriteCompression(true) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. |
||
| clientConn.SetCompressionLevel(6) | ||
|
|
||
| dialer := websocket.Dialer{ | ||
| ReadBufferSize: 65536, | ||
| WriteBufferSize: 65536, | ||
| HandshakeTimeout: 30 * time.Second, | ||
| } | ||
| logger.Info("dialer config", slog.Any("dialer", dialer)) | ||
| upstreamConn, _, err := dialer.Dial(upstreamURL, nil) | ||
| if err != nil { | ||
| logger.Error("dial upstream failed", slog.String("err", err.Error()), slog.String("url", upstreamURL)) | ||
| _ = clientConn.Close() | ||
| return | ||
| } | ||
| upstreamConn.SetReadLimit(100 * 1024 * 1024) // 100 MB. Effectively no maximum size of message from upstream | ||
| upstreamConn.EnableWriteCompression(true) | ||
| upstreamConn.SetCompressionLevel(6) | ||
| upstreamConn.SetReadDeadline(time.Time{}) // no timeout | ||
| upstreamConn.SetWriteDeadline(time.Time{}) // no timeout | ||
| logger.Debug("proxying devtools websocket", slog.String("url", upstreamURL)) | ||
|
|
||
| var once sync.Once | ||
|
|
@@ -180,7 +205,7 @@ func WebSocketProxyHandler(mgr *UpstreamManager, logger *slog.Logger) http.Handl | |
| _ = clientConn.Close() | ||
| }) | ||
| } | ||
| proxyWebSocket(r.Context(), clientConn, upstreamConn, cleanup, logger) | ||
| proxyWebSocket(r.Context(), clientConn, upstreamConn, cleanup, logger, logCDPMessages) | ||
| }) | ||
| } | ||
|
|
||
|
|
@@ -190,47 +215,103 @@ type wsConn interface { | |
| Close() error | ||
| } | ||
|
|
||
| func proxyWebSocket(ctx context.Context, clientConn, upstreamConn wsConn, onClose func(), logger *slog.Logger) { | ||
| errChan := make(chan error, 2) | ||
| // logCDPMessage logs a CDP message with its direction if logging is enabled | ||
| func logCDPMessage(logger *slog.Logger, direction string, mt int, msg []byte) { | ||
| if mt != websocket.TextMessage { | ||
| return // Only log text messages (CDP messages) | ||
| } | ||
|
|
||
| // Extract fields using regex from raw message | ||
| rawMsg := string(msg) | ||
|
|
||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. |
||
| // Regex patterns to match "key":"val" or "key": "val" for string values | ||
| extractStringField := func(key string) string { | ||
| pattern := fmt.Sprintf(`"%s"\s*:\s*"([^"]*)"`, key) | ||
| re := regexp.MustCompile(pattern) | ||
| matches := re.FindStringSubmatch(rawMsg) | ||
| if len(matches) > 1 { | ||
| return matches[1] | ||
| } | ||
| return "" | ||
| } | ||
|
|
||
| // Regex pattern to match "key": number for numeric id | ||
| extractNumberField := func(key string) interface{} { | ||
| pattern := fmt.Sprintf(`"%s"\s*:\s*(\d+)`, key) | ||
| re := regexp.MustCompile(pattern) | ||
| matches := re.FindStringSubmatch(rawMsg) | ||
| if len(matches) > 1 { | ||
| // Try to parse as int first | ||
| if val, err := strconv.Atoi(matches[1]); err == nil { | ||
| return val | ||
| } | ||
| // Fall back to float64 | ||
| if val, err := strconv.ParseFloat(matches[1], 64); err == nil { | ||
| return val | ||
| } | ||
| } | ||
| return nil | ||
| } | ||
|
|
||
| // Extract fields using regex | ||
| method := extractStringField("method") | ||
| id := extractNumberField("id") | ||
| sessionId := extractStringField("sessionId") | ||
| targetId := extractStringField("targetId") | ||
| frameId := extractStringField("frameId") | ||
|
|
||
| // Build log attributes, only including non-empty values | ||
| attrs := []slog.Attr{ | ||
| slog.String("dir", direction), | ||
| } | ||
|
|
||
| if sessionId != "" { | ||
| attrs = append(attrs, slog.String("sessionId", sessionId)) | ||
| } | ||
| if targetId != "" { | ||
| attrs = append(attrs, slog.String("targetId", targetId)) | ||
| } | ||
| if id != nil { | ||
| attrs = append(attrs, slog.Any("id", id)) | ||
| } | ||
| if frameId != "" { | ||
| attrs = append(attrs, slog.String("frameId", frameId)) | ||
| } | ||
|
|
||
| if method != "" { | ||
| attrs = append(attrs, slog.String("method", method)) | ||
| } | ||
|
|
||
| attrs = append(attrs, slog.Int("raw_length", len(msg))) | ||
|
|
||
| // Single-writer guarantee for client connection | ||
| var clientWriteMu sync.Mutex | ||
| // Convert attrs to individual slog.Attr arguments | ||
| args := make([]any, len(attrs)) | ||
| for i, attr := range attrs { | ||
| args[i] = attr | ||
| } | ||
|
|
||
| // Heartbeat tracking | ||
| var hbMu sync.Mutex | ||
| lastClientActivity := time.Now() | ||
| var lastPingSent time.Time | ||
| var lastPongReceived time.Time | ||
| var outstandingPing bool | ||
| logger.Info("cdp", args...) | ||
| } | ||
|
|
||
| func proxyWebSocket(ctx context.Context, clientConn, upstreamConn wsConn, onClose func(), logger *slog.Logger, logCDPMessages bool) { | ||
| errChan := make(chan error, 2) | ||
|
|
||
| go func() { | ||
| for { | ||
| mt, msg, err := clientConn.ReadMessage() | ||
| if err != nil { | ||
| logger.Error("client read error", slog.String("err", err.Error())) | ||
| errChan <- err | ||
| break | ||
| } | ||
| // Record any client activity | ||
| hbMu.Lock() | ||
| lastClientActivity = time.Now() | ||
| hbMu.Unlock() | ||
|
|
||
| // Handle control frames from client | ||
| if mt == websocket.PongMessage { | ||
| hbMu.Lock() | ||
| lastPongReceived = time.Now() | ||
| outstandingPing = false | ||
| hbMu.Unlock() | ||
| continue | ||
| } | ||
| if mt == websocket.PingMessage { | ||
| clientWriteMu.Lock() | ||
| _ = clientConn.WriteMessage(websocket.PongMessage, nil) | ||
| clientWriteMu.Unlock() | ||
| continue | ||
|
|
||
| // Log CDP messages if enabled | ||
| if logCDPMessages { | ||
| logCDPMessage(logger, "->", mt, msg) | ||
| } | ||
|
|
||
| if err := upstreamConn.WriteMessage(mt, msg); err != nil { | ||
| logger.Error("upstream write error", slog.String("err", err.Error())) | ||
| errChan <- err | ||
| break | ||
| } | ||
|
|
@@ -240,65 +321,21 @@ func proxyWebSocket(ctx context.Context, clientConn, upstreamConn wsConn, onClos | |
| for { | ||
| mt, msg, err := upstreamConn.ReadMessage() | ||
| if err != nil { | ||
| logger.Error("upstream read error", slog.String("err", err.Error())) | ||
| errChan <- err | ||
| break | ||
| } | ||
| clientWriteMu.Lock() | ||
|
|
||
| // Log CDP messages if enabled | ||
| if logCDPMessages { | ||
| logCDPMessage(logger, "<-", mt, msg) | ||
| } | ||
|
|
||
| if err := clientConn.WriteMessage(mt, msg); err != nil { | ||
| clientWriteMu.Unlock() | ||
| logger.Error("client write error", slog.String("err", err.Error())) | ||
| errChan <- err | ||
| break | ||
| } | ||
| clientWriteMu.Unlock() | ||
| } | ||
| }() | ||
|
|
||
| // Heartbeat goroutine | ||
| go func() { | ||
| ticker := time.NewTicker(5 * time.Second) | ||
| defer ticker.Stop() | ||
| for { | ||
| select { | ||
| case <-ctx.Done(): | ||
| return | ||
| case <-ticker.C: | ||
| now := time.Now() | ||
| hbMu.Lock() | ||
| inactivity := now.Sub(lastClientActivity) | ||
| pingOutstanding := outstandingPing | ||
| lastPing := lastPingSent | ||
| lastPong := lastPongReceived | ||
| hbMu.Unlock() | ||
|
|
||
| if pingOutstanding { | ||
| if now.Sub(lastPing) > 10*time.Second && lastPong.Before(lastPing) { | ||
| logger.Warn("client ping timeout; closing devtools websocket") | ||
| select { | ||
| case errChan <- fmt.Errorf("ping timeout"): | ||
| default: | ||
| } | ||
| return | ||
| } | ||
| continue | ||
| } | ||
|
|
||
| if inactivity >= 30*time.Second { | ||
| clientWriteMu.Lock() | ||
| pingErr := clientConn.WriteMessage(websocket.PingMessage, nil) | ||
| clientWriteMu.Unlock() | ||
| if pingErr != nil { | ||
| select { | ||
| case errChan <- pingErr: | ||
| default: | ||
| } | ||
| return | ||
| } | ||
| hbMu.Lock() | ||
| lastPingSent = now | ||
| outstandingPing = true | ||
| hbMu.Unlock() | ||
| } | ||
| } | ||
| } | ||
| }() | ||
|
|
||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.