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
+2
View File
@@ -48,6 +48,8 @@ After the database succeeds, the same nineteen result columns are uploaded as GB
```text
/网优日常优化数据文档/(勿删)干扰定时小时指标/干扰历史数据/YYYY-MM-DD/干扰数据处理结果_YYYYMMDDHHMMSS.csv
History retention reads those names, not file modification times. It keeps the latest 7 calendar days by default and deletes older date directories and result files from the file source. Set the retention days to 0 to keep everything.
```
The filename time comes from normalized `metric_time`, never the server clock. If the database already contains the target time but its history CSV is missing or empty, the script exports that time from the database and repairs the history file without reprocessing source data.
+2
View File
@@ -62,6 +62,7 @@ class Settings:
keep_outputs: int = 48
keep_runs: int = 2000
history_keep_days: int = 7
def uses_metrix_api(self) -> bool:
return self.storage_mode == "metrix" or self.database_mode == "metrix"
@@ -117,6 +118,7 @@ def validate(data: dict[str, Any], current: Settings) -> Settings:
"table_name": _identifier(merged, "table_name"),
"keep_outputs": _int(merged, "keep_outputs", 1, 1000),
"keep_runs": _int(merged, "keep_runs", 50, 100000),
"history_keep_days": _int(merged, "history_keep_days", 0, 3650),
}
settings = Settings(**values)
if settings.schedule_mode == "cron":
+66
View File
@@ -83,6 +83,9 @@ class FtpStorage:
self._call("upload", path, lambda ftp: ftp.storbinary(f"STOR {path}", io.BytesIO(payload)))
return path
def delete(self, path: str) -> None:
self._call("delete", path, lambda ftp: self._remove(ftp, path))
def close(self) -> None:
ftp, self._ftp = self._ftp, None
if ftp is None:
@@ -114,6 +117,54 @@ class FtpStorage:
self._ftp = ftp
return self._ftp
def _remove(self, ftp: ftplib.FTP, path: str) -> None:
children = self._children(ftp, path)
if children is None:
ftp.delete(path)
return
for name, is_dir in children:
child = posixpath.join(path, name)
if is_dir:
self._remove(ftp, child)
else:
ftp.delete(child)
ftp.rmd(path)
@staticmethod
def _children(ftp: ftplib.FTP, path: str) -> list[tuple[str, bool]] | None:
try:
listed = list(ftp.mlsd(path))
except ftplib.error_perm as exc:
if str(exc).startswith(FTP_UNSUPPORTED_COMMAND_CODES):
return FtpStorage._nlst_children(ftp, path)
return None
result: list[tuple[str, bool]] = []
for name, facts in listed:
if name in {".", ".."}:
continue
result.append((name, facts.get("type") == "dir"))
return result
@staticmethod
def _nlst_children(ftp: ftplib.FTP, path: str) -> list[tuple[str, bool]] | None:
try:
names = ftp.nlst(path)
except ftplib.error_perm:
return None
children: list[tuple[str, bool]] = []
for name in names:
base = posixpath.basename(name.rstrip("/"))
if base in {"", ".", ".."}:
continue
child = name if name.startswith("/") else posixpath.join(path, base)
try:
ftp.cwd(child)
ftp.cwd(path)
children.append((base, True))
except ftplib.error_perm:
children.append((base, False))
return children
def _call(self, operation: str, path: str, action: Callable[[ftplib.FTP], T]) -> T:
last_error: BaseException | None = None
for _ in range(2):
@@ -156,6 +207,9 @@ class SftpStorage:
self._call("upload", path, lambda sftp: sftp.putfo(io.BytesIO(payload), path))
return path
def delete(self, path: str) -> None:
self._call("delete", path, lambda sftp: self._remove(sftp, path))
def close(self) -> None:
transport, self._transport, self._sftp = self._transport, None, None
if transport is not None:
@@ -183,6 +237,18 @@ class SftpStorage:
self._transport, self._sftp = transport, sftp
return self._sftp
def _remove(self, sftp: paramiko.SFTPClient, path: str) -> None:
try:
attrs = sftp.stat(path)
except FileNotFoundError:
return
if stat.S_ISDIR(attrs.st_mode or 0):
for item in sftp.listdir_attr(path):
self._remove(sftp, posixpath.join(path, item.filename))
sftp.rmdir(path)
return
sftp.remove(path)
def _call(self, operation: str, path: str, action: Callable[[paramiko.SFTPClient], T]) -> T:
last_error: BaseException | None = None
for _ in range(2):
+4
View File
@@ -150,6 +150,8 @@ MESSAGES: dict[str, dict[str, str]] = {
"field.table_name": "表名",
"field.keep_outputs": "本地结果保留份数",
"field.keep_runs": "运行记录保留条数",
"field.history_keep_days": "历史数据保留天数",
"field.history_keep_days_hint": "按目录名 YYYY-MM-DD 和文件名中的日期计算,只保留最近这些天,更早的从文件来源删除。0 表示不删除。",
"option.interval": "固定间隔",
"option.cron": "Cron 表达式",
"option.storageMetrix": "Metrix 存储",
@@ -327,6 +329,8 @@ MESSAGES: dict[str, dict[str, str]] = {
"field.table_name": "Table",
"field.keep_outputs": "Local results kept",
"field.keep_runs": "Runs kept",
"field.history_keep_days": "History kept (days)",
"field.history_keep_days_hint": "Uses the YYYY-MM-DD directory name and the date in each file name. Older history is deleted from the file source. 0 keeps everything.",
"option.interval": "Interval",
"option.cron": "Cron",
"option.storageMetrix": "Metrix storage",
+2
View File
@@ -807,6 +807,8 @@ class AdminPage:
self.text("table_name")
with self.section("retention", "section.retention"):
with self.field("field.history_keep_days", "field.history_keep_days_hint"):
self.number("history_keep_days", 0, 3650)
with self.field("field.keep_outputs"):
self.number("keep_outputs", 1, 1000)
with self.field("field.keep_runs"):
+8
View File
@@ -23,6 +23,14 @@ def run(settings_path: Path, output_dir: Path, dry_run: bool) -> int:
history = None
if store is not None and settings.history_enabled:
history = main.StorageHistoryStore(storage, settings.history_root)
if not dry_run and settings.history_keep_days > 0:
try:
removed = main.StorageHistoryStore(storage, settings.history_root).prune(settings.history_keep_days)
except main.ProcessingError as exc:
print(f"history_prune_error={exc}")
else:
for path in removed:
print(f"history_removed={path}")
main.process(source, output_dir, settings.lookback_days, store=store, history=history)
finally:
close_quietly(storage)
+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:
+8
View File
@@ -5,6 +5,7 @@ import ftplib
import io
import json
import os
import shutil
import sys
import tempfile
import time
@@ -665,6 +666,13 @@ class LocalFileStorage:
(self._path(directory) / filename).write_bytes(payload)
return f"{directory}/{filename}"
def delete(self, path: str) -> None:
target = self._path(path)
if target.is_dir():
shutil.rmtree(target)
elif target.exists():
target.unlink()
class WorkerTest(unittest.TestCase):
def test_worker_processes_with_configured_storage_and_store(self) -> None:
+59
View File
@@ -411,6 +411,65 @@ class PipelineTest(unittest.TestCase):
self.assertEqual(client.uploads, [("/history/2026-08-06", "干扰数据处理结果_20260806120000.csv", b"csv-data")])
class MemoryHistoryStorage:
def __init__(self) -> None:
self.nodes: dict[str, dict[str, object]] = {"/history": {"dir": True}}
def add_dir(self, path: str) -> None:
self.nodes[path] = {"dir": True}
def add_file(self, path: str) -> None:
self.nodes[path] = {"dir": False}
def list_dir(self, path: str) -> list[dict[str, object]]:
prefix = path.rstrip("/")
result = []
for item, node in self.nodes.items():
parent, _, name = item.rpartition("/")
if parent == prefix and name:
result.append({"name": name, "path": item, "is_dir": node["dir"], "size": 1})
return result
def delete(self, path: str) -> None:
prefix = path.rstrip("/")
for item in [key for key in self.nodes if key == prefix or key.startswith(prefix + "/")]:
del self.nodes[item]
class HistoryRetentionTest(unittest.TestCase):
def test_prune_uses_directory_and_file_names(self) -> None:
storage = MemoryHistoryStorage()
storage.add_dir("/history/2026-11-01")
storage.add_file("/history/2026-11-01/干扰数据处理结果_20261101080000.csv")
storage.add_dir("/history/2026-11-09")
storage.add_file("/history/2026-11-09/干扰数据处理结果_20261109100000.csv")
storage.add_file("/history/2026-11-09/干扰数据处理结果_20261001120000.csv")
storage.add_dir("/history/readme")
storage.add_file("/history/notes.txt")
history = main.StorageHistoryStore(storage, "/history")
removed = history.prune(7, today=datetime(2026, 11, 9).date())
self.assertEqual(
removed,
[
"/history/2026-11-01",
"/history/2026-11-09/干扰数据处理结果_20261001120000.csv",
],
)
self.assertNotIn("/history/2026-11-01", storage.nodes)
self.assertIn("/history/2026-11-09/干扰数据处理结果_20261109100000.csv", storage.nodes)
self.assertIn("/history/readme", storage.nodes)
self.assertIn("/history/notes.txt", storage.nodes)
def test_zero_keep_days_deletes_nothing(self) -> None:
storage = MemoryHistoryStorage()
storage.add_dir("/history/2020-01-01")
history = main.StorageHistoryStore(storage, "/history")
self.assertEqual(history.prune(0, today=datetime(2026, 11, 9).date()), [])
self.assertIn("/history/2020-01-01", storage.nodes)
class RecordingStore:
def __init__(self, latest_time: datetime | None = None, stored_rows: list[dict[str, str]] | None = None) -> None:
self.rows: list[dict[str, str]] = []