@@ -108,8 +108,7 @@ async def handle_async_request(self, request: Request) -> Response:
108108 async with Trace ("send_connection_init" , logger , request , kwargs ):
109109 await self ._send_connection_init (** kwargs )
110110 except BaseException as exc :
111- with AsyncShieldCancellation ():
112- await self .aclose ()
111+ await AsyncShieldCancellation .shield (self .aclose )
113112 raise exc
114113
115114 self ._sent_connection_init = True
@@ -160,12 +159,15 @@ async def handle_async_request(self, request: Request) -> Response:
160159 "stream_id" : stream_id ,
161160 },
162161 )
163- except BaseException as exc : # noqa: PIE786
164- with AsyncShieldCancellation ():
162+ except BaseException as exc :
163+
164+ async def close () -> None :
165165 kwargs = {"stream_id" : stream_id }
166166 async with Trace ("response_closed" , logger , request , kwargs ):
167167 await self ._response_closed (stream_id = stream_id )
168168
169+ await AsyncShieldCancellation .shield (close )
170+
169171 if isinstance (exc , h2 .exceptions .ProtocolError ):
170172 # One case where h2 can raise a protocol error is when a
171173 # closed frame has been seen by the state machine.
@@ -577,8 +579,7 @@ async def __aiter__(self) -> typing.AsyncIterator[bytes]:
577579 # If we get an exception while streaming the response,
578580 # we want to close the response (and possibly the connection)
579581 # before raising that exception.
580- with AsyncShieldCancellation ():
581- await self .aclose ()
582+ await AsyncShieldCancellation .shield (self .aclose )
582583 raise exc
583584
584585 async def aclose (self ) -> None :
0 commit comments