@@ -203,9 +203,13 @@ func (mgr *BackendConnManager) Connect(ctx context.Context, clientIO *pnet.Packe
203203 childCtx , cancelFunc := context .WithCancel (ctx )
204204 mgr .cancelFunc = cancelFunc
205205 mgr .lastActiveTime = endTime
206- mgr .wg .Run (func () {
206+ mgr .wg .RunWithRecover (func () {
207207 mgr .processSignals (childCtx )
208- })
208+ }, func (_ any ) {
209+ // If we do not clean up, the router may retain the connection forever and the TiDB won't be released in the
210+ // Serverless Tier.
211+ _ = mgr .Close ()
212+ }, mgr .logger )
209213 return nil
210214}
211215
@@ -422,22 +426,26 @@ func (mgr *BackendConnManager) processSignals(ctx context.Context) {
422426 for {
423427 select {
424428 case s := <- mgr .signalReceived :
425- // Redirect the session immediately just in case the session is finishedTxn.
426- mgr .processLock .Lock ()
427- switch s {
428- case signalTypeGracefulClose :
429- mgr .tryGracefulClose (ctx )
430- case signalTypeRedirect :
431- mgr .tryRedirect (ctx )
432- }
433- mgr .processLock .Unlock ()
429+ func () {
430+ // Redirect the session immediately just in case the session is finishedTxn.
431+ mgr .processLock .Lock ()
432+ defer mgr .processLock .Unlock ()
433+ switch s {
434+ case signalTypeGracefulClose :
435+ mgr .tryGracefulClose (ctx )
436+ case signalTypeRedirect :
437+ mgr .tryRedirect (ctx )
438+ }
439+ }()
434440 case rs := <- mgr .redirectResCh :
435441 mgr .notifyRedirectResult (ctx , rs )
436442 case <- checkBackendTicker .C :
437- mgr .checkBackendActive ()
438- mgr .processLock .Lock ()
439- mgr .setKeepAlive ()
440- mgr .processLock .Unlock ()
443+ func () {
444+ mgr .checkBackendActive ()
445+ mgr .processLock .Lock ()
446+ defer mgr .processLock .Unlock ()
447+ mgr .setKeepAlive ()
448+ }()
441449 case <- ctx .Done ():
442450 checkBackendTicker .Stop ()
443451 return
0 commit comments