main:添加核心文件并初始化项目

新增内容:
- 创建基础项目结构。
- 添加 `.gitignore` 和 `.dockerignore` 文件。
- 编写 `pyproject.toml` 和依赖文件。
- 添加算法模块及示例算法。
- 实现核心功能模块(日志、错误处理、指标)。
- 添加开发和运行所需的相关脚本文件及文档。
This commit is contained in:
2026-02-02 10:46:01 +08:00
commit 31af5e2286
54 changed files with 5726 additions and 0 deletions

View File

@@ -0,0 +1,111 @@
"""Prometheus 指标模块"""
from prometheus_client import Counter, Histogram, Gauge, CollectorRegistry
from functools import wraps
import time
from typing import Callable
# 创建指标注册表
metrics_registry = CollectorRegistry()
# 请求计数器
request_counter = Counter(
"http_requests_total",
"Total HTTP requests",
["method", "endpoint", "status"],
registry=metrics_registry,
)
# 请求延迟直方图
request_latency = Histogram(
"http_request_duration_seconds",
"HTTP request latency",
["method", "endpoint"],
registry=metrics_registry,
)
# 算法执行计数器
algorithm_counter = Counter(
"algorithm_executions_total",
"Total algorithm executions",
["algorithm", "status"],
registry=metrics_registry,
)
# 算法执行延迟
algorithm_latency = Histogram(
"algorithm_execution_duration_seconds",
"Algorithm execution latency",
["algorithm"],
registry=metrics_registry,
)
# 当前处理中的请求数
in_progress_requests = Gauge(
"http_requests_in_progress",
"Number of HTTP requests in progress",
registry=metrics_registry,
)
def track_request(method: str, endpoint: str):
"""
装饰器跟踪HTTP请求指标
Args:
method: HTTP方法
endpoint: 端点路径
"""
def decorator(func: Callable):
@wraps(func)
async def wrapper(*args, **kwargs):
in_progress_requests.inc()
start_time = time.time()
try:
result = await func(*args, **kwargs)
status = "success"
return result
except Exception as e:
status = "error"
raise e
finally:
elapsed = time.time() - start_time
request_counter.labels(method=method, endpoint=endpoint, status=status).inc()
request_latency.labels(method=method, endpoint=endpoint).observe(elapsed)
in_progress_requests.dec()
return wrapper
return decorator
def track_algorithm_execution(algorithm_name: str):
"""
装饰器:跟踪算法执行指标
Args:
algorithm_name: 算法名称
"""
def decorator(func: Callable):
@wraps(func)
def wrapper(*args, **kwargs):
start_time = time.time()
try:
result = func(*args, **kwargs)
status = "success"
return result
except Exception as e:
status = "error"
raise e
finally:
elapsed = time.time() - start_time
algorithm_counter.labels(algorithm=algorithm_name, status=status).inc()
algorithm_latency.labels(algorithm=algorithm_name).observe(elapsed)
return wrapper
return decorator