写一件事的时候,光有纯文本不够:要贴截图、要分段、要标重点。 这次把「正文」这条路补全,思路是**存 Markdown 而不是 HTML**—— 能导出、能全文检索、能直接喂给 LLM,也不必每次渲染都重新清洗一遍 HTML。 后端 - attachment 表 + RLS + 迁移 0005;本地磁盘存储,key 由内容 sha256 决定, 换对象存储只改 services/storage.py 一个文件 - 上传在**读流时**卡 20MB,不先落盘再判断;磁盘名由服务端生成,用户文件名只进库和响应头 - 列表带 attachment_count、详情带 attachments,避免一屏 N 次请求 - raw 直链给 <img src> 用(图片带不了 Authorization 头),只允许本工作区成员, 非成员一律 8001 不区分「不存在」与「没权限」 - 5 个用例:上传下载、超限、跨租户、删除确认与权限、raw 鉴权 前端 - 自研零依赖 Markdown 渲染器:先转义再上标签,链接协议白名单 - RichTextEditor:工具栏 + Ctrl+B/I + 预览,粘贴或拖入图片自动上传并插入引用 - AttachmentPanel:上传/下载/删除,下载走带 Authorization 的 fetch 转 blob - 任务备注、工单说明与验收结论、知识正文、评论全部接入 顺手修的 - TaskDetail.hydrate 漏了 setAttachments,导致附件面板永远是空的(e2e 抓到的) 71 passed;web tsc 0 错、构建 255.07 kB │ gzip 80.85 kB; e2e:richtext 9 项 + smoke 7 + tickets 8 + knowledge 7,全绿。
141 lines
4.8 KiB
Python
141 lines
4.8 KiB
Python
"""FastAPI 入口。"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from contextlib import asynccontextmanager
|
|
from typing import Any
|
|
|
|
from fastapi import FastAPI, Request
|
|
from fastapi.exceptions import RequestValidationError
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|
from fastapi.responses import JSONResponse
|
|
from sqlalchemy import text
|
|
from starlette.exceptions import HTTPException as StarletteHTTPException
|
|
|
|
from .api import attachments, auth, items, knowledge, tickets, workspaces
|
|
from .config import get_settings
|
|
from .db import SessionFactory, current_app_role, engine
|
|
from .errors import AppError, ErrorCode, http_status_for
|
|
from .logging_setup import get_logger, request_id_ctx, setup_logging
|
|
from .middleware import IdempotencyMiddleware, RequestContextMiddleware, error_body
|
|
|
|
settings = get_settings()
|
|
setup_logging("DEBUG" if settings.env == "dev" else "INFO")
|
|
logger = get_logger("app")
|
|
|
|
|
|
@asynccontextmanager
|
|
async def lifespan(app: FastAPI):
|
|
settings.validate_runtime()
|
|
logger.info(
|
|
"服务启动",
|
|
extra={"extra_fields": {"env": settings.env, "commit": settings.build_commit}},
|
|
)
|
|
yield
|
|
await engine.dispose()
|
|
|
|
|
|
app = FastAPI(
|
|
title=f"{settings.app_name} API",
|
|
version="0.1.0",
|
|
description="达道Task —— 任务 / 工单 / 知识库,一条流。",
|
|
lifespan=lifespan,
|
|
docs_url="/docs" if settings.env != "prod" else None,
|
|
redoc_url=None,
|
|
)
|
|
|
|
app.add_middleware(
|
|
CORSMiddleware,
|
|
allow_origins=settings.cors_origins,
|
|
allow_credentials=True,
|
|
allow_methods=["*"],
|
|
allow_headers=["*"],
|
|
expose_headers=["X-Request-Id", "X-Idempotent-Replay"],
|
|
)
|
|
# 后加的中间件先执行:RequestContext 必须最外层
|
|
app.add_middleware(IdempotencyMiddleware)
|
|
app.add_middleware(RequestContextMiddleware)
|
|
|
|
|
|
# ── 异常处理:对外永远是 {code, message, data, request_id} ──
|
|
@app.exception_handler(AppError)
|
|
async def handle_app_error(request: Request, exc: AppError) -> JSONResponse:
|
|
return JSONResponse(
|
|
status_code=exc.http_status,
|
|
content=error_body(request_id_ctx.get(), exc.code, exc.message, exc.details),
|
|
)
|
|
|
|
|
|
@app.exception_handler(RequestValidationError)
|
|
async def handle_validation(request: Request, exc: RequestValidationError) -> JSONResponse:
|
|
details: list[dict[str, Any]] = [
|
|
{"field": ".".join(str(p) for p in err["loc"][1:]), "msg": err["msg"]}
|
|
for err in exc.errors()
|
|
]
|
|
return JSONResponse(
|
|
status_code=422,
|
|
content=error_body(
|
|
request_id_ctx.get(), ErrorCode.VALIDATION_FAILED, "参数校验失败", details
|
|
),
|
|
)
|
|
|
|
|
|
@app.exception_handler(StarletteHTTPException)
|
|
async def handle_http(request: Request, exc: StarletteHTTPException) -> JSONResponse:
|
|
code = ErrorCode.NOT_FOUND if exc.status_code == 404 else ErrorCode.BAD_REQUEST
|
|
return JSONResponse(
|
|
status_code=exc.status_code,
|
|
content=error_body(request_id_ctx.get(), code, str(exc.detail)),
|
|
)
|
|
|
|
|
|
@app.exception_handler(Exception)
|
|
async def handle_unexpected(request: Request, exc: Exception) -> JSONResponse:
|
|
logger.exception("未处理异常")
|
|
return JSONResponse(
|
|
status_code=http_status_for(ErrorCode.INTERNAL),
|
|
content=error_body(request_id_ctx.get(), ErrorCode.INTERNAL, "服务器内部错误"),
|
|
)
|
|
|
|
|
|
app.include_router(auth.router, prefix=settings.api_prefix)
|
|
app.include_router(workspaces.router, prefix=settings.api_prefix)
|
|
app.include_router(items.router, prefix=settings.api_prefix)
|
|
app.include_router(items.tag_router, prefix=settings.api_prefix)
|
|
app.include_router(tickets.router, prefix=settings.api_prefix)
|
|
app.include_router(tickets.notify_router, prefix=settings.api_prefix)
|
|
app.include_router(knowledge.router, prefix=settings.api_prefix)
|
|
app.include_router(attachments.router, prefix=settings.api_prefix)
|
|
|
|
|
|
@app.get("/health", tags=["运维"], summary="存活探针")
|
|
async def health() -> dict:
|
|
db_ok = True
|
|
try:
|
|
async with SessionFactory() as session:
|
|
await session.execute(text("SELECT 1"))
|
|
except Exception: # noqa: BLE001
|
|
logger.exception("数据库探活失败")
|
|
db_ok = False
|
|
return {"status": "ok" if db_ok else "degraded", "db": db_ok, "env": settings.env}
|
|
|
|
|
|
@app.get("/version", tags=["运维"], summary="构建标记")
|
|
async def version() -> dict:
|
|
"""部署后必须校验:commit 必须等于 git rev-parse --short HEAD。"""
|
|
role = None
|
|
try:
|
|
async with SessionFactory() as session:
|
|
role = await current_app_role(session)
|
|
except Exception: # noqa: BLE001
|
|
logger.warning("读取数据库角色失败")
|
|
|
|
return {
|
|
"app": settings.app_name,
|
|
"env": settings.env,
|
|
"commit": settings.build_commit,
|
|
"build_time": settings.build_time,
|
|
"api_prefix": settings.api_prefix,
|
|
"db_role": role,
|
|
}
|