refactor: 引入 safe_create_task 防止后台任务被 GC 回收,降低默认连接池和 worker 数量

- 新增 safe_create_task 统一替代裸 asyncio.create_task,通过全局集合持有 task 引用
- 默认 worker 数量从 4 降为 1,HTTP 连接池总预算从 800 降为 200
- 为 health_cache 和 affinity_manager 内存缓存增加上限淘汰机制
- MemoryCachePlugin 支持延迟启动清理任务
- gunicorn when_ready 增加 gc.collect() 并记录 post_worker_init RSS
This commit is contained in:
fawney19
2026-03-10 14:42:33 +08:00
parent 2d846b2c58
commit cfa5535f6e
22 changed files with 189 additions and 101 deletions

View File

@@ -141,7 +141,7 @@ def test_delete_user_precleans_large_tables_before_final_delete(
"src.services.user.service.UserCacheService.invalidate_user_cache",
invalidate_user_cache,
)
monkeypatch.setattr("src.services.user.service.asyncio.create_task", create_task)
monkeypatch.setattr("src.services.user.service.safe_create_task", create_task)
assert UserService.delete_user(db, "user-3") is True

View File

@@ -0,0 +1,34 @@
import pytest
from src.config.settings import Config
def test_config_defaults_to_single_worker_and_capped_http_pool(
monkeypatch: pytest.MonkeyPatch,
) -> None:
for key in (
"WEB_CONCURRENCY",
"GUNICORN_WORKERS",
"HTTP_MAX_CONNECTIONS",
"HTTP_KEEPALIVE_CONNECTIONS",
):
monkeypatch.delenv(key, raising=False)
cfg = Config()
assert cfg.worker_processes == 1
assert cfg.http_max_connections == 200
assert cfg.http_keepalive_connections == 60
def test_config_scales_http_pool_down_for_multi_worker(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("GUNICORN_WORKERS", "2")
monkeypatch.delenv("WEB_CONCURRENCY", raising=False)
monkeypatch.delenv("HTTP_MAX_CONNECTIONS", raising=False)
monkeypatch.delenv("HTTP_KEEPALIVE_CONNECTIONS", raising=False)
cfg = Config()
assert cfg.worker_processes == 2
assert cfg.http_max_connections == 100
assert cfg.http_keepalive_connections == 30