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
@@ -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)