32feb1b6db
Fixes: - F821: install.py site_url 未定义(NameError)、sync_v2.py os 未导入、script_jobs.py LOG f-string - F401: 移除 22 个未使用导入(models/__init__.py、install.py、auth.py 等) - B904: 20 个 except 块 raise 添加 from e/from None - S110: 20 个有意的 try-except-pass 添加 noqa 注释(SSH清理/DDL幂等/WS断连) - B007: 3 个未使用循环变量重命名(dirs→_dirs、server_id→_server_id) - F541: 3 个无占位符 f-string 修正 - F841: auth.py 未使用 ip_address 变量移除 - S105: auth_service.py Redis key prefix 误报 noqa - B023: script_execution_flush.py 循环变量绑定修复 Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
46 lines
1.9 KiB
Python
46 lines
1.9 KiB
Python
"""Batch-flush script execution live state from Redis to MySQL (every 60s, up to 50 rows/cycle)."""
|
|
|
|
import asyncio
|
|
import logging
|
|
|
|
from server.domain.models import AuditLog
|
|
from server.infrastructure.database.audit_log_repo import AuditLogRepositoryImpl
|
|
from server.infrastructure.database.script_repo import ScriptExecutionRepositoryImpl
|
|
from server.infrastructure.database.session import AsyncSessionLocal
|
|
from server.infrastructure.redis.script_execution_store import (
|
|
FLUSH_INTERVAL_SECONDS,
|
|
detect_stuck_executions,
|
|
flush_pending_batch,
|
|
)
|
|
|
|
logger = logging.getLogger("nexus.script_execution_flush")
|
|
|
|
|
|
async def script_execution_flush_loop():
|
|
"""Every minute: flush queued script execution snapshots to MySQL."""
|
|
logger.info("Script execution flush loop started (interval=%ss)", FLUSH_INTERVAL_SECONDS)
|
|
while True:
|
|
await asyncio.sleep(FLUSH_INTERVAL_SECONDS)
|
|
try:
|
|
async with AsyncSessionLocal() as session:
|
|
repo = ScriptExecutionRepositoryImpl(session)
|
|
audit_repo = AuditLogRepositoryImpl(session)
|
|
|
|
async def _audit(action, target_type, target_id, operator, _repo=audit_repo): # noqa: B023
|
|
await _repo.create(AuditLog(
|
|
admin_username=operator or "system",
|
|
action=action,
|
|
target_type=target_type,
|
|
target_id=target_id,
|
|
detail=f"执行ID={target_id}",
|
|
))
|
|
|
|
stuck = await detect_stuck_executions(repo, _audit)
|
|
count = await flush_pending_batch(repo)
|
|
if stuck:
|
|
logger.info("Script execution: auto-marked %s stuck", stuck)
|
|
if count:
|
|
logger.info("Script execution flush: %s record(s) written to MySQL", count)
|
|
except Exception as e:
|
|
logger.error("Script execution flush loop error: %s", e)
|