mirror of
https://github.com/Rain-kl/OpenFlare.git
synced 2026-10-04 15:06:37 +08:00
2f60329886
代码质量全量清理,零行为变化:golangci 扩展集 13 类 linter(gosec/modernize/perfsprint/canonicalheader/usestdlibvars/wastedassign/intrange/errorlint/forcetypeassert/recvcheck/exhaustive/unparam)全量修复,测试代码质量(testifylint/thelper/usetesting)25→0,frpc 进程生命周期真 bug(进程组击杀)、全仓 go test -race 6 类数据竞争(含 1 个生产竞争)、SPDX license 头补齐 131 文件、前端测试套件 next-intl 迁移后 44 失败→全绿、过期 swagger 文档重新生成、pnpm-workspace 构建审批。 Experiments: #2-#17, #18, #20, #21, #23 Metric: total_issues 108 → 8 (-92.6%)
76 lines
1.8 KiB
Go
76 lines
1.8 KiB
Go
// Copyright 2026 Arctel.net
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
|
|
// Package runner provides shared WebSocket reconnect helpers for edge daemons.
|
|
package runner
|
|
|
|
import (
|
|
"context"
|
|
"log/slog"
|
|
"time"
|
|
)
|
|
|
|
// WSConnection defines the minimum interface required for a WebSocket connection that can be closed.
|
|
type WSConnection interface {
|
|
Close() error
|
|
}
|
|
|
|
// WSReconnectConfig specifies configuration parameters for the WebSocket reconnect loop.
|
|
type WSReconnectConfig struct {
|
|
ComponentName string
|
|
ConnectBackoff time.Duration
|
|
ReconnectDelay time.Duration
|
|
OnShutdown func()
|
|
}
|
|
|
|
// RunWSReconnectLoop runs a loop that attempts to keep a WebSocket connection active, automatically reconnecting when closed or failed.
|
|
func RunWSReconnectLoop(ctx context.Context, cfg WSReconnectConfig,
|
|
connect func(context.Context) (WSConnection, error),
|
|
handle func(context.Context, WSConnection),
|
|
) error {
|
|
if cfg.ConnectBackoff <= 0 {
|
|
cfg.ConnectBackoff = 5 * time.Second
|
|
}
|
|
if cfg.ReconnectDelay <= 0 {
|
|
cfg.ReconnectDelay = 2 * time.Second
|
|
}
|
|
label := cfg.ComponentName
|
|
if label == "" {
|
|
label = "edge"
|
|
}
|
|
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
if cfg.OnShutdown != nil {
|
|
cfg.OnShutdown()
|
|
}
|
|
return ctx.Err()
|
|
default:
|
|
// Continue reconnect loop
|
|
}
|
|
|
|
conn, err := connect(ctx)
|
|
if err != nil {
|
|
slog.Error(label+" ws connect failed, will retry", "error", err)
|
|
SleepContext(ctx, cfg.ConnectBackoff)
|
|
continue
|
|
}
|
|
|
|
handle(ctx, conn)
|
|
_ = conn.Close()
|
|
slog.Info(label + " ws connection closed, reconnecting...")
|
|
SleepContext(ctx, cfg.ReconnectDelay)
|
|
}
|
|
}
|
|
|
|
// SleepContext pauses execution for the given duration or until the context is canceled.
|
|
func SleepContext(ctx context.Context, d time.Duration) {
|
|
t := time.NewTimer(d)
|
|
defer t.Stop()
|
|
select {
|
|
case <-ctx.Done():
|
|
case <-t.C:
|
|
}
|
|
}
|