feat(server): add active client tracking and conditional reconnection

This commit is contained in:
zarazaex69
2026-04-12 16:25:00 +03:00
parent c0027c577a
commit cbb1f0f2fe
2 changed files with 16 additions and 0 deletions

View File

@@ -30,6 +30,7 @@ type Server struct {
streamPumps map[uint16]net.Conn
pumpMu sync.Mutex
peerIdx atomic.Uint32
activeClients atomic.Int32
wg sync.WaitGroup
dnsServer string
dnsCache sync.Map
@@ -171,6 +172,10 @@ func Run(ctx context.Context, roomURL, keyHex string, duo bool, dnsServer, socks
log.Println("Server multiplexer reset complete")
})
peer.SetShouldReconnect(func() bool {
return s.activeClients.Load() > 0
})
log.Printf("Connecting peer %d to Telemost...", peerID)
if err := peer.Connect(runCtx); err != nil {
return err
@@ -414,11 +419,13 @@ func (s *Server) handleConnect(ctx context.Context, sid uint16, req ConnectReque
log.Printf("[SERVER] sid=%d CONNECT_SUCCESS dial_time=%v", sid, dialElapsed)
s.activeClients.Add(1)
s.mux.SendData(sid, []byte{0x00})
s.startStreamPump(ctx, sid, conn)
go func() {
defer func() {
s.activeClients.Add(-1)
s.mux.CloseStream(sid)
s.connMu.Lock()
delete(s.connections, sid)

View File

@@ -44,6 +44,7 @@ type Peer struct {
dc *webrtc.DataChannel
onData func([]byte)
onReconnect func(*webrtc.DataChannel)
shouldReconnect func() bool
reconnectCh chan struct{}
closeCh chan struct{}
keepAliveCh chan struct{}
@@ -131,6 +132,10 @@ func (p *Peer) queueReconnect() {
if p.closed.Load() || p.reconnecting.Load() {
return
}
if p.shouldReconnect != nil && !p.shouldReconnect() {
log.Println("Reconnect skipped: shouldReconnect returned false")
return
}
select {
case p.reconnectCh <- struct{}{}:
default:
@@ -983,6 +988,10 @@ func (p *Peer) SetReconnectCallback(cb func(*webrtc.DataChannel)) {
p.onReconnect = cb
}
func (p *Peer) SetShouldReconnect(fn func() bool) {
p.shouldReconnect = fn
}
func (p *Peer) WatchConnection(ctx context.Context) {
const maxReconnects = 10
const reconnectWindow = 5 * time.Minute