@@ -387,6 +387,7 @@ impl ASGIWebsocketProtocol {
387387 let websocket = self . websocket . lock ( ) . unwrap ( ) . take ( ) ;
388388 let accepted = self . init_tx . clone ( ) ;
389389 let accept_notify = self . init_event . clone ( ) ;
390+ let closed = self . closed . clone ( ) ;
390391 let rx = self . ws_rx . clone ( ) ;
391392 let tx = self . ws_tx . clone ( ) ;
392393
@@ -410,6 +411,12 @@ impl ASGIWebsocketProtocol {
410411 accept_notify. notify_one ( ) ;
411412 return FutureResultToPy :: None ;
412413 }
414+
415+ // connection was closed before upgrade
416+ closed. store ( true , atomic:: Ordering :: Release ) ;
417+ accepted. store ( true , atomic:: Ordering :: Release ) ;
418+ accept_notify. notify_one ( ) ;
419+ return FutureResultToPy :: None ;
413420 }
414421 FutureResultToPy :: Err ( error_flow ! ( "Connection already upgraded" ) )
415422 } )
@@ -521,6 +528,13 @@ impl ASGIWebsocketProtocol {
521528 . compare_exchange ( false , true , atomic:: Ordering :: Relaxed , atomic:: Ordering :: Relaxed )
522529 . is_ok ( )
523530 {
531+ // unless the connection was closed
532+ if self . closed . load ( atomic:: Ordering :: Acquire ) {
533+ return done_future_into_py (
534+ py,
535+ super :: conversion:: message_into_py ( py, ASGIMessageType :: WSClose ( None ) ) . map ( Bound :: unbind) ,
536+ ) ;
537+ }
524538 return done_future_into_py (
525539 py,
526540 super :: conversion:: message_into_py ( py, ASGIMessageType :: WSConnect ) . map ( Bound :: unbind) ,
0 commit comments