Marking response.force_close() doesn't prevent lingering
Long story short
Returning a response with force_close() before the request is fully read still causes lingering.
Expected behaviour
Connection should be closed immediately after the response is written.
Actual behaviour
The lingering logic in web_protocol.py is activated.
Tried to replicate with the short information of the ticket, and it looks like it solved on aiohttp 2.0.0
@Polandia94 when closing issues like this, try to include as much context as possible. Like maybe a PR you suspect fixed this. Or the way you tried to reproduce this etc.
Sorry, i had a reproducer using the aiohttp client, but it was incorrect. I believe this script is reproducing the issue and it's still happening, so I reopened the issue
import asyncio
import time
import aiohttp
from aiohttp import web
LINGERING_TIME = 3.0
DECLARED_LENGTH = 65536
PORT = 9558
async def handler(request: web.Request) -> web.Response:
resp = web.Response(text="ignored")
resp.force_close()
return resp
async def main() -> None:
app = web.Application()
app.router.add_post("/upload", handler)
runner = web.AppRunner(app, handle_signals=False, lingering_time=LINGERING_TIME)
await runner.setup()
await web.TCPSite(runner, "127.0.0.1", PORT).start()
reader, writer = await asyncio.open_connection("127.0.0.1", PORT)
# Announce DECLARED_LENGTH but send only 512 bytes, so the server-side
# payload never reaches EOF on its own.
writer.write(
b"POST /upload HTTP/1.1\r\n"
b"Host: 127.0.0.1\r\n"
b"Content-Length: " + str(DECLARED_LENGTH).encode() + b"\r\n"
b"\r\n" + b"x" * 512
)
await writer.drain()
# Read the head and exactly Content-Length body bytes. Reading to EOF
# would block through the very window being measured.
head = await reader.readuntil(b"\r\n\r\n")
start = time.monotonic()
status_line = head.split(b"\r\n", 1)[0].decode()
for line in head.split(b"\r\n"):
if line.lower().startswith(b"content-length:"):
await reader.readexactly(int(line.split(b":", 1)[1]))
await reader.read() # blocks until the server closes
elapsed = time.monotonic() - start
print(f"aiohttp {aiohttp.__version__}, lingering_time={LINGERING_TIME}s")
print(f"response: {status_line}")
print(f"server closed {elapsed:.3f}s after the response")
writer.close()
await runner.cleanup()
asyncio.run(main())
I reproduced this on current master (2e64b0f) and turned the timing script into a raw-TCP test that races a read from the request payload against client EOF, so it does not depend on the configured linger duration.
The call chain sets resp.keep_alive=False, then RequestHandler.start() copies it to _keepalive; the lingering branch intentionally checks only protocol _force_close. This matches #1478/#927's TCP-reset rationale and the docs' wording that StreamResponse.force_close() disables keep-alive. Adding _keepalive to the lingering guard, as #13245 attempted, also skips graceful drain for HTTP/1.0 and Connection: close.
Should #1800 change only an explicit StreamResponse.force_close() to immediate transport close, while preserving graceful drain for other non-keep-alive cases? That would require carrying the explicit response intent separately. Or should force_close() retain the current graceful-close semantics and the docs/tests be clarified instead?
I've taken a look into this and I think this is the correct behaviour. Feel free to make a PR adjusting the documentation.
Basically, resp.force_close() stops the keep-alive behaviour and gracefully closes the response (the primary purpose of this is probably when aiohttp handles an error and calls this method. You want lingering close here to ensure the client receives the error response).
To actually kill the connection immediately, you'd use the lower level request.protocol.force_close().