nonebot2/nonebot/drivers/aiohttp.py

459 lines
16 KiB
Python
Raw Normal View History

2021-06-21 01:22:33 +08:00
"""
2021-07-31 12:24:11 +08:00
AIOHTTP 驱动适配
================
本驱动仅支持客户端连接
2021-06-21 01:22:33 +08:00
"""
import signal
import asyncio
2021-07-20 15:35:56 +08:00
import threading
2021-07-19 14:51:28 +08:00
from dataclasses import dataclass
from typing import Set, List, Union, Callable, Optional, Awaitable, cast
2021-06-21 01:22:33 +08:00
import aiohttp
2021-07-19 14:51:28 +08:00
from yarl import URL
2021-06-21 01:22:33 +08:00
from nonebot.log import logger
2021-07-19 01:20:17 +08:00
from nonebot.adapters import Bot
2021-06-21 01:22:33 +08:00
from nonebot.typing import overrides
from nonebot.utils import escape_tag
2021-06-21 01:22:33 +08:00
from nonebot.config import Env, Config
from nonebot.drivers import WebSocket as BaseWebSocket
from nonebot.drivers import (
HTTPRequest,
ForwardDriver,
WebSocketSetup,
HTTPPollingSetup,
)
2021-06-21 01:22:33 +08:00
STARTUP_FUNC = Callable[[], Awaitable[None]]
SHUTDOWN_FUNC = Callable[[], Awaitable[None]]
HTTPPOLLING_SETUP = Union[HTTPPollingSetup, Callable[[], Awaitable[HTTPPollingSetup]]]
2021-07-31 12:24:11 +08:00
WEBSOCKET_SETUP = Union[WebSocketSetup, Callable[[], Awaitable[WebSocketSetup]]]
2021-07-20 15:35:56 +08:00
HANDLED_SIGNALS = (
signal.SIGINT, # Unix signal 2. Sent by Ctrl+C.
signal.SIGTERM, # Unix signal 15. Sent by `kill <pid>`.
)
2021-06-21 01:22:33 +08:00
class Driver(ForwardDriver):
2021-07-31 12:24:11 +08:00
"""
AIOHTTP 驱动框架
"""
2021-06-21 01:22:33 +08:00
def __init__(self, env: Env, config: Config):
super().__init__(env, config)
self.startup_funcs: Set[STARTUP_FUNC] = set()
self.shutdown_funcs: Set[SHUTDOWN_FUNC] = set()
2021-07-31 12:24:11 +08:00
self.http_pollings: List[HTTPPOLLING_SETUP] = []
self.websockets: List[WEBSOCKET_SETUP] = []
2021-07-20 15:35:56 +08:00
self.connections: List[asyncio.Task] = []
self.should_exit: asyncio.Event = asyncio.Event()
2021-07-20 15:35:56 +08:00
self.force_exit: bool = False
2021-06-21 01:22:33 +08:00
@property
@overrides(ForwardDriver)
def type(self) -> str:
"""驱动名称: ``aiohttp``"""
return "aiohttp"
@property
@overrides(ForwardDriver)
def logger(self):
2021-07-31 12:24:11 +08:00
"""aiohttp driver 使用的 logger"""
2021-06-21 01:22:33 +08:00
return logger
@overrides(ForwardDriver)
2021-07-31 12:24:11 +08:00
def on_startup(self, func: STARTUP_FUNC) -> STARTUP_FUNC:
"""
:说明:
注册一个启动时执行的函数
:参数:
* ``func: Callable[[], Awaitable[None]]``
"""
2021-06-21 01:22:33 +08:00
self.startup_funcs.add(func)
return func
@overrides(ForwardDriver)
2021-07-31 12:24:11 +08:00
def on_shutdown(self, func: SHUTDOWN_FUNC) -> SHUTDOWN_FUNC:
"""
:说明:
注册一个停止时执行的函数
:参数:
* ``func: Callable[[], Awaitable[None]]``
"""
2021-06-21 01:22:33 +08:00
self.shutdown_funcs.add(func)
return func
@overrides(ForwardDriver)
2021-07-31 12:24:11 +08:00
def setup_http_polling(self, setup: HTTPPOLLING_SETUP) -> None:
"""
:说明:
注册一个 HTTP 轮询连接如果传入一个函数则该函数会在每次连接时被调用
:参数:
* ``setup: Union[HTTPPollingSetup, Callable[[], Awaitable[HTTPPollingSetup]]]``
"""
self.http_pollings.append(setup)
2021-07-20 15:35:56 +08:00
@overrides(ForwardDriver)
2021-07-31 12:24:11 +08:00
def setup_websocket(self, setup: WEBSOCKET_SETUP) -> None:
"""
:说明:
注册一个 WebSocket 连接如果传入一个函数则该函数会在每次重连时被调用
:参数:
* ``setup: Union[WebSocketSetup, Callable[[], Awaitable[WebSocketSetup]]]``
"""
self.websockets.append(setup)
2021-06-21 01:22:33 +08:00
@overrides(ForwardDriver)
def run(self, *args, **kwargs):
2021-07-31 12:24:11 +08:00
"""启动 aiohttp driver"""
2021-07-20 15:35:56 +08:00
super().run(*args, **kwargs)
2021-06-21 01:22:33 +08:00
loop = asyncio.get_event_loop()
2021-07-20 15:35:56 +08:00
loop.run_until_complete(self.serve())
2021-06-21 01:22:33 +08:00
2021-07-20 15:35:56 +08:00
async def serve(self):
self.install_signal_handlers()
await self.startup()
if self.should_exit.is_set():
2021-07-20 15:35:56 +08:00
return
await self.main_loop()
await self.shutdown()
2021-06-21 01:22:33 +08:00
async def startup(self):
2021-07-20 15:35:56 +08:00
for setup in self.http_pollings:
self.connections.append(asyncio.create_task(self._http_loop(setup)))
for setup in self.websockets:
self.connections.append(asyncio.create_task(self._ws_loop(setup)))
2021-07-19 01:20:17 +08:00
2021-07-20 15:35:56 +08:00
logger.info("Application startup completed.")
2021-06-21 01:22:33 +08:00
# run startup
cors = [startup() for startup in self.startup_funcs]
if cors:
try:
await asyncio.gather(*cors)
except Exception as e:
logger.opt(colors=True, exception=e).error(
"<r><bg #f8bbd0>Error when running startup function. "
"Ignored!</bg #f8bbd0></r>"
)
2021-06-21 01:22:33 +08:00
2021-07-20 15:35:56 +08:00
async def main_loop(self):
await self.should_exit.wait()
2021-06-21 01:22:33 +08:00
2021-07-20 15:35:56 +08:00
async def shutdown(self):
2021-06-21 01:22:33 +08:00
# run shutdown
cors = [shutdown() for shutdown in self.shutdown_funcs]
if cors:
try:
await asyncio.gather(*cors)
except Exception as e:
logger.opt(colors=True, exception=e).error(
"<r><bg #f8bbd0>Error when running shutdown function. "
"Ignored!</bg #f8bbd0></r>"
)
2021-06-21 01:22:33 +08:00
2021-07-20 15:35:56 +08:00
for task in self.connections:
if not task.done():
task.cancel()
await asyncio.sleep(0.1)
tasks = [t for t in asyncio.all_tasks() if t is not asyncio.current_task()]
2021-07-20 15:35:56 +08:00
if tasks and not self.force_exit:
logger.info("Waiting for tasks to finish. (CTRL+C to force quit)")
while tasks and not self.force_exit:
await asyncio.sleep(0.1)
tasks = [t for t in asyncio.all_tasks() if t is not asyncio.current_task()]
2021-06-21 01:22:33 +08:00
for task in tasks:
task.cancel()
await asyncio.gather(*tasks, return_exceptions=True)
2021-07-20 15:35:56 +08:00
loop = asyncio.get_event_loop()
2021-06-21 01:22:33 +08:00
loop.stop()
2021-07-19 01:20:17 +08:00
2021-07-20 15:35:56 +08:00
def install_signal_handlers(self) -> None:
if threading.current_thread() is not threading.main_thread():
# Signals can only be listened to from the main thread.
return
2021-07-19 14:51:28 +08:00
2021-07-20 15:35:56 +08:00
loop = asyncio.get_event_loop()
2021-07-19 14:51:28 +08:00
2021-07-20 15:35:56 +08:00
try:
for sig in HANDLED_SIGNALS:
loop.add_signal_handler(sig, self.handle_exit, sig, None)
except NotImplementedError:
# Windows
for sig in HANDLED_SIGNALS:
signal.signal(sig, self.handle_exit)
def handle_exit(self, sig, frame):
if self.should_exit.is_set():
2021-07-20 15:35:56 +08:00
self.force_exit = True
else:
self.should_exit.set()
2021-07-20 15:35:56 +08:00
2021-07-31 12:24:11 +08:00
async def _http_loop(self, setup: HTTPPOLLING_SETUP):
async def _build_request(setup: HTTPPollingSetup) -> Optional[HTTPRequest]:
2021-07-31 12:24:11 +08:00
url = URL(setup.url)
if not url.is_absolute() or not url.host:
logger.opt(colors=True).error(
f"<r><bg #f8bbd0>Error parsing url {escape_tag(str(url))}</bg #f8bbd0></r>"
)
2021-07-31 12:24:11 +08:00
return
host = f"{url.host}:{url.port}" if url.port else url.host
return HTTPRequest(
setup.http_version,
url.scheme,
url.path,
url.raw_query_string.encode("latin-1"),
{**setup.headers, "host": host},
setup.method,
setup.body,
)
2021-07-31 12:24:11 +08:00
bot: Optional[Bot] = None
request: Optional[HTTPRequest] = None
setup_: Optional[HTTPPollingSetup] = None
logger.opt(colors=True).info(
f"Start http polling for <y>{escape_tag(setup.adapter.upper())} "
f"Bot {escape_tag(setup.self_id)}</y>"
)
2021-07-19 01:20:17 +08:00
2021-07-19 14:51:28 +08:00
try:
2021-07-31 12:24:11 +08:00
async with aiohttp.ClientSession() as session:
while not self.should_exit.is_set():
try:
2021-07-31 12:24:11 +08:00
if callable(setup):
setup_ = await setup()
else:
setup_ = setup
except Exception as e:
logger.opt(colors=True, exception=e).error(
"<r><bg #f8bbd0>Error while parsing setup "
f"{escape_tag(repr(setup))}.</bg #f8bbd0></r>"
)
await asyncio.sleep(3)
continue
2021-11-19 18:18:53 +08:00
setup_ = cast(HTTPPollingSetup, setup_)
if not bot:
2021-07-31 12:24:11 +08:00
request = await _build_request(setup_)
if not request:
return
BotClass = self._adapters[setup.adapter]
bot = BotClass(setup.self_id, request)
self._bot_connect(bot)
elif callable(setup):
request = await _build_request(setup_)
if not request:
await asyncio.sleep(setup_.poll_interval)
continue
bot.request = request
request = cast(HTTPRequest, request)
headers = request.headers
timeout = aiohttp.ClientTimeout(30)
version: aiohttp.HttpVersion
if request.http_version == "1.0":
version = aiohttp.HttpVersion10
elif request.http_version == "1.1":
version = aiohttp.HttpVersion11
else:
logger.opt(colors=True).error(
"<r><bg #f8bbd0>Unsupported HTTP Version "
f"{escape_tag(request.http_version)}</bg #f8bbd0></r>"
)
2021-07-31 12:24:11 +08:00
return
2021-07-20 15:35:56 +08:00
logger.debug(
2021-07-31 12:24:11 +08:00
f"Bot {setup_.self_id} from adapter {setup_.adapter} request {setup_.url}"
2021-07-20 15:35:56 +08:00
)
2021-07-31 12:24:11 +08:00
2021-07-19 14:51:28 +08:00
try:
async with session.request(
request.method,
setup_.url,
data=request.body,
headers=headers,
timeout=timeout,
version=version,
) as response:
2021-07-19 14:51:28 +08:00
response.raise_for_status()
data = await response.read()
asyncio.create_task(bot.handle_message(data))
except aiohttp.ClientResponseError as e:
logger.opt(colors=True, exception=e).error(
f"<r><bg #f8bbd0>Error occurred while requesting {escape_tag(setup_.url)}. "
"Try to reconnect...</bg #f8bbd0></r>"
)
2021-07-19 14:51:28 +08:00
2021-07-31 12:24:11 +08:00
await asyncio.sleep(setup_.poll_interval)
2021-07-19 14:51:28 +08:00
except asyncio.CancelledError:
pass
except Exception as e:
logger.opt(colors=True, exception=e).error(
"<r><bg #f8bbd0>Unexpected exception occurred "
"while http polling</bg #f8bbd0></r>"
)
2021-07-19 14:51:28 +08:00
finally:
2021-07-31 12:24:11 +08:00
if bot:
self._bot_disconnect(bot)
2021-07-20 15:35:56 +08:00
2021-07-31 12:24:11 +08:00
async def _ws_loop(self, setup: WEBSOCKET_SETUP):
2021-07-20 15:35:56 +08:00
bot: Optional[Bot] = None
2021-07-31 12:24:11 +08:00
2021-07-19 01:20:17 +08:00
try:
2021-07-31 12:24:11 +08:00
async with aiohttp.ClientSession() as session:
2021-07-19 14:51:28 +08:00
while True:
try:
if callable(setup):
setup_ = await setup()
else:
setup_ = setup
except Exception as e:
logger.opt(colors=True, exception=e).error(
"<r><bg #f8bbd0>Error while parsing setup "
f"{escape_tag(repr(setup))}.</bg #f8bbd0></r>"
)
await asyncio.sleep(3)
continue
2021-07-31 12:24:11 +08:00
url = URL(setup_.url)
if not url.is_absolute() or not url.host:
logger.opt(colors=True).error(
f"<r><bg #f8bbd0>Error parsing url {escape_tag(str(url))}</bg #f8bbd0></r>"
2021-07-31 12:24:11 +08:00
)
await asyncio.sleep(setup_.reconnect_interval)
continue
host = f"{url.host}:{url.port}" if url.port else url.host
headers = {**setup_.headers, "host": host}
2021-07-20 15:35:56 +08:00
logger.debug(
2021-07-31 12:24:11 +08:00
f"Bot {setup_.self_id} from adapter {setup_.adapter} connecting to {url}"
2021-07-20 15:35:56 +08:00
)
try:
async with session.ws_connect(
url, headers=headers, timeout=30.0
) as ws:
logger.opt(colors=True).info(
f"WebSocket Connection to <y>{escape_tag(setup_.adapter.upper())} "
f"Bot {escape_tag(setup_.self_id)}</y> succeeded!"
)
2021-07-20 15:35:56 +08:00
request = WebSocket(
"1.1",
url.scheme,
url.path,
url.raw_query_string.encode("latin-1"),
headers,
ws,
)
2021-07-20 15:35:56 +08:00
2021-07-31 12:24:11 +08:00
BotClass = self._adapters[setup_.adapter]
bot = BotClass(setup_.self_id, request)
2021-07-20 15:35:56 +08:00
self._bot_connect(bot)
while not self.should_exit.is_set():
2021-07-20 15:35:56 +08:00
msg = await ws.receive()
if msg.type == aiohttp.WSMsgType.text:
asyncio.create_task(
bot.handle_message(msg.data.encode())
)
2021-07-20 15:35:56 +08:00
elif msg.type == aiohttp.WSMsgType.binary:
asyncio.create_task(bot.handle_message(msg.data))
2021-07-20 15:35:56 +08:00
elif msg.type == aiohttp.WSMsgType.error:
logger.opt(colors=True).error(
"<r><bg #f8bbd0>Error while handling websocket frame. "
"Try to reconnect...</bg #f8bbd0></r>"
)
2021-07-20 15:35:56 +08:00
break
else:
logger.opt(colors=True).error(
"<r><bg #f8bbd0>WebSocket connection closed by peer. "
"Try to reconnect...</bg #f8bbd0></r>"
)
2021-07-20 15:35:56 +08:00
break
except (
aiohttp.ClientResponseError,
aiohttp.ClientConnectionError,
) as e:
2021-07-20 15:35:56 +08:00
logger.opt(colors=True, exception=e).error(
f"<r><bg #f8bbd0>Error while connecting to {escape_tag(str(url))}. "
"Try to reconnect...</bg #f8bbd0></r>"
)
2021-07-20 15:35:56 +08:00
finally:
if bot:
self._bot_disconnect(bot)
bot = None
2021-11-30 12:24:09 +08:00
if not setup_.reconnect:
logger.info(
f"WebSocket reconnect disabled for bot {setup_.self_id}"
)
break
2021-07-31 12:24:11 +08:00
await asyncio.sleep(setup_.reconnect_interval)
2021-07-19 14:51:28 +08:00
except asyncio.CancelledError:
pass
except Exception as e:
logger.opt(colors=True, exception=e).error(
"<r><bg #f8bbd0>Unexpected exception occurred "
"while websocket loop</bg #f8bbd0></r>"
)
2021-07-20 15:35:56 +08:00
@dataclass
class WebSocket(BaseWebSocket):
websocket: aiohttp.ClientWebSocketResponse = None # type: ignore
@property
@overrides(BaseWebSocket)
def closed(self):
return self.websocket.closed
@overrides(BaseWebSocket)
async def accept(self):
raise NotImplementedError
@overrides(BaseWebSocket)
async def close(self, code: int = 1000):
await self.websocket.close(code=code)
@overrides(BaseWebSocket)
async def receive(self) -> str:
return await self.websocket.receive_str()
@overrides(BaseWebSocket)
async def receive_bytes(self) -> bytes:
return await self.websocket.receive_bytes()
@overrides(BaseWebSocket)
async def send(self, data: str) -> None:
await self.websocket.send_str(data)
@overrides(BaseWebSocket)
async def send_bytes(self, data: bytes) -> None:
await self.websocket.send_bytes(data)