Improved sync enter and exit

This commit is contained in:
2026-01-10 11:45:09 +01:00
parent d0c804b48e
commit 89d7b9c7ce

View File

@@ -1,8 +1,6 @@
import asyncio
import atexit
import json
import logging
import signal
import socket
from typing import Any, Callable, Coroutine, Dict, List, Optional
@@ -47,9 +45,20 @@ class EventApi:
self.subscriptions: List[SubscriptionData] = []
self.callback = callback
atexit.register(self._close_sync)
signal.signal(signal.SIGINT, self._handle_exit)
signal.signal(signal.SIGTERM, self._handle_exit)
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
loop = None
try:
loop = asyncio.get_running_loop()
except RuntimeError:
asyncio.run(self.close())
else:
if loop.is_running():
loop.create_task(self.close())
else:
loop.run_until_complete(self.close())
async def __aenter__(self) -> Self:
await self.connect()
@@ -112,7 +121,7 @@ class EventApi:
if self.handler:
self.handler.cancel()
try:
await asyncio.wait_for(self.handler, timeout=5.0)
await asyncio.wait_for(self.handler, timeout=3.0)
except asyncio.TimeoutError:
logging.warning("Handler did not cancel within timeout, forcing close")
except asyncio.CancelledError:
@@ -120,7 +129,7 @@ class EventApi:
self.handler = None
if self.ws and not self.closed:
try:
await asyncio.wait_for(self.ws.close(), timeout=5.0)
await asyncio.wait_for(self.ws.close(), timeout=3.0)
except asyncio.TimeoutError:
logging.warning("WebSocket close timed out, forcing close")
except ConnectionClosed: