mirror of
https://github.com/coder/coder.git
synced 2026-06-03 21:18:24 +00:00
bddb808b25
Fixes all our Go file imports to match the preferred spec that we've _mostly_ been using. For example: ``` import ( "context" "time" "github.com/prometheus/client_golang/prometheus" "golang.org/x/xerrors" "gopkg.in/natefinch/lumberjack.v2" "cdr.dev/slog/v3" "github.com/coder/coder/v2/codersdk/agentsdk" "github.com/coder/serpent" ) ``` 3 groups: standard library, 3rd partly libs, Coder libs. This PR makes the change across the codebase. The PR in the stack above modifies our formatting to maintain this state of affairs, and is a separate PR so it's possible to review that one in detail.
70 lines
1.6 KiB
Go
70 lines
1.6 KiB
Go
package httpapi
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"time"
|
|
|
|
"golang.org/x/xerrors"
|
|
|
|
"cdr.dev/slog/v3"
|
|
"github.com/coder/websocket"
|
|
)
|
|
|
|
const HeartbeatInterval time.Duration = 15 * time.Second
|
|
|
|
// Heartbeat loops to ping a WebSocket to keep it alive.
|
|
// Default idle connection timeouts are typically 60 seconds.
|
|
// See: https://docs.aws.amazon.com/elasticloadbalancing/latest/application/application-load-balancers.html#connection-idle-timeout
|
|
func Heartbeat(ctx context.Context, conn *websocket.Conn) {
|
|
ticker := time.NewTicker(HeartbeatInterval)
|
|
defer ticker.Stop()
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
return
|
|
case <-ticker.C:
|
|
}
|
|
err := conn.Ping(ctx)
|
|
if err != nil {
|
|
return
|
|
}
|
|
}
|
|
}
|
|
|
|
// Heartbeat loops to ping a WebSocket to keep it alive. It calls `exit` on ping
|
|
// failure.
|
|
func HeartbeatClose(ctx context.Context, logger slog.Logger, exit func(), conn *websocket.Conn) {
|
|
ticker := time.NewTicker(HeartbeatInterval)
|
|
defer ticker.Stop()
|
|
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
return
|
|
case <-ticker.C:
|
|
}
|
|
err := pingWithTimeout(ctx, conn, HeartbeatInterval)
|
|
if err != nil {
|
|
// context.DeadlineExceeded is expected when the client disconnects without sending a close frame
|
|
if !errors.Is(err, context.DeadlineExceeded) {
|
|
logger.Error(ctx, "failed to heartbeat ping", slog.Error(err))
|
|
}
|
|
_ = conn.Close(websocket.StatusGoingAway, "Ping failed")
|
|
exit()
|
|
return
|
|
}
|
|
}
|
|
}
|
|
|
|
func pingWithTimeout(ctx context.Context, conn *websocket.Conn, timeout time.Duration) error {
|
|
ctx, cancel := context.WithTimeout(ctx, timeout)
|
|
defer cancel()
|
|
err := conn.Ping(ctx)
|
|
if err != nil {
|
|
return xerrors.Errorf("failed to ping: %w", err)
|
|
}
|
|
|
|
return nil
|
|
}
|