fix: auto-fix code issues (cron)

- 修复隐式 Optional 类型注解 (RUF013)
- 修复不必要的赋值后返回 (RET504)
- 优化列表推导式 (PERF401)
- 修复未使用的参数 (ARG002)
- 清理重复导入
- 优化异常处理
This commit is contained in:
AutoFix Bot
2026-03-03 21:11:47 +08:00
parent d17a58ceae
commit 259f2c90d0
36 changed files with 1651 additions and 863 deletions

View File

@@ -680,7 +680,8 @@ class OpsManager:
"""获取告警渠道"""
with self._get_db() as conn:
row = conn.execute(
"SELECT * FROM alert_channels WHERE id = ?", (channel_id,),
"SELECT * FROM alert_channels WHERE id = ?",
(channel_id,),
).fetchone()
if row:
@@ -819,7 +820,9 @@ class OpsManager:
for rule in rules:
# 获取相关指标
metrics = self.get_recent_metrics(
tenant_id, rule.metric, seconds=rule.duration + rule.evaluation_interval,
tenant_id,
rule.metric,
seconds=rule.duration + rule.evaluation_interval,
)
# 评估规则
@@ -1129,7 +1132,9 @@ class OpsManager:
async with httpx.AsyncClient() as client:
response = await client.post(
"https://events.pagerduty.com/v2/enqueue", json=message, timeout=30.0,
"https://events.pagerduty.com/v2/enqueue",
json=message,
timeout=30.0,
)
success = response.status_code == 202
self._update_channel_stats(channel.id, success)
@@ -1299,12 +1304,16 @@ class OpsManager:
conn.commit()
def _update_alert_notification_status(
self, alert_id: str, channel_id: str, success: bool,
self,
alert_id: str,
channel_id: str,
success: bool,
) -> None:
"""更新告警通知状态"""
with self._get_db() as conn:
row = conn.execute(
"SELECT notification_sent FROM alerts WHERE id = ?", (alert_id,),
"SELECT notification_sent FROM alerts WHERE id = ?",
(alert_id,),
).fetchone()
if row:
@@ -1394,7 +1403,8 @@ class OpsManager:
"""检查告警是否被抑制"""
with self._get_db() as conn:
rows = conn.execute(
"SELECT * FROM alert_suppression_rules WHERE tenant_id = ?", (rule.tenant_id,),
"SELECT * FROM alert_suppression_rules WHERE tenant_id = ?",
(rule.tenant_id,),
).fetchall()
for row in rows:
@@ -1436,7 +1446,7 @@ class OpsManager:
metric_name: str,
metric_value: float,
unit: str,
metadata: dict = None,
metadata: dict | None = None,
) -> ResourceMetric:
"""记录资源指标"""
metric_id = f"rm_{uuid.uuid4().hex[:16]}"
@@ -1479,7 +1489,10 @@ class OpsManager:
return metric
def get_recent_metrics(
self, tenant_id: str, metric_name: str, seconds: int = 3600,
self,
tenant_id: str,
metric_name: str,
seconds: int = 3600,
) -> list[ResourceMetric]:
"""获取最近的指标数据"""
cutoff_time = (datetime.now() - timedelta(seconds=seconds)).isoformat()
@@ -1531,7 +1544,9 @@ class OpsManager:
# 基于历史数据预测
metrics = self.get_recent_metrics(
tenant_id, f"{resource_type.value}_usage", seconds=30 * 24 * 3600,
tenant_id,
f"{resource_type.value}_usage",
seconds=30 * 24 * 3600,
)
if metrics:
@@ -1704,7 +1719,8 @@ class OpsManager:
"""获取自动扩缩容策略"""
with self._get_db() as conn:
row = conn.execute(
"SELECT * FROM auto_scaling_policies WHERE id = ?", (policy_id,),
"SELECT * FROM auto_scaling_policies WHERE id = ?",
(policy_id,),
).fetchone()
if row:
@@ -1721,7 +1737,10 @@ class OpsManager:
return [self._row_to_auto_scaling_policy(row) for row in rows]
def evaluate_scaling_policy(
self, policy_id: str, current_instances: int, current_utilization: float,
self,
policy_id: str,
current_instances: int,
current_utilization: float,
) -> ScalingEvent | None:
"""评估扩缩容策略"""
policy = self.get_auto_scaling_policy(policy_id)
@@ -1826,7 +1845,10 @@ class OpsManager:
return None
def update_scaling_event_status(
self, event_id: str, status: str, error_message: str = None,
self,
event_id: str,
status: str,
error_message: str | None = None,
) -> ScalingEvent | None:
"""更新扩缩容事件状态"""
now = datetime.now().isoformat()
@@ -1864,7 +1886,10 @@ class OpsManager:
return None
def list_scaling_events(
self, tenant_id: str, policy_id: str = None, limit: int = 100,
self,
tenant_id: str,
policy_id: str | None = None,
limit: int = 100,
) -> list[ScalingEvent]:
"""列出租户的扩缩容事件"""
query = "SELECT * FROM scaling_events WHERE tenant_id = ?"
@@ -2056,7 +2081,8 @@ class OpsManager:
start_time = time.time()
try:
reader, writer = await asyncio.wait_for(
asyncio.open_connection(host, port), timeout=check.timeout,
asyncio.open_connection(host, port),
timeout=check.timeout,
)
response_time = (time.time() - start_time) * 1000
writer.close()
@@ -2101,7 +2127,7 @@ class OpsManager:
failover_trigger: str,
auto_failover: bool = False,
failover_timeout: int = 300,
health_check_id: str = None,
health_check_id: str | None = None,
) -> FailoverConfig:
"""创建故障转移配置"""
config_id = f"fc_{uuid.uuid4().hex[:16]}"
@@ -2153,7 +2179,8 @@ class OpsManager:
"""获取故障转移配置"""
with self._get_db() as conn:
row = conn.execute(
"SELECT * FROM failover_configs WHERE id = ?", (config_id,),
"SELECT * FROM failover_configs WHERE id = ?",
(config_id,),
).fetchone()
if row:
@@ -2259,7 +2286,8 @@ class OpsManager:
"""获取故障转移事件"""
with self._get_db() as conn:
row = conn.execute(
"SELECT * FROM failover_events WHERE id = ?", (event_id,),
"SELECT * FROM failover_events WHERE id = ?",
(event_id,),
).fetchone()
if row:
@@ -2290,7 +2318,7 @@ class OpsManager:
retention_days: int = 30,
encryption_enabled: bool = True,
compression_enabled: bool = True,
storage_location: str = None,
storage_location: str | None = None,
) -> BackupJob:
"""创建备份任务"""
job_id = f"bj_{uuid.uuid4().hex[:16]}"
@@ -2410,7 +2438,9 @@ class OpsManager:
return record
def _complete_backup(self, record_id: str, size_bytes: int, checksum: str = None) -> None:
def _complete_backup(
self, record_id: str, size_bytes: int, checksum: str | None = None
) -> None:
"""完成备份"""
now = datetime.now().isoformat()
checksum = checksum or hashlib.sha256(str(time.time()).encode()).hexdigest()[:16]
@@ -2430,7 +2460,8 @@ class OpsManager:
"""获取备份记录"""
with self._get_db() as conn:
row = conn.execute(
"SELECT * FROM backup_records WHERE id = ?", (record_id,),
"SELECT * FROM backup_records WHERE id = ?",
(record_id,),
).fetchone()
if row:
@@ -2438,7 +2469,10 @@ class OpsManager:
return None
def list_backup_records(
self, tenant_id: str, job_id: str = None, limit: int = 100,
self,
tenant_id: str,
job_id: str | None = None,
limit: int = 100,
) -> list[BackupRecord]:
"""列出租户的备份记录"""
query = "SELECT * FROM backup_records WHERE tenant_id = ?"
@@ -2624,7 +2658,9 @@ class OpsManager:
return util
def get_resource_utilizations(
self, tenant_id: str, report_period: str,
self,
tenant_id: str,
report_period: str,
) -> list[ResourceUtilization]:
"""获取资源利用率列表"""
with self._get_db() as conn:
@@ -2709,7 +2745,8 @@ class OpsManager:
return [self._row_to_idle_resource(row) for row in rows]
def generate_cost_optimization_suggestions(
self, tenant_id: str,
self,
tenant_id: str,
) -> list[CostOptimizationSuggestion]:
"""生成成本优化建议"""
suggestions = []
@@ -2777,7 +2814,9 @@ class OpsManager:
return suggestions
def get_cost_optimization_suggestions(
self, tenant_id: str, is_applied: bool = None,
self,
tenant_id: str,
is_applied: bool | None = None,
) -> list[CostOptimizationSuggestion]:
"""获取成本优化建议"""
query = "SELECT * FROM cost_optimization_suggestions WHERE tenant_id = ?"
@@ -2794,7 +2833,8 @@ class OpsManager:
return [self._row_to_cost_optimization_suggestion(row) for row in rows]
def apply_cost_optimization_suggestion(
self, suggestion_id: str,
self,
suggestion_id: str,
) -> CostOptimizationSuggestion | None:
"""应用成本优化建议"""
now = datetime.now().isoformat()
@@ -2813,12 +2853,14 @@ class OpsManager:
return self.get_cost_optimization_suggestion(suggestion_id)
def get_cost_optimization_suggestion(
self, suggestion_id: str,
self,
suggestion_id: str,
) -> CostOptimizationSuggestion | None:
"""获取成本优化建议详情"""
with self._get_db() as conn:
row = conn.execute(
"SELECT * FROM cost_optimization_suggestions WHERE id = ?", (suggestion_id,),
"SELECT * FROM cost_optimization_suggestions WHERE id = ?",
(suggestion_id,),
).fetchone()
if row: