opensearch-project / opensearch-py

Python Client for OpenSearch
https://opensearch.org/docs/latest/clients/python/
Apache License 2.0
338 stars 170 forks source link

[FEATURE] Re-create `aiohttp.ClientSession` after using `close()` on `AsyncOpensearch` #637

Closed odelmarcelle closed 9 months ago

odelmarcelle commented 9 months ago

Is your feature request related to a problem?

I find it pretty annoying to handle the close() method of AsyncOpensearch. Basically, once closed, the client becomes unusable because every attempt to connect to the Opensearch cluster will yield the error opensearchpy.exceptions.ConnectionError: ConnectionError(Session is closed) caused by: RuntimeError(Session is closed).

What solution would you like?

This happens because close() effectively closes the aiohttp.ClientSession without removing the attribute from AsyncHttpSession. A simple solution would be to write self.session = None right after https://github.com/opensearch-project/opensearch-py/blob/e323ab2435a26ffd21104a2c765f9711b8614c3a/opensearchpy/connection/http_async.py#L279.

What alternatives have you considered?

Re-creating the AsyncOpensearch instance, which bring unecessary overhead?

Do you have any additional context?

How to create a RuntimeError:

import asyncio
from opensearchpy import AsyncOpenSearch
loop = asyncio.get_event_loop()
opensearch = AsyncOpenSearch(...)
async def get_health():
    print(await opensearch.cluster.health())

loop.run_until_complete(get_health())         # Ok
loop.run_until_complete(opensearch.close())   # Closing
loop.run_until_complete(get_health())         # RuntimeError
dblock commented 9 months ago

This is a good catch, definitely a problem. There should be a way to use with for any connection/instance, too. Please contribute!