"""启动前清空状态:默认仅重置客户端游标,保留 SQLite 历史快照。 由 start_fresh.sh 在 uvicorn 之前调用。 - 默认保留 SQLite 历史数据,仅重置 client_id 投递游标(fresh 语义) - 设置 CLEAR_SQLITE_DATABASE=1 可强制清空 SQLite(主库 + wal/shm) - 默认保留 measure_output 以复用中间步骤(点云等) - 设置 CLEAR_MEASURE_OUTPUT=1 清空测量输出目录 - 设置 CLEAR_ACTION_OUTPUT=1 清空行为输出目录 """ from __future__ import annotations import os from pathlib import Path from app.db import _safe_rm_tree, remove_sqlite_database_files, reset_delivery_client_progress from app.settings import get_settings def _rm_legacy_json(path: Path | None) -> None: if path is None: return try: if path.is_file(): path.unlink() print(f"[prestart-fresh] removed legacy JSON {path}", flush=True) except OSError as e: print(f"[prestart-fresh] skip {path}: {e}", flush=True) def run_prestart_fresh() -> None: s = get_settings() clear_sqlite_database = os.environ.get("CLEAR_SQLITE_DATABASE", "").strip() in ( "1", "true", "yes", ) if clear_sqlite_database: remove_sqlite_database_files(s) print( f"[prestart-fresh] removed SQLite at {s.sqlite_path} (and -wal/-shm if present).", flush=True, ) else: reset_delivery_client_progress(s) print( f"[prestart-fresh] kept SQLite history, reset delivery client progress in {s.sqlite_path}.", flush=True, ) # 检查是否清空中间输出目录(默认保留以复用点云等中间步骤) clear_measure_output = os.environ.get("CLEAR_MEASURE_OUTPUT", "").strip() in ("1", "true", "yes") clear_action_output = os.environ.get("CLEAR_ACTION_OUTPUT", "").strip() in ("1", "true", "yes") if clear_measure_output: _safe_rm_tree(s.measure_output_root) print(f"[prestart-fresh] cleared measure_output: {s.measure_output_root}", flush=True) else: print(f"[prestart-fresh] kept measure_output for reuse: {s.measure_output_root}", flush=True) if clear_action_output: _safe_rm_tree(s.action_output_root) print(f"[prestart-fresh] cleared action_output: {s.action_output_root}", flush=True) else: print(f"[prestart-fresh] kept action_output: {s.action_output_root}", flush=True) # 始终清空媒体根目录和流临时目录(这些是可以重新生成的) _safe_rm_tree(s.media_root) _safe_rm_tree(s.stream_tmp_dir) print( f"[prestart-fresh] cleared media and stream_tmp: " f"media={s.media_root}, stream_tmp={s.stream_tmp_dir}", flush=True, ) # 清理旧版 JSON 状态文件(数据已迁移到 SQLite) if s.measure_watch_use_state_file and s.measure_watch_dir is not None: _rm_legacy_json(s.measure_watch_dir / ".fishmeasure_watch_processed.json") if s.action_watch_use_state_file and s.action_watch_dir is not None: _rm_legacy_json(s.action_watch_dir / ".fishaction_watch_processed.json") print("[prestart-fresh] done.", flush=True) def main() -> None: run_prestart_fresh() if __name__ == "__main__": main()