@@ -108,8 +108,7 @@ async def handle_async_request(self, request: Request) -> Response:
108
108
async with Trace ("send_connection_init" , logger , request , kwargs ):
109
109
await self ._send_connection_init (** kwargs )
110
110
except BaseException as exc :
111
- with AsyncShieldCancellation ():
112
- await self .aclose ()
111
+ await AsyncShieldCancellation .shield (self .aclose )
113
112
raise exc
114
113
115
114
self ._sent_connection_init = True
@@ -160,12 +159,15 @@ async def handle_async_request(self, request: Request) -> Response:
160
159
"stream_id" : stream_id ,
161
160
},
162
161
)
163
- except BaseException as exc : # noqa: PIE786
164
- with AsyncShieldCancellation ():
162
+ except BaseException as exc :
163
+
164
+ async def close () -> None :
165
165
kwargs = {"stream_id" : stream_id }
166
166
async with Trace ("response_closed" , logger , request , kwargs ):
167
167
await self ._response_closed (stream_id = stream_id )
168
168
169
+ await AsyncShieldCancellation .shield (close )
170
+
169
171
if isinstance (exc , h2 .exceptions .ProtocolError ):
170
172
# One case where h2 can raise a protocol error is when a
171
173
# closed frame has been seen by the state machine.
@@ -577,8 +579,7 @@ async def __aiter__(self) -> typing.AsyncIterator[bytes]:
577
579
# If we get an exception while streaming the response,
578
580
# we want to close the response (and possibly the connection)
579
581
# before raising that exception.
580
- with AsyncShieldCancellation ():
581
- await self .aclose ()
582
+ await AsyncShieldCancellation .shield (self .aclose )
582
583
raise exc
583
584
584
585
async def aclose (self ) -> None :
0 commit comments