From 44d339d777293e5bb96677a4df9329661f64d28b Mon Sep 17 00:00:00 2001 From: 9seconds Date: Tue, 19 Nov 2019 11:49:27 +0300 Subject: [PATCH] Forcefully cleanup old connections --- hub/connection_list.go | 9 ++++----- hub/mux.go | 11 ++++++++++- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/hub/connection_list.go b/hub/connection_list.go index 7acdde1..565ba61 100644 --- a/hub/connection_list.go +++ b/hub/connection_list.go @@ -11,11 +11,7 @@ type connectionList struct { connections []*connection } -func (c *connectionList) Get(conn *ProxyConn) (*connection, error) { - if len(c.connections) > 0 { - c.gc() - } - +func (c *connectionList) get(conn *ProxyConn) (*connection, error) { if len(c.connections) > 0 && c.connections[0].Len() < config.C.MultiplexPerConnection { if err := c.connections[0].Attach(conn); err == nil { return c.connections[0], nil @@ -41,6 +37,9 @@ func (c *connectionList) Get(conn *ProxyConn) (*connection, error) { func (c *connectionList) gc() { prevLen := len(c.connections) + if prevLen == 0 { + return + } for i := len(c.connections) - 1; i >= 0; i-- { lastIndex := len(c.connections) - 1 diff --git a/hub/mux.go b/hub/mux.go index 7263826..817bc8a 100644 --- a/hub/mux.go +++ b/hub/mux.go @@ -2,11 +2,14 @@ package hub import ( "context" + "time" "mtg/conntypes" "mtg/protocol" ) +const muxGCEvery = time.Minute + type muxNewRequest struct { req *protocol.TelegramRequest resp chan<- muxNewResponse @@ -26,6 +29,9 @@ type mux struct { } func (m *mux) run() { + gcTicker := time.NewTicker(muxGCEvery) + defer gcTicker.Stop() + for { select { case <-m.ctx.Done(): @@ -34,9 +40,12 @@ func (m *mux) run() { } return + case <-gcTicker.C: + m.connections.gc() case req := <-m.channelNew: + m.connections.gc() proxyConn := newProxyConn(req.req, m.channelClosed) - conn, err := m.connections.Get(proxyConn) + conn, err := m.connections.get(proxyConn) if err == nil { m.clients[string(req.req.ConnID[:])] = conn