micropython-lib icon indicating copy to clipboard operation
micropython-lib copied to clipboard

aiohttp - incorrect handling of connection pooling with web sockets.

Open FuNK3Y opened this issue 7 months ago • 2 comments

Reading the official aiohttp documentation: https://docs.aiohttp.org/en/stable/client_reference.html

I optimized my code to have a single ClientSession within my app to take advantage of connection pooling

class My_class:
    _clientSession= aiohttp.ClientSession()

    async def my_method():
        async with self._clientSession.ws_connect(uri) as ws:
            await ws.receive_json()
            ...
            await ws.send_json(stuff)

my_method is invoked twice - to different web sockets, over TLS simultaneously.

I get randomly served with a Uncaught exception in callback: (-28928, 'MBEDTLS_ERR_SSL_BAD_INPUT_DATA').

Creating the ClientSession within my_method completely resolves the issue - but at the expense of connection pooling. I strongly suspect a racing condition tied to the pooling.

This is happening on a pico 2 w running 1.25.0

FuNK3Y avatar Jun 04 '25 15:06 FuNK3Y

Can you test this without TLS?, Can you test unix port?

As a workaround asyncio.Lock may help https://docs.micropython.org/en/latest/library/asyncio.html#class-lock,

I get randomly served with a Uncaught exception in callback: (-28928, 'MBEDTLS_ERR_SSL_BAD_INPUT_DATA').

Concurrency and TLS is tricky, if you want to debug this for mbedTLS add at mbedtls_config_port.h

 #define MBEDTLS_DEBUG_C  (1)

Carglglz avatar Jun 04 '25 22:06 Carglglz

Thank you for your answer.

As a workaround, I create a ClientSession per remote endpoint and it works well enough.

I sadly can't test without TLS. This bug is out of my depth to troubleshoot - I raised an issue to give a chance to others to correlate their observations with mine.

FuNK3Y avatar Jun 11 '25 18:06 FuNK3Y