Skip to content

Исправление: утечка соединения при ошибке в upload_file / upload_file_buffer#136

Open
gistrec wants to merge 4 commits intolove-apples:mainfrom
gistrec:fix-aiohttp-response-not-closed-on-exception
Open

Исправление: утечка соединения при ошибке в upload_file / upload_file_buffer#136
gistrec wants to merge 4 commits intolove-apples:mainfrom
gistrec:fix-aiohttp-response-not-closed-on-exception

Conversation

@gistrec
Copy link
Copy Markdown
Contributor

@gistrec gistrec commented Apr 26, 2026

response = await session.post(url=url, data=form)
return await response.text()  # Если здесь получим исключение, то
                              # соединение не возвратится в пул ClientSession

В aiohttp session.post() возвращает response после получения заголовков, тело ещё не прочитано. response.text() читает тело уже отдельным вызовом. На этом этапе можем получить:

  1. aiohttp.ClientPayloadError - сервер закрыл соединение до конца передачи тела
  2. asyncio.TimeoutError - истёк read-таймаут пока читается тело
  3. UnicodeDecodeError - сервер вернул тело с кодировкой, которую не удалось декодировать

То есть сценарий реальный, но достаточно редкий — нужен сбой именно после получения заголовков, но во время чтения тела. Для upload-эндпоинтов, которые отвечают коротким JSON, вероятность невысокая, но исправление правильное — это best practice для aiohttp

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Этот PR устраняет утечку соединений в пуле aiohttp.ClientSession в редких сценариях, когда session.post() успевает вернуть заголовки, но чтение тела через response.text() падает исключением, из-за чего соединение не возвращается в пул.

Changes:

  • В upload_file() обёрнут вызов session.post(...) в async with ... as response для гарантированного освобождения ответа при исключениях во время чтения тела.
  • В upload_file_buffer() сделано аналогичное изменение для session.post(...).

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread maxapi/connection/base.py Outdated
Comment thread maxapi/connection/base.py Outdated
Comment thread maxapi/connection/base.py
@codecov
Copy link
Copy Markdown

codecov Bot commented Apr 28, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

Copy link
Copy Markdown
Collaborator

@Olegt0rr Olegt0rr left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Отличная работа!

Остаётся добавить немного покрытия для задетых участков кода (если помощь нужна - пишите)

И исправить замечания при вызове make run-test

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 3 out of 3 changed files in this pull request and generated 8 comments.


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread tests/test_upload_file.py
Comment thread tests/test_upload_file.py
Comment thread tests/test_coverage_gaps.py
Comment thread tests/test_coverage_gaps.py
Comment thread tests/test_upload_file.py
Comment thread tests/test_upload_file.py
Comment thread tests/test_upload_file.py
Comment thread tests/test_upload_file.py
@Olegt0rr Olegt0rr requested a review from Copilot April 28, 2026 18:25
@Olegt0rr Olegt0rr added the bug Something isn't working label Apr 28, 2026
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 3 out of 3 changed files in this pull request and generated 4 comments.


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread tests/test_upload_file.py
Comment thread tests/test_upload_file.py
Comment thread tests/test_upload_file.py
Comment thread tests/test_coverage_gaps.py
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants