feat: 历史归档按名称默认只保留最近7天

This commit is contained in:
2026-11-09 15:03:28 +08:00
parent f849950c5a
commit 3cd1196010
9 changed files with 219 additions and 1 deletions
+68 -1
View File
@@ -9,7 +9,7 @@ import json
import math
import os
from dataclasses import dataclass
from datetime import datetime, timezone
from datetime import date, datetime, timedelta, timezone
from pathlib import Path
import posixpath
import re
@@ -22,6 +22,7 @@ from urllib.parse import quote, urlencode
from urllib.request import ProxyHandler, Request, build_opener
import warnings
import zipfile
from zoneinfo import ZoneInfo
VENDOR_DIR = Path(__file__).resolve().parent / "vendor"
@@ -98,6 +99,9 @@ SQL_IDENTIFIER_RE = re.compile(r"[A-Za-z0-9_]{1,64}")
DEFAULT_HISTORY_ROOT = f"{DEFAULT_ROOT}/干扰历史数据"
LOCAL_CSV_ENCODING = "utf-8-sig"
HISTORY_CSV_ENCODING = "gbk"
HISTORY_DIRECTORY_DAY = re.compile(r"^(\d{4})-(\d{2})-(\d{2})$")
HISTORY_FILE_STAMP = re.compile(r"(?<!\d)(\d{4})(\d{2})(\d{2})\d{6}(?!\d)")
HISTORY_FILE_DAY = re.compile(r"(?<!\d)(\d{4})-(\d{2})-(\d{2})(?!\d)")
HEADER_FDD = (
"开始时间",
@@ -296,6 +300,8 @@ class FileStorage(Protocol):
def write_bytes(self, directory: str, filename: str, payload: bytes) -> str: ...
def delete(self, path: str) -> None: ...
class MetrixApiClient:
def __init__(self, base_url: str, token: str) -> None:
@@ -345,6 +351,9 @@ class MetrixApiClient:
)
)
def delete(self, endpoint: str, query: dict[str, object], timeout: int = 120) -> object:
return self._decode_json(self._request("DELETE", endpoint, query=query, timeout=timeout))
def _request(
self,
method: str,
@@ -573,6 +582,9 @@ class MetrixStorage:
raise ProcessingError("Metrix Storage API returned an invalid upload result")
return expected_path
def delete(self, path: str) -> None:
self.client.delete(self._endpoint("files"), {"path": path})
def _endpoint(self, action: str) -> str:
return f"/api/storages/{quote(self.storage_id, safe='')}/{action}"
@@ -605,6 +617,61 @@ class StorageHistoryStore:
def _has_directory(self, directory: str) -> bool:
return any(item.get("is_dir") and item.get("path") == directory for item in self.storage.list_dir(self.root))
def prune(self, keep_days: int, today: date | None = None) -> list[str]:
"""Delete history older than the last keep_days calendar days.
A directory is dated only when its name is YYYY-MM-DD. A file is dated
from YYYYMMDDHHMMSS in its name, or from YYYY-MM-DD if that is all it has.
Modification times are not used.
"""
if keep_days <= 0:
return []
current = today or datetime.now(ZoneInfo(os.getenv("TZ") or "Asia/Shanghai")).date()
cutoff = current - timedelta(days=keep_days - 1)
removed: list[str] = []
for item in self.storage.list_dir(self.root):
name = str(item.get("name") or "")
path = str(item.get("path") or "")
if item.get("is_dir"):
folder_day = directory_day(name)
if folder_day is None:
continue
if folder_day < cutoff:
self.storage.delete(path)
removed.append(path)
continue
for child in self.storage.list_dir(path):
if child.get("is_dir"):
continue
child_day = file_day(str(child.get("name") or ""))
if child_day is not None and child_day < cutoff:
child_path = str(child.get("path") or "")
self.storage.delete(child_path)
removed.append(child_path)
continue
named_day = file_day(name)
if named_day is not None and named_day < cutoff:
self.storage.delete(path)
removed.append(path)
return removed
def directory_day(name: str) -> date | None:
match = HISTORY_DIRECTORY_DAY.fullmatch(name)
return _calendar_day(match.groups()) if match else None
def file_day(name: str) -> date | None:
match = HISTORY_FILE_STAMP.search(name) or HISTORY_FILE_DAY.search(name)
return _calendar_day(match.groups()) if match else None
def _calendar_day(parts: tuple[str, ...]) -> date | None:
try:
return date(int(parts[0]), int(parts[1]), int(parts[2]))
except ValueError:
return None
class ApiHistoryStore(StorageHistoryStore):
def __init__(self, client: MetrixApiClient, storage_id: str, root: str = DEFAULT_HISTORY_ROOT) -> None: