Open
feat(REST): 将 query 下沉为可扩展的 operation #16
jaxAdd on Sep 18
feat(REST): 将 query 下沉为可扩展的 operation #16
Open
Merged fromfeat/rest-operation-query-0930intoupstream-br_release_930
Total: 3 files changed+286-18
| @@ -13,18 +13,19 @@ | |||
| 13 | import json | 13 | import json |
| 14 | import os | 14 | import os |
| 15 | from collections.abc import AsyncGenerator | 15 | from collections.abc import AsyncGenerator |
| 16 | -from typing import Any | 16 | +from typing import Annotated, Any, Literal |
| 17 | 17 | ||
| 18 | -from fastapi import Body, Depends, FastAPI | 18 | +from fastapi import Depends, FastAPI, Request |
| 19 | +from fastapi.exceptions import RequestValidationError | ||
| 19 | from fastapi.responses import JSONResponse, StreamingResponse | 20 | from fastapi.responses import JSONResponse, StreamingResponse |
| 20 | -from pydantic import BaseModel, ConfigDict, Field | 21 | +from pydantic import BaseModel, ConfigDict, Field, TypeAdapter, ValidationError |
| 21 | 22 | ||
| 22 | from dataagent.interface.rest_api.middleware import SecurityLimitsMiddleware, load_rest_api_limits | 23 | from dataagent.interface.rest_api.middleware import SecurityLimitsMiddleware, load_rest_api_limits |
| 23 | from dataagent.interface.rest_api.service import DataAgentService | 24 | from dataagent.interface.rest_api.service import DataAgentService |
| 24 | 25 | ||
| 25 | 26 | ||
| 26 | class DataAgentQueryRequest(BaseModel): | 27 | class DataAgentQueryRequest(BaseModel): |
| 27 | - """DataAgent query request.""" | 28 | + """Original /api/agent/query body. Callers of this path keep this contract.""" |
| 28 | 29 | ||
| 29 | model_config = ConfigDict(extra="forbid") | 30 | model_config = ConfigDict(extra="forbid") |
| 30 | 31 | ||
| @@ -32,6 +33,30 @@ class DataAgentQueryRequest(BaseModel): | |||
| 32 | stream: bool = False | 33 | stream: bool = False |
| 33 | 34 | ||
| 34 | 35 | ||
| 36 | +class QueryContent(BaseModel): | ||
| 37 | + """Body of the query operation. stream belongs here, not on other types.""" | ||
| 38 | + | ||
| 39 | + model_config = ConfigDict(extra="forbid") | ||
| 40 | + | ||
| 41 | + query: str = Field(min_length=1) | ||
| 42 | + stream: bool = False | ||
| 43 | + | ||
| 44 | + | ||
| 45 | +class QueryRequest(BaseModel): | ||
| 46 | + """One northbound operation. type selects the operation; query is implemented first.""" | ||
| 47 | + | ||
| 48 | + model_config = ConfigDict(extra="forbid") | ||
| 49 | + | ||
| 50 | + type: Literal["query"] = Field(description="Operation type. query is one operation; more can be added later.") | ||
| 51 | + content: QueryContent | ||
| 52 | + | ||
| 53 | + | ||
| 54 | +# Discriminated by `type`. First wave registers query only. | ||
| 55 | +# Later operations add another model; they will not inherit query/stream. | ||
| 56 | +DataAgentRequest = Annotated[QueryRequest, Field(discriminator="type")] | ||
| 57 | +_DATA_AGENT_REQUEST_ADAPTER: TypeAdapter[QueryRequest] = TypeAdapter(DataAgentRequest) | ||
| 58 | + | ||
| 59 | + | ||
| 35 | _data_agent_service: DataAgentService | None = None | 60 | _data_agent_service: DataAgentService | None = None |
| 36 | _CONFIG_ENV_NAME = "DATAAGENT_REST_CONFIG" | 61 | _CONFIG_ENV_NAME = "DATAAGENT_REST_CONFIG" |
| 37 | 62 | ||
| @@ -43,6 +68,34 @@ def get_data_agent_service() -> DataAgentService: | |||
| 43 | return _data_agent_service | 68 | return _data_agent_service |
| 44 | 69 | ||
| 45 | 70 | ||
| 71 | +async def get_data_agent_request(http_request: Request) -> QueryRequest: | ||
| 72 | + """Parse a type-discriminated body. Other operations are not registered yet.""" | ||
| 73 | + try: | ||
| 74 | + payload = await http_request.json() | ||
| 75 | + except Exception as exc: | ||
| 76 | + raise RequestValidationError( | ||
| 77 | + [ | ||
| 78 | + { | ||
| 79 | + "type": "json_invalid", | ||
| 80 | + "loc": ("body",), | ||
| 81 | + "msg": "JSON decode error", | ||
| 82 | + "input": {}, | ||
| 83 | + "ctx": {"error": str(exc)}, | ||
| 84 | + } | ||
| 85 | + ] | ||
| 86 | + ) from exc | ||
| 87 | + try: | ||
| 88 | + return _DATA_AGENT_REQUEST_ADAPTER.validate_python(payload) | ||
| 89 | + except ValidationError as exc: | ||
| 90 | + errors = [] | ||
| 91 | + for err in exc.errors(): | ||
| 92 | + loc = err.get("loc", ()) | ||
| 93 | + if not loc or loc[0] != "body": | ||
| 94 | + err = {**err, "loc": ("body", *loc)} | ||
| 95 | + errors.append(err) | ||
| 96 | + raise RequestValidationError(errors, body=payload) from exc | ||
| 97 | + | ||
| 98 | + | ||
| 46 | def agent_error_payload(result: Any) -> dict[str, Any] | None: | 99 | def agent_error_payload(result: Any) -> dict[str, Any] | None: |
| 47 | """Return an agent error payload when result carries one.""" | 100 | """Return an agent error payload when result carries one.""" |
| 48 | if not isinstance(result, dict): | 101 | if not isinstance(result, dict): |
| @@ -108,17 +161,33 @@ async def health_check(): | |||
| 108 | return {"status": "ok"} | 161 | return {"status": "ok"} |
| 109 | 162 | ||
| 110 | 163 | ||
| 111 | -@app.post("/api/agent/query") | 164 | +async def _dispatch_query(query: str, stream: bool, service: DataAgentService): |
| 112 | -async def query_agent( | 165 | + """Run the query operation. Output shape is unchanged.""" |
| 113 | - request: DataAgentQueryRequest = Body(...), | 166 | + if stream: |
| 114 | - service: DataAgentService = Depends(get_data_agent_service), | 167 | + return StreamingResponse(stream_agent_events(query, service), media_type="text/event-stream") |
| 115 | -): | ||
| 116 | - """Run one DataAgent query.""" | ||
| 117 | - if request.stream: | ||
| 118 | - return StreamingResponse(stream_agent_events(request.query, service), media_type="text/event-stream") | ||
| 119 | 168 | ||
| 120 | - result = await service.query(request.query) | 169 | + result = await service.query(query) |
| 121 | payload = agent_error_payload(result) | 170 | payload = agent_error_payload(result) |
| 122 | if payload is not None: | 171 | if payload is not None: |
| 123 | return JSONResponse(status_code=int(payload.get("http_status", 500)), content=result) | 172 | return JSONResponse(status_code=int(payload.get("http_status", 500)), content=result) |
| 124 | return result | 173 | return result |
| 174 | + | ||
| 175 | + | ||
| 176 | +@app.post("/api/agent/query") | ||
| 177 | +async def query_agent( | ||
| 178 | + request: DataAgentQueryRequest, | ||
| 179 | + service: DataAgentService = Depends(get_data_agent_service), | ||
| 180 | +): | ||
| 181 | + """Original query path. Body stays {query, stream}.""" | ||
| 182 | + return await _dispatch_query(request.query, request.stream, service) | ||
| 183 | + | ||
| 184 | + | ||
| 185 | +@app.post("/api/agent/operation") | ||
| 186 | +async def agent_operation( | ||
| 187 | + request: QueryRequest = Depends(get_data_agent_request), | ||
| 188 | + service: DataAgentService = Depends(get_data_agent_service), | ||
| 189 | +): | ||
| 190 | + """New operation path. First wave only implements type=query.""" | ||
| 191 | + if isinstance(request, QueryRequest): | ||
| 192 | + return await _dispatch_query(request.content.query, request.content.stream, service) | ||
| 193 | + raise AssertionError(f"unsupported type: {getattr(request, 'type', request)}") | ||
| @@ -0,0 +1,93 @@ | |||
| 1 | +# REST 操作查询(!429) | ||
| 2 | + | ||
| 3 | +`POST /api/agent/operation`,默认地址 `http://127.0.0.1:8010`。 | ||
| 4 | + | ||
| 5 | +原来的 `POST /api/agent/query` **保留**,请求体仍是原来的 `{query, stream}`,不要改成 `type` + `content`。新结构只给 `/operation`。 | ||
| 6 | + | ||
| 7 | +兼容调用: | ||
| 8 | + | ||
| 9 | +```bash | ||
| 10 | +curl -sS -X POST "http://127.0.0.1:8010/api/agent/query" \ | ||
| 11 | + -H "Content-Type: application/json" \ | ||
| 12 | + -d '{ | ||
| 13 | + "query": "上个月销量最高的产品是什么?", | ||
| 14 | + "stream": false | ||
| 15 | + }' | ||
| 16 | +``` | ||
| 17 | + | ||
| 18 | +`type` 是操作类型(operation)。`query` 只是操作之一;现在只实现 query,其它 type 会 422。后续可加 `update` / `view` 等,字段会不同,不要再包第三层。 | ||
| 19 | + | ||
| 20 | +## 请求体(type=query) | ||
| 21 | + | ||
| 22 | +| 字段 | 类型 | 说明 | | ||
| 23 | +| --- | --- | --- | | ||
| 24 | +| `type` | 字符串 | 操作类型。取值示例:`query`(当前已实现的一种) | | ||
| 25 | +| `content` | 对象 | 该操作的内容。query 时里面只有 `query`、`stream` | | ||
| 26 | +| `content.query` | 字符串 | 提问文本,必填,长度至少 1 | | ||
| 27 | +| `content.stream` | 布尔 | 仅 query 的 content 里有。`false` 一次返回 JSON;`true` 用 SSE | | ||
| 28 | + | ||
| 29 | +```json | ||
| 30 | +{ | ||
| 31 | + "type": "query", | ||
| 32 | + "content": { | ||
| 33 | + "query": "上个月销量最高的产品是什么?", | ||
| 34 | + "stream": false | ||
| 35 | + } | ||
| 36 | +} | ||
| 37 | +``` | ||
| 38 | + | ||
| 39 | +## 同步 | ||
| 40 | + | ||
| 41 | +```bash | ||
| 42 | +curl -sS -X POST "http://127.0.0.1:8010/api/agent/operation" \ | ||
| 43 | + -H "Content-Type: application/json" \ | ||
| 44 | + -d '{ | ||
| 45 | + "type": "query", | ||
| 46 | + "content": { | ||
| 47 | + "query": "上个月销量最高的产品是什么?", | ||
| 48 | + "stream": false | ||
| 49 | + } | ||
| 50 | + }' | ||
| 51 | +``` | ||
| 52 | + | ||
| 53 | +## 流式 | ||
| 54 | + | ||
| 55 | +```bash | ||
| 56 | +curl -sS -N -X POST "http://127.0.0.1:8010/api/agent/operation" \ | ||
| 57 | + -H "Content-Type: application/json" \ | ||
| 58 | + -H "Accept: text/event-stream" \ | ||
| 59 | + -d '{ | ||
| 60 | + "type": "query", | ||
| 61 | + "content": { | ||
| 62 | + "query": "上个月销量最高的产品是什么?", | ||
| 63 | + "stream": true | ||
| 64 | + } | ||
| 65 | + }' | ||
| 66 | +``` | ||
| 67 | + | ||
| 68 | +## 同步返回 | ||
| 69 | + | ||
| 70 | +外层始终是 `{"result": ...}`。 | ||
| 71 | + | ||
| 72 | +```json | ||
| 73 | +{ | ||
| 74 | + "result": { | ||
| 75 | + "success": true, | ||
| 76 | + "message": "SQL generated.", | ||
| 77 | + "sql": "SELECT 1" | ||
| 78 | + } | ||
| 79 | +} | ||
| 80 | +``` | ||
| 81 | + | ||
| 82 | +`result.success` 为 `false` 时,HTTP 状态取 `result.http_status`(缺省 500)。 | ||
| 83 | + | ||
| 84 | +## SSE | ||
| 85 | + | ||
| 86 | +先推若干条 `event: message` 进度,最后一条是结果: | ||
| 87 | + | ||
| 88 | +```text | ||
| 89 | +event: result | ||
| 90 | +data: {"result": {"success": true, "message": "SQL generated.", "sql": "SELECT 1"}} | ||
| 91 | +``` | ||
| 92 | + | ||
| 93 | +`result` 的 `data` 与同步整包 JSON 相同。未知 `type` 会 422,不会当提问执行。 | ||
| @@ -20,6 +20,9 @@ from starlette.testclient import TestClient | |||
| 20 | 20 | ||
| 21 | from dataagent.interface.rest_api.app import app, get_data_agent_service | 21 | from dataagent.interface.rest_api.app import app, get_data_agent_service |
| 22 | 22 | ||
| 23 | +OPERATION_PATH = "/api/agent/operation" | ||
| 24 | +LEGACY_QUERY_PATH = "/api/agent/query" | ||
| 25 | + | ||
| 23 | 26 | ||
| 24 | class _StubDataAgentService: | 27 | class _StubDataAgentService: |
| 25 | """Return the submitted query without invoking the real agent.""" | 28 | """Return the submitted query without invoking the real agent.""" |
| @@ -69,23 +72,126 @@ def client() -> Iterator[TestClient]: | |||
| 69 | app.dependency_overrides.pop(get_data_agent_service, None) | 72 | app.dependency_overrides.pop(get_data_agent_service, None) |
| 70 | 73 | ||
| 71 | 74 | ||
| 75 | +def test_query_endpoint_requires_type_and_content(client: TestClient) -> None: | ||
| 76 | + """type is the discriminator; missing type is rejected.""" | ||
| 77 | + response = client.post(OPERATION_PATH, json={"content": {"query": "hello"}}) | ||
| 78 | + | ||
| 79 | + assert response.status_code == 422 | ||
| 80 | + detail = response.json()["detail"][0] | ||
| 81 | + assert detail["type"] == "union_tag_not_found" | ||
| 82 | + | ||
| 83 | + | ||
| 84 | +def test_query_endpoint_accepts_type_query(client: TestClient) -> None: | ||
| 85 | + """Query body is type + content{query, stream}. Output shape stays the same.""" | ||
| 86 | + response = client.post( | ||
| 87 | + OPERATION_PATH, | ||
| 88 | + json={"type": "query", "content": {"query": "hello", "stream": False}}, | ||
| 89 | + ) | ||
| 90 | + | ||
| 91 | + assert response.status_code == 200 | ||
| 92 | + assert response.json() == {"query": "hello"} | ||
| 93 | + | ||
| 94 | + | ||
| 95 | +def test_legacy_query_path_keeps_original_body(client: TestClient) -> None: | ||
| 96 | + """POST /api/agent/query keeps the original {query, stream} contract.""" | ||
| 97 | + response = client.post( | ||
| 98 | + LEGACY_QUERY_PATH, | ||
| 99 | + json={"query": "hello", "stream": False}, | ||
| 100 | + ) | ||
| 101 | + | ||
| 102 | + assert response.status_code == 200 | ||
| 103 | + assert response.json() == {"query": "hello"} | ||
| 104 | + | ||
| 105 | + | ||
| 106 | +def test_legacy_query_path_rejects_operation_body(client: TestClient) -> None: | ||
| 107 | + """Old query callers must not be required to send type/content.""" | ||
| 108 | + response = client.post( | ||
| 109 | + LEGACY_QUERY_PATH, | ||
| 110 | + json={"type": "query", "content": {"query": "hello", "stream": False}}, | ||
| 111 | + ) | ||
| 112 | + | ||
| 113 | + assert response.status_code == 422 | ||
| 114 | + | ||
| 115 | + | ||
| 116 | +def test_query_endpoint_rejects_string_content(client: TestClient) -> None: | ||
| 117 | + """content must be an object for type=query, not a string.""" | ||
| 118 | + response = client.post( | ||
| 119 | + OPERATION_PATH, | ||
| 120 | + json={"type": "query", "content": "hello"}, | ||
| 121 | + ) | ||
| 122 | + | ||
| 123 | + assert response.status_code == 422 | ||
| 124 | + | ||
| 125 | + | ||
| 126 | +def test_query_endpoint_rejects_unknown_type(client: TestClient) -> None: | ||
| 127 | + """Unimplemented operations must not fall through to query.""" | ||
| 128 | + response = client.post( | ||
| 129 | + OPERATION_PATH, | ||
| 130 | + json={"type": "update", "content": {"query": "hello", "stream": False}}, | ||
| 131 | + ) | ||
| 132 | + | ||
| 133 | + assert response.status_code == 422 | ||
| 134 | + detail = response.json()["detail"][0] | ||
| 135 | + assert detail["type"] == "union_tag_invalid" | ||
| 136 | + | ||
| 137 | + | ||
| 138 | +def test_query_endpoint_rejects_legacy_field_names(client: TestClient) -> None: | ||
| 139 | + """Old top-level field names operation/query are not accepted.""" | ||
| 140 | + response = client.post( | ||
| 141 | + OPERATION_PATH, | ||
| 142 | + json={"operation": "query", "query": "hello"}, | ||
| 143 | + ) | ||
| 144 | + | ||
| 145 | + assert response.status_code == 422 | ||
| 146 | + | ||
| 147 | + | ||
| 72 | def test_query_endpoint_rejects_unknown_body_fields(client: TestClient) -> None: | 148 | def test_query_endpoint_rejects_unknown_body_fields(client: TestClient) -> None: |
| 73 | response = client.post( | 149 | response = client.post( |
| 74 | - "/api/agent/query", | 150 | + LEGACY_QUERY_PATH, |
| 75 | json={"query": "hello", "unknown_field": True}, | 151 | json={"query": "hello", "unknown_field": True}, |
| 76 | ) | 152 | ) |
| 77 | 153 | ||
| 78 | assert response.status_code == 422 | 154 | assert response.status_code == 422 |
| 79 | detail = response.json()["detail"][0] | 155 | detail = response.json()["detail"][0] |
| 80 | assert detail["type"] == "extra_forbidden" | 156 | assert detail["type"] == "extra_forbidden" |
| 81 | - assert detail["loc"] == ["body", "unknown_field"] | 157 | + assert detail["loc"][-1] == "unknown_field" |
| 158 | + | ||
| 159 | + | ||
| 160 | +def test_operation_endpoint_rejects_unknown_body_fields(client: TestClient) -> None: | ||
| 161 | + response = client.post( | ||
| 162 | + OPERATION_PATH, | ||
| 163 | + json={"type": "query", "content": {"query": "hello"}, "unknown_field": True}, | ||
| 164 | + ) | ||
| 165 | + | ||
| 166 | + assert response.status_code == 422 | ||
| 167 | + detail = response.json()["detail"][0] | ||
| 168 | + assert detail["type"] == "extra_forbidden" | ||
| 169 | + assert detail["loc"][-1] == "unknown_field" | ||
| 170 | + | ||
| 171 | + | ||
| 172 | +def test_legacy_query_path_returns_detailed_sql_security_error() -> None: | ||
| 173 | + """Original /query body still returns mapped SQL security details.""" | ||
| 174 | + app.dependency_overrides[get_data_agent_service] = _StubSQLSecurityErrorService | ||
| 175 | + try: | ||
| 176 | + response = TestClient(app).post( | ||
| 177 | + LEGACY_QUERY_PATH, | ||
| 178 | + json={"query": "show missing column"}, | ||
| 179 | + ) | ||
| 180 | + finally: | ||
| 181 | + app.dependency_overrides.pop(get_data_agent_service, None) | ||
| 182 | + | ||
| 183 | + assert response.status_code == 422 | ||
| 184 | + assert response.json() == _StubSQLSecurityErrorService._result | ||
| 82 | 185 | ||
| 83 | 186 | ||
| 84 | def test_query_endpoint_returns_detailed_sql_security_error() -> None: | 187 | def test_query_endpoint_returns_detailed_sql_security_error() -> None: |
| 85 | """Non-streaming REST responses should preserve mapped SQL security details.""" | 188 | """Non-streaming REST responses should preserve mapped SQL security details.""" |
| 86 | app.dependency_overrides[get_data_agent_service] = _StubSQLSecurityErrorService | 189 | app.dependency_overrides[get_data_agent_service] = _StubSQLSecurityErrorService |
| 87 | try: | 190 | try: |
| 88 | - response = TestClient(app).post("/api/agent/query", json={"query": "show missing column"}) | 191 | + response = TestClient(app).post( |
| 192 | + OPERATION_PATH, | ||
| 193 | + json={"type": "query", "content": {"query": "show missing column"}}, | ||
| 194 | + ) | ||
| 89 | finally: | 195 | finally: |
| 90 | app.dependency_overrides.pop(get_data_agent_service, None) | 196 | app.dependency_overrides.pop(get_data_agent_service, None) |
| 91 | 197 | ||
| @@ -98,8 +204,8 @@ def test_streaming_query_returns_detailed_sql_security_error() -> None: | |||
| 98 | app.dependency_overrides[get_data_agent_service] = _StubSQLSecurityErrorService | 204 | app.dependency_overrides[get_data_agent_service] = _StubSQLSecurityErrorService |
| 99 | try: | 205 | try: |
| 100 | response = TestClient(app).post( | 206 | response = TestClient(app).post( |
| 101 | - "/api/agent/query", | 207 | + OPERATION_PATH, |
| 102 | - json={"query": "show missing column", "stream": True}, | 208 | + json={"type": "query", "content": {"query": "show missing column", "stream": True}}, |
| 103 | ) | 209 | ) |
| 104 | finally: | 210 | finally: |
| 105 | app.dependency_overrides.pop(get_data_agent_service, None) | 211 | app.dependency_overrides.pop(get_data_agent_service, None) |