From 508088edae89d765960666961ce8b3bf4ff1b0c0 Mon Sep 17 00:00:00 2001 From: Lan_zhijiang Date: Sun, 29 Nov 2026 00:23:05 +0800 Subject: [PATCH 1/2] =?UTF-8?q?ref(core):=20=E5=90=88=E5=B9=B6=20Python=20?= =?UTF-8?q?=E6=9C=8D=E5=8A=A1=E5=85=A5=E5=8F=A3=E4=B8=8E=E5=8F=AF=E8=A7=82?= =?UTF-8?q?=E6=B5=8B=E6=80=A7=E7=94=9F=E5=91=BD=E5=91=A8=E6=9C=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .changes/python-process-owner.changed.md | 1 + .changes/python-runtime-hardening.fixed.md | 2 +- app/middleware.py | 14 -- app/persistence/observability/__init__.py | 3 - app/persistence/observability/uow.py | 10 -- docs/40-deployment/docker.md | 2 +- docs/40-deployment/runtime-orchestration.md | 9 +- inkcre_core/libs/obsrv/log_handler_logtail.py | 29 ---- .../libs/obsrv/log_handler_postgresql.py | 75 --------- inkcre_core/libs/obsrv/main.py | 11 -- .../persistence/observability/__init__.py | 1 - inkcre_core/persistence/observability/uow.py | 11 -- libs/obsrv/log_handler_logtail.py | 10 -- libs/obsrv/log_handler_postgresql.py | 10 -- pdm.lock | 38 +---- pyproject.toml | 1 - run.py | 52 +++--- scripts/automation/runtime_contract.sh | 2 +- scripts/container.py | 4 +- scripts/release.py | 1 - scripts/web.py | 45 ------ tests/test_access_log.py | 149 +++++++----------- 22 files changed, 96 insertions(+), 384 deletions(-) create mode 100644 .changes/python-process-owner.changed.md delete mode 100644 app/persistence/observability/__init__.py delete mode 100644 app/persistence/observability/uow.py delete mode 100644 inkcre_core/libs/obsrv/log_handler_logtail.py delete mode 100644 inkcre_core/libs/obsrv/log_handler_postgresql.py delete mode 100644 inkcre_core/persistence/observability/__init__.py delete mode 100644 inkcre_core/persistence/observability/uow.py delete mode 100644 libs/obsrv/log_handler_logtail.py delete mode 100644 libs/obsrv/log_handler_postgresql.py delete mode 100644 scripts/web.py diff --git a/.changes/python-process-owner.changed.md b/.changes/python-process-owner.changed.md new file mode 100644 index 00000000..be4c5bc8 --- /dev/null +++ b/.changes/python-process-owner.changed.md @@ -0,0 +1 @@ +Python 服务统一由 run.py 启动和执行进程重启。HTTP 请求 DEBUG 日志省略查询参数。Core 统一排空可观测性队列并关闭导出器,移除已停用的 Logtail 写入器及旧 PostgreSQL 日志队列。 diff --git a/.changes/python-runtime-hardening.fixed.md b/.changes/python-runtime-hardening.fixed.md index eb22a3df..8b3ce03d 100644 --- a/.changes/python-runtime-hardening.fixed.md +++ b/.changes/python-runtime-hardening.fixed.md @@ -1 +1 @@ -提高 PDF、HTTP 与 CA 证书依赖的安全版本下限,并在两种服务启动方式中移除 Uvicorn 访问日志的查询参数,避免记录 OAuth 回调凭据。 +提高 PDF、HTTP 与 CA 证书依赖的安全版本下限,并移除 Uvicorn 访问日志的查询参数,避免记录 OAuth 回调凭据。 diff --git a/app/middleware.py b/app/middleware.py index 62249f99..d37f80bc 100644 --- a/app/middleware.py +++ b/app/middleware.py @@ -15,19 +15,6 @@ from inkcre_core.libs.obsrv.main import get_logger -SENSITIVE_QUERY_PARAMETERS = frozenset( - {"access_token", "client_secret", "code", "refresh_token", "state", "token"} -) - - -def logged_query_params(request: Request) -> str: - """Render query diagnostics without persisting OAuth or credential material.""" - return "&".join( - f"{key}={'' if key.lower() in SENSITIVE_QUERY_PARAMETERS else value}" - for key, value in request.query_params.multi_items() - ) - - def create_peer_jwt( secret: str, *, now: float | None = None, lifetime_seconds: int | None = None ) -> str: @@ -97,7 +84,6 @@ async def dispatch(self, request: Request, call_next: Callable) -> Response: extra={ "method": request.method, "path": request.url.path, - "query_params": logged_query_params(request), }, ) diff --git a/app/persistence/observability/__init__.py b/app/persistence/observability/__init__.py deleted file mode 100644 index 6f9aab43..00000000 --- a/app/persistence/observability/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -"""Legacy import; use inkcre_core for new consumers.""" - -from inkcre_core.persistence.observability import * diff --git a/app/persistence/observability/uow.py b/app/persistence/observability/uow.py deleted file mode 100644 index fe555525..00000000 --- a/app/persistence/observability/uow.py +++ /dev/null @@ -1,10 +0,0 @@ -"""Legacy import; use inkcre_core for new consumers.""" - -from typing import TYPE_CHECKING -from importlib import import_module -import sys - -sys.modules[__name__] = import_module("inkcre_core.persistence.observability.uow") - -if TYPE_CHECKING: - from inkcre_core.persistence.observability.uow import * diff --git a/docs/40-deployment/docker.md b/docs/40-deployment/docker.md index 19a8bbb9..00a70d6a 100644 --- a/docs/40-deployment/docker.md +++ b/docs/40-deployment/docker.md @@ -21,7 +21,7 @@ operational helpers: The service has no entry point and defaults to `python scripts/container.py web`, which keeps Heroku's shell-based `CMD` behavior explicit. Call other supported commands with the full prefix: -- `python scripts/container.py web`: start Uvicorn on `0.0.0.0:$PORT` +- `python scripts/container.py web`: restore enabled Extensions, then run `run.py --host 0.0.0.0 --port "$PORT"` - `python scripts/container.py db `: run the explicit lifecycle surface documented in [database-contract.md](database-contract.md) - `python scripts/container.py ready`: compatibility entry point for runtime-profile readiness diff --git a/docs/40-deployment/runtime-orchestration.md b/docs/40-deployment/runtime-orchestration.md index 8c91f298..71f7cf20 100644 --- a/docs/40-deployment/runtime-orchestration.md +++ b/docs/40-deployment/runtime-orchestration.md @@ -98,10 +98,11 @@ starts from an image without Extension wheels and its writable environment is no distribution that cannot be resolved, downloaded, applied, or verified prevents that dyno from starting. The separate `ready` command and HTTP `/readyz` remain read-only and never provision packages. -The web process starts only after pre-start restoration succeeds. The `scripts/web.py` runner waits for Uvicorn’s graceful -shutdown and resource cleanup, then replaces itself with a fresh Python process after an environment application. -The new process reimports installed packages, restores exact enabled selections, and publishes readiness only after -bootstrap succeeds. If pip application fails, Core keeps the Peer paused, reports the failure in management status, +Once pre-start restoration succeeds, the container replaces its bootstrap process with `run.py`, the same Uvicorn runner +used locally. The container binds to `0.0.0.0:$PORT`, defaulting to port 8000. Local runs use the application settings by +default and accept the same `--host` and `--port` overrides. After an environment application, the runner waits for +graceful shutdown and replaces itself with the same command line. The new process reimports the installed packages, +starts the exact enabled selections, and publishes readiness after bootstrap succeeds. If pip application fails, Core keeps the Peer paused, reports the failure in management status, and does not claim that dependencies were restored. An operator must repair the environment and restart the process. Active Agent Turns are ordinary caller-owned asyncio Tasks,not scheduler jobs or deployment work records。The MVP Thread diff --git a/inkcre_core/libs/obsrv/log_handler_logtail.py b/inkcre_core/libs/obsrv/log_handler_logtail.py deleted file mode 100644 index 61a93592..00000000 --- a/inkcre_core/libs/obsrv/log_handler_logtail.py +++ /dev/null @@ -1,29 +0,0 @@ -"""Logtail logging handler.""" - -import logging -from typing import Optional - -from logtail import LogtailHandler as RealLogtailHandler - - -class LogtailHandler: - """Wrapper for Logtail handler.""" - - def __init__(self, source_token: Optional[str] = None, host: Optional[str] = None): - self.source_token = source_token - self.host = host - self.handler = None - - def get_handler(self) -> Optional[logging.Handler]: - """Get the logtail handler if available.""" - if not self.source_token: - return None - if self.handler is None: - try: - self.handler = RealLogtailHandler(source_token=self.source_token) - if self.host: - self.handler.host = self.host - self.handler.setLevel(logging.INFO) - except Exception: - return None - return self.handler diff --git a/inkcre_core/libs/obsrv/log_handler_postgresql.py b/inkcre_core/libs/obsrv/log_handler_postgresql.py deleted file mode 100644 index 5b8d0d55..00000000 --- a/inkcre_core/libs/obsrv/log_handler_postgresql.py +++ /dev/null @@ -1,75 +0,0 @@ -"""Bounded bridge from synchronous logging calls to async PostgreSQL writes.""" - -import asyncio -import logging -from queue import Empty, Full, Queue -import sys - -from inkcre_core.libs.obsrv.log_record import ENABLE_LOG_BACKEND, LogModel, adapt_log_record - - -class PostgreSQLHandler(logging.Handler): - """Capture caller context immediately; persist only while lifespan is running.""" - - def __init__(self, level: int): - super().__init__(level) - self._queue: Queue[LogModel] = Queue(maxsize=1024) - self._task: asyncio.Task[None] | None = None - self._accepting = False - self.dropped = 0 - - def start(self) -> None: - if self._task is not None: - raise RuntimeError("PostgreSQL log writer is already running") - self._accepting = True - self._task = asyncio.create_task(self._write(), name="postgresql-log-writer") - - def emit(self, record: logging.LogRecord) -> None: - if not self._accepting or not ENABLE_LOG_BACKEND.get(): - return - try: - self._queue.put_nowait(adapt_log_record(record)) - except Full: - self.dropped += 1 - if self.dropped == 1: - print("PostgreSQL log queue full; dropping backend records", file=sys.stderr) - except Exception: - self.handleError(record) - - async def _write(self) -> None: - from inkcre_core.persistence.observability.uow import write_logs - - while self._accepting or not self._queue.empty(): - batch: list[LogModel] = [] - for _ in range(100): - try: - batch.append(self._queue.get_nowait()) - except Empty: - break - if not batch: - await asyncio.sleep(0.1) - continue - try: - await write_logs(batch) - except Exception as error: - # Report through stderr, never recursively through the failed backend. - print(f"PostgreSQL log batch failed: {type(error).__name__}", file=sys.stderr) - - async def aclose(self) -> None: - # Handler.handle() holds this lock even when emit originates on a worker thread. - self.acquire() - try: - self._accepting = False - finally: - self.release() - if self._task is not None: - try: - async with asyncio.timeout(5): - await self._task - except TimeoutError: - print("PostgreSQL log drain timed out; pending records lost", file=sys.stderr) - finally: - self._task = None - while not self._queue.empty(): - self._queue.get_nowait() - super().close() diff --git a/inkcre_core/libs/obsrv/main.py b/inkcre_core/libs/obsrv/main.py index f291b79c..97ca8bb4 100644 --- a/inkcre_core/libs/obsrv/main.py +++ b/inkcre_core/libs/obsrv/main.py @@ -50,14 +50,3 @@ def get_logger() -> logging.Logger: """ global LOGGER return LOGGER - - -def start_obsrv() -> None: - """Compatibility entry; the App starts its bound runtime after config admission.""" - - -async def close_obsrv() -> None: - from .telemetry import close_telemetry - - await close_telemetry() - # Core.aclose owns its selected backend and drains it before closing the DB. diff --git a/inkcre_core/persistence/observability/__init__.py b/inkcre_core/persistence/observability/__init__.py deleted file mode 100644 index 302d1365..00000000 --- a/inkcre_core/persistence/observability/__init__.py +++ /dev/null @@ -1 +0,0 @@ -"""Isolated asynchronous telemetry persistence.""" diff --git a/inkcre_core/persistence/observability/uow.py b/inkcre_core/persistence/observability/uow.py deleted file mode 100644 index e442cde0..00000000 --- a/inkcre_core/persistence/observability/uow.py +++ /dev/null @@ -1,11 +0,0 @@ -"""Log batches commit independently of application transactions.""" - -from collections.abc import Sequence - -from inkcre_core.context import current_core -from inkcre_core.libs.obsrv.log_record import LogModel - - -async def write_logs(entries: Sequence[LogModel]) -> None: - async with current_core().sessions.begin() as session: - session.add_all(entries) diff --git a/libs/obsrv/log_handler_logtail.py b/libs/obsrv/log_handler_logtail.py deleted file mode 100644 index 8e081e1c..00000000 --- a/libs/obsrv/log_handler_logtail.py +++ /dev/null @@ -1,10 +0,0 @@ -"""Legacy import; use inkcre_core for new consumers.""" - -from typing import TYPE_CHECKING -from importlib import import_module -import sys - -sys.modules[__name__] = import_module("inkcre_core.libs.obsrv.log_handler_logtail") - -if TYPE_CHECKING: - from inkcre_core.libs.obsrv.log_handler_logtail import * diff --git a/libs/obsrv/log_handler_postgresql.py b/libs/obsrv/log_handler_postgresql.py deleted file mode 100644 index 0e4ebaa3..00000000 --- a/libs/obsrv/log_handler_postgresql.py +++ /dev/null @@ -1,10 +0,0 @@ -"""Legacy import; use inkcre_core for new consumers.""" - -from typing import TYPE_CHECKING -from importlib import import_module -import sys - -sys.modules[__name__] = import_module("inkcre_core.libs.obsrv.log_handler_postgresql") - -if TYPE_CHECKING: - from inkcre_core.libs.obsrv.log_handler_postgresql import * diff --git a/pdm.lock b/pdm.lock index 8755a35b..3c510fb7 100644 --- a/pdm.lock +++ b/pdm.lock @@ -5,7 +5,7 @@ groups = ["default", "app", "dev", "extension-preview", "extension-publisher"] strategy = ["inherit_metadata"] lock_version = "4.5.0" -content_hash = "sha256:491f995fb832f31faa7cd188431c93a302b7893e57de90d4177a62690bf2ea2f" +content_hash = "sha256:edd24851ba4ba645970e773c0800cac56d7b1a4554f971fba369c7b8d57942e3" [[metadata.targets]] requires_python = ">=3.12,<3.13" @@ -1030,21 +1030,6 @@ files = [ {file = "libpass-1.9.4.tar.gz", hash = "sha256:4ff9a5ebf51aad1e8164453bc29c4a06926cf175a9501d87205612ba247f3cbd"}, ] -[[package]] -name = "logtail-python" -version = "0.4.0" -requires_python = ">=3.10" -summary = "Better Stack client library" -groups = ["app"] -dependencies = [ - "msgpack>=0.5.6", - "requests>=2.18.4", -] -files = [ - {file = "logtail_python-0.4.0-py2.py3-none-any.whl", hash = "sha256:d9ecf4841965cfced09d747aa4ec62be586cd208d43a6af0c85a6cbd9e8f28e7"}, - {file = "logtail_python-0.4.0.tar.gz", hash = "sha256:1483cb71aad89fb1fae4c1c55be3397914057986257e5b24f4359b96e6dff30b"}, -] - [[package]] name = "lxml" version = "6.1.2" @@ -1237,27 +1222,6 @@ files = [ {file = "mdurl-0.1.2.tar.gz", hash = "sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba"}, ] -[[package]] -name = "msgpack" -version = "1.2.1" -requires_python = ">=3.10" -summary = "MessagePack serializer" -groups = ["app"] -files = [ - {file = "msgpack-1.2.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:2ef59c659f289eddf8aa6623823f19fa2f40a4029266889eac7a2505dd210c35"}, - {file = "msgpack-1.2.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:d3567748a5107cb40cdf66a275430c2f87c07777698f4bfd25c35f44d533258c"}, - {file = "msgpack-1.2.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:60926b75d00c8e816ef98f3034f484a8bc64242d66839cef4cf7e503142316a0"}, - {file = "msgpack-1.2.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:020e881a764b20d8d7ca1a54fc01b8175519d108e3c3f194fddc200bda95951a"}, - {file = "msgpack-1.2.1-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:4202c74688ca06591f78cb18988228bd4cca2cc75d57b60008372892d2f1e6e6"}, - {file = "msgpack-1.2.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:8b267ce94efb76fbd1b3373511420074ee3187f0f7811bf394531de13294735a"}, - {file = "msgpack-1.2.1-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:e4f1d0f8f98ade9634e01fb704a408f9336c0a8f1117b369f5db83dc7551d8b1"}, - {file = "msgpack-1.2.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:f02cf17a6ca1abe29b5f980644f7551f94d71f2011509b26d8625ce038f0df64"}, - {file = "msgpack-1.2.1-cp312-cp312-win32.whl", hash = "sha256:0c0d9802354507bcba62af19c17918e3eb437cc25e6f50657d511b5856a77aac"}, - {file = "msgpack-1.2.1-cp312-cp312-win_amd64.whl", hash = "sha256:5c24aa15d5963051e1a5c62b12c50cd705992502b5ec1f3bece6046f33c9fc24"}, - {file = "msgpack-1.2.1-cp312-cp312-win_arm64.whl", hash = "sha256:4227224aaec8f7fbcbfbd4272319347b2bb4030366502600f8c45588c5187b07"}, - {file = "msgpack-1.2.1.tar.gz", hash = "sha256:04c721c2c7448767e9e3f2520a475663d8ee0f09c31890f6d2bd70fd636a9647"}, -] - [[package]] name = "multidict" version = "6.7.1" diff --git a/pyproject.toml b/pyproject.toml index fd20823c..8bbdc239 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -48,7 +48,6 @@ app = [ "semantic-version (>=2.10.0,<3.0.0)", "uvicorn (>=0.35.0,<0.36.0)", "apscheduler>=3.11.0", - "logtail-python>=0.3.0", "python-telegram-bot==22.8", "alembic>=1.16.4", "alembic-utils>=0.8.8", diff --git a/run.py b/run.py index 53a9116e..bb3043d4 100644 --- a/run.py +++ b/run.py @@ -1,5 +1,6 @@ """Run API Service.""" +import argparse import asyncio import contextlib import datetime @@ -12,7 +13,7 @@ from fastapi.responses import JSONResponse # Setup logging -from inkcre_core.libs.obsrv.main import close_obsrv, setup_obsrv, start_obsrv +from inkcre_core.libs.obsrv.main import setup_obsrv from app.settings import settings from app.access_log import access_log_config @@ -95,20 +96,11 @@ from app.scheduler import drain_scheduler, scheduler, start_scheduler, with_trace_id -_CURRENT_SERVER: uvicorn.Server | None = None _REQUEST_CONDITION = asyncio.Condition() _PEER_EXECUTION_OPEN = True _ACTIVE_PEER_REQUESTS = 0 -def _request_uvicorn_exit() -> None: - if _CURRENT_SERVER is not None: - _CURRENT_SERVER.should_exit = True - - -configure_process_restart(_request_uvicorn_exit) - - async def pause_peer_execution() -> None: """Drain Core work before a shared Python environment can be changed.""" global _PEER_EXECUTION_OPEN @@ -260,7 +252,6 @@ async def bootstrap_when_database_is_ready(app: fastapi.FastAPI) -> None: @contextlib.asynccontextmanager async def lifespan(app: fastapi.FastAPI): - start_obsrv() logger.info("Application startup") RUNTIME_STATUS.set(RuntimePhase.STARTING, "runtime_bootstrap_pending") bootstrap_task = asyncio.create_task(bootstrap_when_database_is_ready(app)) @@ -286,10 +277,7 @@ async def lifespan(app: fastapi.FastAPI): if runtime_was_ready: await PeerManager.clear_self_lease() finally: - try: - await close_obsrv() - finally: - await CORE.aclose() + await CORE.aclose() api_app = fastapi.FastAPI(title="InKCre", lifespan=lifespan) @@ -394,16 +382,28 @@ async def readiness() -> JSONResponse: core_router.include_router(observability_router) api_app.include_router(core_router) -if __name__ == "__main__": - async def serve() -> None: - global _CURRENT_SERVER - config = uvicorn.Config( - api_app, host=settings.host, port=settings.port, log_config=access_log_config() - ) - _CURRENT_SERVER = uvicorn.Server(config) - await _CURRENT_SERVER.serve() - if process_restart_requested(): - os.execv(sys.executable, [sys.executable, *sys.argv]) +async def serve(host: str, port: int) -> None: + server = uvicorn.Server( + uvicorn.Config(api_app, host=host, port=port, log_config=access_log_config()) + ) - asyncio.run(serve()) + def request_exit() -> None: + server.should_exit = True + + configure_process_restart(request_exit) + await server.serve() + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--host", default=settings.host) + parser.add_argument("--port", type=int, default=settings.port) + args = parser.parse_args() + asyncio.run(serve(args.host, args.port)) + if process_restart_requested(): + os.execv(sys.executable, [sys.executable, *sys.argv]) + + +if __name__ == "__main__": + main() diff --git a/scripts/automation/runtime_contract.sh b/scripts/automation/runtime_contract.sh index 28160305..a3729bee 100644 --- a/scripts/automation/runtime_contract.sh +++ b/scripts/automation/runtime_contract.sh @@ -14,7 +14,7 @@ case "${1:-}" in ;; inspect) docker run --rm --entrypoint python "$IMAGE_TAG" -c \ - "from pathlib import Path; required=('app','libs','utils','migrations/versions','alembic.ini','scripts/container.py','scripts/web.py','scripts/database.py','scripts/verify_postgrest_contract.py'); missing=[p for p in required if not Path(p).exists()]; assert not missing, missing; assert not Path('extensions').exists(); import os,pip,site; assert all(os.access(p,os.W_OK) for p in site.getsitepackages())" + "from pathlib import Path; required=('app','libs','utils','migrations/versions','alembic.ini','scripts/container.py','run.py','scripts/database.py','scripts/verify_postgrest_contract.py'); missing=[p for p in required if not Path(p).exists()]; assert not missing, missing; assert not Path('extensions').exists(); import os,pip,site; assert all(os.access(p,os.W_OK) for p in site.getsitepackages())" ;; initialize) for name in CORE_DATABASE_PASSWORD MIGRATION_DATABASE_URL POSTGREST_DATABASE_PASSWORD; do require_env "$name"; done diff --git a/scripts/container.py b/scripts/container.py index 02704e08..21704cfe 100644 --- a/scripts/container.py +++ b/scripts/container.py @@ -39,9 +39,9 @@ async def provision() -> None: asyncio.run(provision()) - os.execvp( + os.execv( sys.executable, - [sys.executable, "scripts/web.py", "--port", port], + [sys.executable, "run.py", "--host", "0.0.0.0", "--port", port], ) return 0 diff --git a/scripts/release.py b/scripts/release.py index bf35a150..bcb5b18b 100644 --- a/scripts/release.py +++ b/scripts/release.py @@ -233,7 +233,6 @@ def affected_projects(base: str) -> set[str]: "scripts/automation/runtime_artifact.sh", "scripts/automation/runtime_contract.sh", "scripts/container.py", - "scripts/web.py", } for path in paths: parts = path.split("/") diff --git a/scripts/web.py b/scripts/web.py deleted file mode 100644 index d044e129..00000000 --- a/scripts/web.py +++ /dev/null @@ -1,45 +0,0 @@ -"""Run the web service with a same-process restart after environment changes.""" - -import argparse -import asyncio -import os -from pathlib import Path -import sys - -import uvicorn - -PROJECT_ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(PROJECT_ROOT)) - -from app.settings import settings -from app.access_log import access_log_config -from app.runtime import process_restart_requested -from run import api_app - - -def _arguments() -> argparse.Namespace: - parser = argparse.ArgumentParser() - parser.add_argument("--port", type=int, default=settings.port) - return parser.parse_args() - - -async def _serve(port: int) -> None: - config = uvicorn.Config( - api_app, host="0.0.0.0", port=port, log_config=access_log_config() - ) - server = uvicorn.Server(config) - import run - - run._CURRENT_SERVER = server - await server.serve() - - -def main() -> None: - args = _arguments() - asyncio.run(_serve(args.port)) - if process_restart_requested(): - os.execv(sys.executable, [sys.executable, *sys.argv]) - - -if __name__ == "__main__": - main() diff --git a/tests/test_access_log.py b/tests/test_access_log.py index 2c193965..b9019177 100644 --- a/tests/test_access_log.py +++ b/tests/test_access_log.py @@ -1,6 +1,5 @@ -"""Access logs retain request diagnostics without query credentials.""" +"""Keep query parameters out of HTTP logs while retaining request diagnostics.""" -from copy import deepcopy import asyncio import logging from pathlib import Path @@ -8,52 +7,16 @@ import subprocess import sys -import pytest +from fastapi import FastAPI, Response +import httpx import uvicorn -from uvicorn.config import LOGGING_CONFIG -from uvicorn.logging import AccessFormatter -from app.access_log import QuerylessAccessFilter, access_log_config +from app.access_log import access_log_config +from app.middleware import LoggingMiddleware +from inkcre_core.libs.obsrv.main import get_logger -@pytest.mark.parametrize( - ("target", "path"), - [ - ("/callback", "/callback"), - ("/callback?oauth_token=synthetic&oauth_verifier=synthetic", "/callback"), - ("/a%3Fb?search=synthetic", "/a%3Fb"), - ], -) -@pytest.mark.parametrize("status", [200, 302, 404, 500]) -def test_access_record_omits_query(target: str, path: str, status: int) -> None: - record = logging.LogRecord( - "uvicorn.access", - logging.INFO, - __file__, - 0, - '%s - "%s %s HTTP/%s" %d', - ("127.0.0.1:1234", "GET", target, "1.1", status), - None, - ) - assert QuerylessAccessFilter().filter(record) - assert record.getMessage() == f'127.0.0.1:1234 - "GET {path} HTTP/1.1" {status}' - output = AccessFormatter( - '%(client_addr)s - "%(request_line)s" %(status_code)s', use_colors=False - ).format(record) - assert f'"GET {path} HTTP/1.1" {status}' in output - assert "synthetic" not in output - assert "?" not in output - - -def test_access_configs_are_independent() -> None: - original = deepcopy(LOGGING_CONFIG) - first, second = access_log_config(), access_log_config() - first["loggers"]["uvicorn.access"]["filters"].clear() - assert second["loggers"]["uvicorn.access"]["filters"] == ["queryless_access"] - assert LOGGING_CONFIG == original - - -def test_real_uvicorn_access_records() -> None: +def test_real_uvicorn_and_application_logs_omit_query() -> None: # Uvicorn's dictConfig closes existing handlers, so isolate its whole process. result = subprocess.run( # noqa: S603 [ @@ -69,54 +32,58 @@ def test_real_uvicorn_access_records() -> None: timeout=15, ) output = result.stdout - assert output.count('"GET /callback HTTP/1.1" 204 No Content') == 2 - assert "?" not in output - assert "oauth_token" not in output - assert "synthetic" not in output - - -if __name__ == "__main__": - - async def app(scope, receive, send): - await send({"type": "http.response.start", "status": 204, "headers": []}) - await send({"type": "http.response.body", "body": b""}) - - async def probe() -> None: - with socket.socket() as sock: - sock.bind(("127.0.0.1", 0)) - sock.listen() - sock.setblocking(False) - server = uvicorn.Server( - uvicorn.Config( - app, http="h11", lifespan="off", log_config=access_log_config(), use_colors=False - ) + assert '"GET /callback HTTP/1.1" 204 No Content' in output + assert "Request started: GET /callback" in output + assert "Request completed: GET /callback 204" in output + for query_part in ("oauth_token", "search", "synthetic"): + assert query_part not in output + + +async def probe() -> None: + app = FastAPI() + app.add_middleware(LoggingMiddleware) + + @app.get("/callback") + async def callback() -> Response: + return Response(status_code=204) + + with socket.socket() as sock: + sock.bind(("127.0.0.1", 0)) + server = uvicorn.Server( + uvicorn.Config( + app, http="h11", lifespan="off", log_config=access_log_config(), use_colors=False ) - task = asyncio.create_task(server.serve(sockets=[sock])) - try: - - async def ready() -> None: - while not server.started: - if task.done(): - await task - raise RuntimeError("server exited before startup") - await asyncio.sleep(0.01) + ) + handler = logging.StreamHandler(sys.stdout) + handler.setFormatter( + logging.Formatter( + "%(message)s %(status_code)s %(query_params)s", + defaults={"status_code": "", "query_params": ""}, + ) + ) + logger = get_logger() + logger.setLevel(logging.DEBUG) + logger.addHandler(handler) + + task = asyncio.create_task(server.serve(sockets=[sock])) + try: + async with asyncio.timeout(5): + while not server.started: + if task.done(): + await task + raise RuntimeError("server exited before startup") + await asyncio.sleep(0.01) + async with httpx.AsyncClient(trust_env=False) as client: + response = await client.get( + f"http://127.0.0.1:{sock.getsockname()[1]}/callback", + params={"oauth_token": "synthetic", "search": "synthetic"}, + ) + assert response.status_code == 204 + assert response.headers["x-trace-id"] + finally: + server.should_exit = True + await asyncio.wait_for(task, 5) - await asyncio.wait_for(ready(), 5) - for target in ("/callback", "/callback?oauth_token=synthetic"): - reader, writer = await asyncio.open_connection("127.0.0.1", sock.getsockname()[1]) - try: - request_line = f"GET {target} HTTP/1.1\r\n" - writer.write( - (request_line + "Host: localhost\r\nConnection: close\r\n\r\n").encode() - ) - await writer.drain() - response = await asyncio.wait_for(reader.read(), 5) - assert response.startswith(b"HTTP/1.1 204") - finally: - writer.close() - await writer.wait_closed() - finally: - server.should_exit = True - await asyncio.wait_for(task, 5) +if __name__ == "__main__": asyncio.run(probe()) From 810c63d1bdac93bf1159f0de3551c4ea0c41c522 Mon Sep 17 00:00:00 2001 From: Lan_zhijiang Date: Sun, 29 Nov 2026 00:44:08 +0800 Subject: [PATCH 2/2] =?UTF-8?q?fix(core):=20=E4=BF=9D=E7=95=99=E5=AE=B9?= =?UTF-8?q?=E5=99=A8=E5=90=AF=E5=8A=A8=E7=9A=84=20execvp=20=E8=B0=83?= =?UTF-8?q?=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- scripts/container.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/container.py b/scripts/container.py index 21704cfe..7b2d5655 100644 --- a/scripts/container.py +++ b/scripts/container.py @@ -39,7 +39,7 @@ async def provision() -> None: asyncio.run(provision()) - os.execv( + os.execvp( sys.executable, [sys.executable, "run.py", "--host", "0.0.0.0", "--port", port], )