server.py
покрыто: 151 из 15995.0%
1"""HTTP-приложение: отдаёт страницу-песочницу и API для линтера и запросов."""23from __future__ import annotations45import json6import sqlite37from http import HTTPStatus8from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer9from pathlib import Path10from typing import Any11from urllib.parse import parse_qs, unquote, urlparse1213from . import db, query, rules1415STATIC_DIR = Path(__file__).parent / "static"16JSON_TYPE = "application/json; charset=utf-8"17HTML_TYPE = "text/html; charset=utf-8"18MAX_BODY = 64 * 102419MAX_CODE = 32 * 1024202122class ApiError(Exception):23 def __init__(self, status: HTTPStatus, message: str):24 super().__init__(message)25 self.status = status26 self.message = message272829def _json(payload: dict, status: HTTPStatus = HTTPStatus.OK) -> tuple[int, bytes, str]:30 return int(status), json.dumps(payload, ensure_ascii=False).encode("utf-8"), JSON_TYPE313233def _error(status: HTTPStatus, message: str) -> tuple[int, bytes, str]:34 return _json({"error": message}, status)353637def _int_param(values: dict[str, list[str]], name: str, default: int, maximum: int) -> int:38 try:39 number = int(values.get(name, [str(default)])[0])40 except ValueError as exc:41 raise ApiError(HTTPStatus.BAD_REQUEST, f"параметр {name} должен быть целым") from exc42 if number < 1 or number > maximum:43 raise ApiError(HTTPStatus.BAD_REQUEST, f"параметр {name} вне диапазона 1..{maximum}")44 return number454647class ApiHandler(BaseHTTPRequestHandler):48 server_version = "sql-lint/1.0"49 protocol_version = "HTTP/1.1"50 db_path = ":memory:"51 seed_on_open = True5253 # -- утилиты -----------------------------------------------------------54 def log_message(self, fmt: str, *args: Any) -> None: # noqa: A003 - API базового класса55 pass5657 def _connect(self) -> sqlite3.Connection:58 connection = sqlite3.connect(self.db_path, check_same_thread=False)59 connection.row_factory = sqlite3.Row60 connection.execute("PRAGMA query_only = ON")61 return connection6263 def _send(self, status: int, body: bytes, content_type: str) -> None:64 self.send_response(status)65 self.send_header("Content-Type", content_type)66 self.send_header("Content-Length", str(len(body)))67 self.send_header("Cache-Control", "no-store")68 self.end_headers()69 if self.command != "HEAD":70 self.wfile.write(body)7172 def _drain(self, length: int) -> None:73 """Дочитывает тело, чтобы клиент получил ответ 413, а не сброс соединения."""74 remaining = length75 while remaining > 0:76 chunk = self.rfile.read(min(64 * 1024, remaining))77 remaining = remaining - len(chunk) if chunk else 07879 def _read_json(self) -> dict:80 length = int(self.headers.get("Content-Length") or 0)81 if length > MAX_BODY:82 self._drain(length)83 raise ApiError(HTTPStatus.REQUEST_ENTITY_TOO_LARGE, f"тело больше {MAX_BODY} байт")84 raw = self.rfile.read(length) if length else b"{}"85 try:86 payload = json.loads(raw.decode("utf-8"))87 except (UnicodeDecodeError, json.JSONDecodeError) as exc:88 raise ApiError(HTTPStatus.BAD_REQUEST, "тело должно быть JSON") from exc89 if not isinstance(payload, dict):90 raise ApiError(HTTPStatus.BAD_REQUEST, "ожидался JSON-объект")91 return payload9293 # -- разбор запроса ----------------------------------------------------94 def _route_get(self, path: str, params: dict[str, list[str]]) -> tuple[int, bytes, str]:95 with self._connect() as connection:96 if path in ("/", "/index.html"):97 page = (STATIC_DIR / "app.html").read_text(encoding="utf-8")98 result = (int(HTTPStatus.OK), page.encode("utf-8"), HTML_TYPE)99 elif path == "/api/health":100 result = _json({"status": "ok", "version": "1.0.0", "tables": len(db.table_counts(connection))})101 elif path == "/api/schema":102 result = _json({"tables": db.tables(connection)})103 elif path.startswith("/api/table/"):104 name = unquote(path[len("/api/table/"):])105 result = _table(connection, name, _int_param(params, "limit", 20, 200))106 elif path == "/favicon.ico":107 result = (int(HTTPStatus.NO_CONTENT), b"", "image/x-icon")108 else:109 result = _error(HTTPStatus.NOT_FOUND, f"маршрут {path} не найден")110 return result111112 def _route_post(self, path: str) -> tuple[int, bytes, str]:113 payload = self._read_json()114 code = payload.get("code") or ""115 if isinstance(code, str) and len(code) > MAX_CODE:116 raise ApiError(HTTPStatus.REQUEST_ENTITY_TOO_LARGE, f"код больше {MAX_CODE} символов")117 with self._connect() as connection:118 if path == "/api/lint":119 result = _lint_response(code, payload)120 elif path == "/api/query":121 result = _query_response(connection, payload)122 elif path == "/api/analyze":123 result = _analyze_response(connection, code, payload)124 else:125 result = _error(HTTPStatus.NOT_FOUND, f"маршрут {path} не найден")126 return result127128 # -- HTTP --------------------------------------------------------------129 def do_GET(self) -> None: # noqa: N802 - имя из BaseHTTPRequestHandler130 parsed = urlparse(self.path)131 try:132 status, body, content_type = self._route_get(parsed.path, parse_qs(parsed.query))133 except ApiError as exc:134 status, body, content_type = _error(exc.status, exc.message)135 except (sqlite3.Error, OSError) as exc:136 status, body, content_type = _error(HTTPStatus.INTERNAL_SERVER_ERROR, f"ошибка сервера: {exc}")137 self._send(status, body, content_type)138139 def do_POST(self) -> None: # noqa: N802140 path = urlparse(self.path).path141 try:142 status, body, content_type = self._route_post(path)143 except ApiError as exc:144 status, body, content_type = _error(exc.status, exc.message)145 except (sqlite3.Error, OSError) as exc:146 status, body, content_type = _error(HTTPStatus.INTERNAL_SERVER_ERROR, f"ошибка сервера: {exc}")147 self._send(status, body, content_type)148149 def do_PUT(self) -> None: # noqa: N802150 self._send(*_error(HTTPStatus.METHOD_NOT_ALLOWED, "поддерживаются только GET и POST"))151152 def do_DELETE(self) -> None: # noqa: N802153 self._send(*_error(HTTPStatus.METHOD_NOT_ALLOWED, "поддерживаются только GET и POST"))154155 def do_HEAD(self) -> None: # noqa: N802156 self._send(*_error(HTTPStatus.METHOD_NOT_ALLOWED, "HEAD не поддерживается"))157158159def _table(connection: sqlite3.Connection, name: str, limit: int) -> tuple[int, bytes, str]:160 try:161 payload = db.preview(connection, name, limit)162 result = _json(payload)163 except KeyError as exc:164 result = _error(HTTPStatus.NOT_FOUND, str(exc))165 return result166167168def _lint_response(code: str, payload: dict) -> tuple[int, bytes, str]:169 max_lines = payload.get("max_lines", rules.DEFAULT_MAX_LINES)170 implicit = bool(payload.get("allow_implicit_exit", False))171 try:172 violations = rules.lint_code(code, max_lines=int(max_lines), allow_implicit_exit=implicit)173 except rules.LintError as exc:174 result = _json({"error": exc.message, "line": exc.line, "column": exc.column}, HTTPStatus.BAD_REQUEST)175 else:176 result = _json({177 "ok": not violations,178 "violations": [item.as_dict() for item in violations],179 "summary": rules.summary(violations),180 })181 return result182183184def _query_response(connection: sqlite3.Connection, payload: dict) -> tuple[int, bytes, str]:185 sql = payload.get("sql") or query.extract_sql(payload.get("code") or "") or ""186 if not sql:187 empty = query.QueryResult(sql="", error="не найден SQL: передайте поле sql или код с запросом")188 result = _json(empty.as_dict(), HTTPStatus.BAD_REQUEST)189 else:190 outcome = query.run_query(191 connection,192 sql,193 limit=int(payload.get("limit") or query.DEFAULT_LIMIT),194 timeout_ms=int(payload.get("timeout_ms") or query.DEFAULT_TIMEOUT_MS),195 )196 result = _json(outcome.as_dict(), HTTPStatus.OK if outcome.ok else HTTPStatus.BAD_REQUEST)197 return result198199200def _analyze_response(connection: sqlite3.Connection, code: str, payload: dict) -> tuple[int, bytes, str]:201 try:202 violations = rules.lint_code(code)203 except rules.LintError as exc:204 result = _json({"error": exc.message, "line": exc.line, "column": exc.column}, HTTPStatus.BAD_REQUEST)205 else:206 sql = query.extract_sql(code) or ""207 outcome = query.run_query(connection, sql) if sql else None208 result = _json({209 "ok": not violations,210 "violations": [item.as_dict() for item in violations],211 "summary": rules.summary(violations),212 "sql": sql,213 "query": outcome.as_dict() if outcome is not None else None,214 })215 return result216217218def make_server(db_path: str, port: int = 0, seed_data: bool = True) -> ThreadingHTTPServer:219 if seed_data:220 connection = db.connect(db_path)221 if not db.table_counts(connection).get("client"):222 db.seed(connection)223 connection.close()224 handler = type("BoundApiHandler", (ApiHandler,), {"db_path": db_path})225 server = ThreadingHTTPServer(("127.0.0.1", port), handler)226 server.daemon_threads = True227 return server← ко всем файлам