Skip to content

backend refactor#8688

Open
Soulter wants to merge 10 commits into
masterfrom
backend-refactor
Open

backend refactor#8688
Soulter wants to merge 10 commits into
masterfrom
backend-refactor

Conversation

@Soulter

@Soulter Soulter commented Jun 8, 2026

Copy link
Copy Markdown
Member
  1. Migrate backend backbone from Quart to FastAPI
  2. Introduce more OpenAPIs to boost AstrBot economy
  3. Improve backend structures
  4. This PR is not a break change PR

Modifications / 改动点

  • This is NOT a breaking change. / 这不是一个破坏性变更。

Screenshots or Test Results / 运行截图或测试结果


Checklist / 检查清单

  • 😊 If there are new features added in the PR, I have discussed it with the authors through issues/emails, etc.
    / 如果 PR 中有新加入的功能,已经通过 Issue / 邮件等方式和作者讨论过。

  • 👀 My changes have been well-tested, and "Verification Steps" and "Screenshots" have been provided above.
    / 我的更改经过了良好的测试,并已在上方提供了“验证步骤”和“运行截图”

  • 🤓 I have ensured that no new dependencies are introduced, OR if new dependencies are introduced, they have been added to the appropriate locations in requirements.txt and pyproject.toml.
    / 我确保没有引入新依赖库,或者引入了新依赖库的同时将其添加到 requirements.txtpyproject.toml 文件相应位置。

  • 😮 My changes do not introduce malicious code.
    / 我的更改没有引入恶意代码。

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry, we are unable to review this pull request

The GitHub API does not allow us to fetch diffs exceeding 20000 lines

@github-advanced-security github-advanced-security AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CodeQL found more than 20 potential problems in the proposed changes. Check the Files changed tab for more details.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request migrates the AstrBot dashboard and webhook servers from Quart to FastAPI, introducing a new ASGI runtime adapter, a unified FastAPI webhook server, and restructuring all dashboard API endpoints into FastAPI routers. The review feedback highlights several critical issues: FastAPIAppAdapter needs to register itself on the FastAPI application state to prevent authentication failures over HTTP in local development; the require_scope dependency must be updated to check cookies to support dashboard users; the close callback in open_api.py should be an asynchronous function to ensure the WebSocket close coroutine is properly awaited; and inspect.signature in the webhook server should be called once during route registration rather than on every request to avoid performance bottlenecks.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment on lines +545 to +553

def add_url_rule(
self,
path: str,
view_func: Callable,
methods: list[str] | None = None,
endpoint: str | None = None,
) -> None:
route_path = _convert_rule(path)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The dashboard_app_adapter attribute is expected to be present on request.app.state (e.g., in _use_secure_dashboard_jwt_cookie to check debug and testing flags). However, FastAPIAppAdapter never registers itself on the FastAPI application's state. This causes request.app.state.dashboard_app_adapter to always be None, forcing secure cookies to be enabled even in local development or testing environments, which breaks authentication over HTTP. Register the adapter instance on app.state during initialization.

Suggested change
def add_url_rule(
self,
path: str,
view_func: Callable,
methods: list[str] | None = None,
endpoint: str | None = None,
) -> None:
route_path = _convert_rule(path)
class FastAPIAppAdapter:
def __init__(self, app: FastAPI, static_folder: str | None = None) -> None:
self._app = app
self.static_folder = static_folder
self._dashboard_server: Any | None = None
self.config: dict[str, Any] = {}
self.debug = False
self.testing = False
self.name = "dashboard"
app.state.dashboard_app_adapter = self

Comment on lines +142 to +145
auth_header = request.headers.get("Authorization", "").strip()
if not auth_header.startswith("Bearer "):
raise ApiError("Missing API key", status_code=401)
token = auth_header.removeprefix("Bearer ").strip()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security-high high

The require_scope dependency only extracts tokens from the Authorization header and does not check cookies. However, several dashboard-specific endpoints (e.g., in config_profiles.py, bots.py, and providers.py) use dependencies that rely on require_scope. This means logged-in dashboard users using cookie-based sessions will be denied access to these pages with a 401 Unauthorized error. Update require_scope to use _extract_dashboard_jwt(request) so it seamlessly supports both Authorization headers and cookies.

Suggested change
auth_header = request.headers.get("Authorization", "").strip()
if not auth_header.startswith("Bearer "):
raise ApiError("Missing API key", status_code=401)
token = auth_header.removeprefix("Bearer ").strip()
token = _extract_dashboard_jwt(request)
if not token:
raise ApiError("Missing API key", status_code=401)

Comment on lines +71 to +78
async def endpoint(request: Request):
if inspect.signature(view_func).parameters:
result = view_func(WebhookRequest(request))
else:
result = view_func()
if inspect.isawaitable(result):
result = await result
return _response_from_result(result)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Calling inspect.signature on every request inside the endpoint coroutine is highly inefficient and can cause significant performance bottlenecks under load. Instead, inspect the signature once when registering the route in add_url_rule and store the result in a local variable.

        has_params = bool(inspect.signature(view_func).parameters)

        async def endpoint(request: Request):
            if has_params:
                result = view_func(WebhookRequest(request))
            else:
                result = view_func()
            if inspect.isawaitable(result):
                result = await result
            return _response_from_result(result)

Comment on lines +270 to +277
await service.run_chat_websocket(
raw_api_key=_extract_ws_api_key(websocket),
receive_json=websocket.receive_json,
send_json=websocket.send_json,
close=lambda code, reason: websocket.close(code=code, reason=reason),
conf_list=_get_chat_config_list(service),
chat_bridge=_build_chat_ws_bridge(service, chat_service),
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The close callback is defined as a synchronous lambda returning a coroutine (websocket.close(...)). If the caller (run_chat_websocket) executes this callback synchronously, the coroutine will never be awaited, leading to a RuntimeWarning and failing to close the WebSocket connection. Define an asynchronous helper function instead to ensure proper awaiting.

Suggested change
await service.run_chat_websocket(
raw_api_key=_extract_ws_api_key(websocket),
receive_json=websocket.receive_json,
send_json=websocket.send_json,
close=lambda code, reason: websocket.close(code=code, reason=reason),
conf_list=_get_chat_config_list(service),
chat_bridge=_build_chat_ws_bridge(service, chat_service),
)
async def close_ws(code: int, reason: str):
await websocket.close(code=code, reason=reason)
await service.run_chat_websocket(
raw_api_key=_extract_ws_api_key(websocket),
receive_json=websocket.receive_json,
send_json=websocket.send_json,
close=close_ws,
conf_list=_get_chat_config_list(service),
chat_bridge=_build_chat_ws_bridge(service, chat_service),
)

@dosubot dosubot Bot added the size:XXL This PR changes 1000+ lines, ignoring generated files. label Jun 9, 2026

def _service_error(exc: UpdateServiceError) -> JSONResponse:
return JSONResponse(
{"status": "error", "message": str(exc), "data": None},
Soulter added 5 commits June 9, 2026 17:10
- Updated API client configuration to use a dedicated HTTP client.
- Introduced utility functions for generating options, queries, and form data for API requests.
- Refactored multiple API methods to utilize the new utility functions for improved consistency and readability.
- Renamed types for clarity and updated import statements accordingly.

feat(docs): add script to update OpenAPI JSON from YAML spec

- Created a Python script to convert OpenAPI YAML specification to JSON format.
- The script supports customizable input and output paths.
- Ensured the script handles directory creation for output paths and validates the YAML structure.
…atibility

- Changed all instances of dashboard_router to legacy_router across multiple API modules including platform, plugins, providers, sessions, skills, stats, subagents, t2i, tools, updates, and asgi_runtime.
- Updated route definitions to ensure existing endpoints remain functional under the new router structure.
- Introduced support for Quart request context in asgi_runtime to enhance compatibility with existing Quart-based plugins.
- Added a test case to validate the functionality of the new Quart request context handling in plugin extensions.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:XXL This PR changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants