nonebot2/nonebot/drivers/fastapi.py

282 lines
9.4 KiB
Python
Raw Normal View History

2020-07-04 22:51:10 +08:00
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
2020-10-16 01:10:46 +08:00
"""
FastAPI 驱动适配
================
后端使用方法请参考: `FastAPI 文档`_
.. _FastAPI 文档:
https://fastapi.tiangolo.com/
"""
2020-07-04 22:51:10 +08:00
2020-08-25 18:02:18 +08:00
import hmac
2020-08-10 13:06:02 +08:00
import json
import asyncio
2020-07-04 22:51:10 +08:00
import logging
import uvicorn
2020-08-25 18:02:18 +08:00
from fastapi.responses import Response
2020-08-21 16:59:41 +08:00
from fastapi import Body, status, Header, FastAPI, Depends, HTTPException
2020-08-20 16:34:07 +08:00
from starlette.websockets import WebSocketDisconnect, WebSocket as FastAPIWebSocket
2020-07-04 22:51:10 +08:00
2020-07-05 20:39:34 +08:00
from nonebot.log import logger
2020-08-10 13:06:02 +08:00
from nonebot.config import Env, Config
from nonebot.utils import DataclassEncoder
2020-08-01 22:03:40 +08:00
from nonebot.drivers import BaseDriver, BaseWebSocket
2020-08-25 18:02:18 +08:00
from nonebot.typing import Optional, Callable, overrides
2020-07-04 22:51:10 +08:00
2020-08-20 16:34:07 +08:00
def get_auth_bearer(access_token: Optional[str] = Header(
None, alias="Authorization")):
if not access_token:
return None
scheme, _, param = access_token.partition(" ")
if scheme.lower() != "bearer":
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,
detail="Not authenticated",
headers={"WWW-Authenticate": "Bearer"})
return param
2020-07-04 22:51:10 +08:00
class Driver(BaseDriver):
2020-10-16 01:10:46 +08:00
"""FastAPI 驱动框架"""
2020-07-04 22:51:10 +08:00
2020-08-10 13:06:02 +08:00
def __init__(self, env: Env, config: Config):
super().__init__(env, config)
2020-08-07 17:51:57 +08:00
2020-07-04 22:51:10 +08:00
self._server_app = FastAPI(
debug=config.debug,
openapi_url=None,
docs_url=None,
redoc_url=None,
)
2020-07-11 17:32:03 +08:00
self._server_app.post("/{adapter}/")(self._handle_http)
self._server_app.post("/{adapter}/http")(self._handle_http)
self._server_app.websocket("/{adapter}/ws")(self._handle_ws_reverse)
self._server_app.websocket("/{adapter}/ws/")(self._handle_ws_reverse)
2020-07-05 20:39:34 +08:00
2020-08-13 15:56:09 +08:00
@property
@overrides(BaseDriver)
def type(self) -> str:
2020-10-16 01:10:46 +08:00
"""驱动名称: ``fastapi``"""
2020-08-13 15:56:09 +08:00
return "fastapi"
2020-07-04 22:51:10 +08:00
@property
2020-08-07 17:51:57 +08:00
@overrides(BaseDriver)
2020-08-11 10:44:05 +08:00
def server_app(self) -> FastAPI:
2020-10-16 01:10:46 +08:00
"""``FastAPI APP`` 对象"""
2020-07-04 22:51:10 +08:00
return self._server_app
@property
2020-08-07 17:51:57 +08:00
@overrides(BaseDriver)
2020-07-04 22:51:10 +08:00
def asgi(self):
2020-10-16 01:10:46 +08:00
"""``FastAPI APP`` 对象"""
2020-07-04 22:51:10 +08:00
return self._server_app
@property
2020-08-07 17:51:57 +08:00
@overrides(BaseDriver)
2020-08-01 22:03:40 +08:00
def logger(self) -> logging.Logger:
2020-10-16 01:10:46 +08:00
"""fastapi 使用的 logger"""
2020-07-04 22:51:10 +08:00
return logging.getLogger("fastapi")
2020-08-11 10:44:05 +08:00
@overrides(BaseDriver)
def on_startup(self, func: Callable) -> Callable:
2020-10-16 01:10:46 +08:00
"""参考文档: `Events <https://fastapi.tiangolo.com/advanced/events/#startup-event>`_"""
2020-08-11 10:44:05 +08:00
return self.server_app.on_event("startup")(func)
@overrides(BaseDriver)
def on_shutdown(self, func: Callable) -> Callable:
2020-10-16 01:10:46 +08:00
"""参考文档: `Events <https://fastapi.tiangolo.com/advanced/events/#startup-event>`_"""
2020-08-11 10:44:05 +08:00
return self.server_app.on_event("shutdown")(func)
2020-08-07 17:51:57 +08:00
@overrides(BaseDriver)
2020-07-04 22:51:10 +08:00
def run(self,
2020-08-18 17:24:49 +08:00
host: Optional[str] = None,
2020-07-04 22:51:10 +08:00
port: Optional[int] = None,
*,
app: Optional[str] = None,
**kwargs):
2020-10-16 01:10:46 +08:00
"""使用 ``uvicorn`` 启动 FastAPI"""
2020-07-04 22:51:10 +08:00
LOGGING_CONFIG = {
"version": 1,
"disable_existing_loggers": False,
"handlers": {
"default": {
2020-08-27 13:27:42 +08:00
"class": "nonebot.log.LoguruHandler",
2020-07-04 22:51:10 +08:00
},
},
"loggers": {
"uvicorn.error": {
"handlers": ["default"],
"level": "INFO"
},
"uvicorn.access": {
"handlers": ["default"],
"level": "INFO",
},
},
}
uvicorn.run(app or self.server_app,
2020-08-22 14:11:04 +08:00
host=host or str(self.config.host),
2020-07-04 22:51:10 +08:00
port=port or self.config.port,
2020-08-22 14:11:04 +08:00
reload=bool(app) and self.config.debug,
2020-07-04 22:51:10 +08:00
debug=self.config.debug,
log_config=LOGGING_CONFIG,
**kwargs)
2020-07-05 20:39:34 +08:00
2020-08-07 17:51:57 +08:00
@overrides(BaseDriver)
2020-08-25 18:02:18 +08:00
async def _handle_http(self,
adapter: str,
data: dict = Body(...),
x_self_id: Optional[str] = Header(None),
2020-09-15 14:48:15 +08:00
x_signature: Optional[str] = Header(None),
auth: Optional[str] = Depends(get_auth_bearer)):
2020-08-25 18:02:18 +08:00
# 检查self_id
if not x_self_id:
logger.warning("Missing X-Self-ID Header")
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST,
detail="Missing X-Self-ID Header")
# 检查签名
2020-08-20 16:34:07 +08:00
secret = self.config.secret
2020-08-25 18:02:18 +08:00
if secret:
if not x_signature:
logger.warning("Missing Signature Header")
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,
detail="Missing Signature")
sig = hmac.new(secret.encode("utf-8"),
json.dumps(data).encode(), "sha1").hexdigest()
if x_signature != "sha1=" + sig:
logger.warning("Signature Header is invalid")
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN,
detail="Signature is invalid")
2020-09-15 14:48:15 +08:00
access_token = self.config.access_token
if access_token and access_token != auth:
logger.warning("Authorization Header is invalid"
if auth else "Missing Authorization Header")
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN,
detail="Authorization Header is invalid"
if auth else "Missing Authorization Header")
2020-08-25 18:02:18 +08:00
if not isinstance(data, dict):
logger.warning("Data received is invalid")
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST)
2020-08-10 13:06:02 +08:00
2020-08-25 18:02:18 +08:00
if x_self_id in self._clients:
logger.warning("There's already a reverse websocket api connection,"
"so the event may be handled twice.")
# 创建 Bot 对象
2020-08-13 15:23:04 +08:00
if adapter in self._adapters:
BotClass = self._adapters[adapter]
bot = BotClass(self, "http", self.config, x_self_id)
2020-08-10 13:06:02 +08:00
else:
2020-08-25 18:02:18 +08:00
logger.warning("Unknown adapter")
2020-08-21 16:59:41 +08:00
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
detail="adapter not found")
2020-08-10 13:06:02 +08:00
asyncio.create_task(bot.handle_message(data))
2020-08-25 18:02:18 +08:00
return Response("", 204)
2020-07-05 20:39:34 +08:00
2020-08-07 17:51:57 +08:00
@overrides(BaseDriver)
2020-08-20 16:34:07 +08:00
async def _handle_ws_reverse(
self,
adapter: str,
websocket: FastAPIWebSocket,
x_self_id: str = Header(None),
2020-09-15 14:48:15 +08:00
auth: Optional[str] = Depends(get_auth_bearer)):
2020-08-25 18:02:18 +08:00
ws = WebSocket(websocket)
2020-09-15 14:48:15 +08:00
access_token = self.config.access_token
if access_token and access_token != auth:
2020-08-25 18:02:18 +08:00
logger.warning("Authorization Header is invalid"
2020-09-15 14:48:15 +08:00
if auth else "Missing Authorization Header")
2020-08-25 18:02:18 +08:00
await ws.close(code=status.WS_1008_POLICY_VIOLATION)
2020-09-15 14:48:15 +08:00
return
2020-08-01 22:03:40 +08:00
2020-08-21 16:59:41 +08:00
if not x_self_id:
2020-08-25 18:02:18 +08:00
logger.warning(f"Missing X-Self-ID Header")
await ws.close(code=status.WS_1008_POLICY_VIOLATION)
2020-09-15 14:48:15 +08:00
return
2020-08-21 16:59:41 +08:00
if x_self_id in self._clients:
2020-08-25 18:02:18 +08:00
logger.warning(f"Connection Conflict: self_id {x_self_id}")
await ws.close(code=status.WS_1008_POLICY_VIOLATION)
2020-09-15 14:48:15 +08:00
return
2020-08-21 16:59:41 +08:00
2020-08-01 22:03:40 +08:00
# Create Bot Object
2020-08-21 15:42:33 +08:00
if adapter in self._adapters:
BotClass = self._adapters[adapter]
bot = BotClass(self,
"websocket",
self.config,
x_self_id,
2020-08-25 18:02:18 +08:00
websocket=ws)
2020-08-01 22:03:40 +08:00
else:
2020-08-25 18:02:18 +08:00
logger.warning("Unknown adapter")
2020-09-27 12:37:15 +08:00
await ws.close(code=status.WS_1008_POLICY_VIOLATION)
return
2020-08-01 22:03:40 +08:00
2020-08-25 18:02:18 +08:00
await ws.accept()
2020-08-10 13:06:02 +08:00
self._clients[x_self_id] = bot
2020-08-27 16:43:58 +08:00
logger.opt(colors=True).info(
f"WebSocket Connection from <y>{adapter.upper()} "
f"Bot {x_self_id}</y> Accepted!")
2020-08-14 17:41:24 +08:00
try:
2020-08-25 18:02:18 +08:00
while not ws.closed:
data = await ws.receive()
2020-08-14 17:41:24 +08:00
if not data:
continue
2020-07-05 20:39:34 +08:00
asyncio.create_task(bot.handle_message(data))
2020-08-14 17:41:24 +08:00
finally:
del self._clients[x_self_id]
class WebSocket(BaseWebSocket):
def __init__(self, websocket: FastAPIWebSocket):
super().__init__(websocket)
self._closed = None
@property
2020-08-07 17:51:57 +08:00
@overrides(BaseWebSocket)
def closed(self):
return self._closed
2020-08-07 17:51:57 +08:00
@overrides(BaseWebSocket)
async def accept(self):
await self.websocket.accept()
self._closed = False
2020-08-07 17:51:57 +08:00
@overrides(BaseWebSocket)
2020-08-01 22:03:40 +08:00
async def close(self, code: int = status.WS_1000_NORMAL_CLOSURE):
await self.websocket.close(code=code)
self._closed = True
2020-08-07 17:51:57 +08:00
@overrides(BaseWebSocket)
async def receive(self) -> Optional[dict]:
data = None
try:
data = await self.websocket.receive_json()
2020-08-25 18:02:18 +08:00
if not isinstance(data, dict):
data = None
raise ValueError
except ValueError:
2020-08-25 18:02:18 +08:00
logger.warning("Received an invalid json message.")
except WebSocketDisconnect:
self._closed = True
logger.error("WebSocket disconnected by peer.")
return data
2020-08-07 17:51:57 +08:00
@overrides(BaseWebSocket)
async def send(self, data: dict) -> None:
2020-08-10 13:06:02 +08:00
text = json.dumps(data, cls=DataclassEncoder)
await self.websocket.send({"type": "websocket.send", "text": text})