@@ -18,6 +18,7 @@ import (
1818
1919 "golang.org/x/net/http2"
2020
21+ "github.com/bep/debounce"
2122 "github.com/hons82/go-http-tunnel/connection"
2223 "github.com/hons82/go-http-tunnel/id"
2324 "github.com/hons82/go-http-tunnel/log"
@@ -57,6 +58,14 @@ type Server struct {
5758 httpClient * http.Client
5859 logger log.Logger
5960 vhostMuxer * vhost.TLSMuxer
61+
62+ debounce Debounced
63+ }
64+
65+ // Debounced Hold IDs that are disconnected for a short time before executing the function.
66+ type Debounced struct {
67+ debounced func (f func ())
68+ disconnectedIDs []id.ID
6069}
6170
6271// NewServer creates a new Server.
@@ -71,11 +80,16 @@ func NewServer(config *ServerConfig) (*Server, error) {
7180 logger = log .NewNopLogger ()
7281 }
7382
83+ debounced := & Debounced {
84+ debounced : debounce .New (1000 * time .Millisecond ),
85+ }
86+
7487 s := & Server {
7588 registry : newRegistry (logger ),
7689 config : config ,
7790 listener : listener ,
7891 logger : logger ,
92+ debounce : * debounced ,
7993 }
8094
8195 t := & http2.Transport {}
@@ -158,11 +172,18 @@ func listener(config *ServerConfig) (net.Listener, error) {
158172// disconnected clears resources used by client, it's invoked by connection pool
159173// when client goes away.
160174func (s * Server ) disconnected (identifier id.ID ) {
161- s .logger .Log (
162- "level" , 1 ,
163- "action" , "disconnected" ,
164- "identifier" , identifier ,
165- )
175+ s .debounce .disconnectedIDs = append (s .debounce .disconnectedIDs , identifier )
176+
177+ s .debounce .debounced (func () {
178+ for _ , id := range s .debounce .disconnectedIDs {
179+ s .logger .Log (
180+ "level" , 1 ,
181+ "action" , "disconnected" ,
182+ "identifier" , id ,
183+ )
184+ }
185+ s .debounce .disconnectedIDs = nil
186+ })
166187
167188 i := s .registry .clear (identifier )
168189 if i == nil {
@@ -233,7 +254,7 @@ func (s *Server) handleClient(conn net.Conn) {
233254 logger := log .NewContext (s .logger ).With ("remote addr" , conn .RemoteAddr ())
234255
235256 logger .Log (
236- "level" , 1 ,
257+ "level" , 2 ,
237258 "action" , "try connect" ,
238259 )
239260
@@ -246,6 +267,9 @@ func (s *Server) handleClient(conn net.Conn) {
246267 ok bool
247268
248269 inConnPool bool
270+
271+ remainingIDs []id.ID
272+ found bool
249273 )
250274
251275 tlsConn , ok := conn .(* tls.Conn )
@@ -373,10 +397,19 @@ func (s *Server) handleClient(conn net.Conn) {
373397 goto reject
374398 }
375399
376- logger .Log (
377- "level" , 1 ,
378- "action" , "connected" ,
379- )
400+ remainingIDs , found = id .Remove (s .debounce .disconnectedIDs , identifier )
401+ if found {
402+ s .debounce .disconnectedIDs = remainingIDs
403+ logger .Log (
404+ "level" , 2 ,
405+ "action" , "reconnected" ,
406+ )
407+ } else {
408+ logger .Log (
409+ "level" , 1 ,
410+ "action" , "connected" ,
411+ )
412+ }
380413
381414 return
382415
0 commit comments