File size: 5,153 Bytes
7529108
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
"""
GaiaScale Uploads Cleanup Worker
Background worker that purges temporary uploaded imagery and generated
GeoTIFF/NPZ cache products every day at 02:00 AM.
"""

from __future__ import annotations

from datetime import datetime, time, timedelta
import logging
from pathlib import Path
import threading
import time as _time
from typing import Dict, Any, Tuple

try:
    from backend.config import UPLOADS_DIR
    from backend.services.inference import inference_engine
except ImportError:
    from config import UPLOADS_DIR
    from services.inference import inference_engine

logger = logging.getLogger("gaiascale.cleanup")

PROTECTED_FILENAMES = {".gitkeep", ".gitignore"}


def get_seconds_until_next_2am(target_hour: int = 2, target_minute: int = 0) -> Tuple[float, datetime]:
    """Calculate the number of seconds until the next occurrence of target_hour:target_minute."""
    now = datetime.now()
    target = datetime.combine(now.date(), time(hour=target_hour, minute=target_minute, second=0))
    if now >= target:
        target += timedelta(days=1)
    seconds = (target - now).total_seconds()
    return max(0.0, seconds), target


def cleanup_uploads_now(min_age_seconds: int = 0) -> Dict[str, Any]:
    """
    Scans UPLOADS_DIR and deletes files, protecting .gitkeep and subdirectories.

    Args:
        min_age_seconds: Files modified more recently than this are preserved
                         (useful to avoid deleting files during an active upload).
    """
    if not UPLOADS_DIR.exists():
        return {"status": "no_directory", "files_deleted": 0, "bytes_freed": 0, "mb_freed": 0.0}

    now_ts = _time.time()
    deleted_count = 0
    bytes_freed = 0
    errors = []

    for file_path in UPLOADS_DIR.iterdir():
        if file_path.is_file():
            if file_path.name in PROTECTED_FILENAMES:
                continue

            try:
                stat = file_path.stat()
                file_age = now_ts - stat.st_mtime
                if file_age < min_age_seconds:
                    continue

                size = stat.st_size
                file_path.unlink()
                deleted_count += 1
                bytes_freed += size
            except Exception as e:
                errors.append(f"{file_path.name}: {str(e)}")

    # Clear inference_engine in-memory tensor cache
    try:
        inference_engine.cache.clear()
    except Exception:
        pass

    mb_freed = bytes_freed / (1024 * 1024)
    summary = {
        "status": "success",
        "files_deleted": deleted_count,
        "bytes_freed": bytes_freed,
        "mb_freed": round(mb_freed, 2),
        "errors": errors,
        "timestamp": datetime.now().isoformat(),
    }
    print(f"[Cleanup Worker] Cleaned uploads: {deleted_count} files removed ({round(mb_freed, 2)} MB freed).")
    return summary


class CleanupWorker:
    """
    Daemon thread worker that executes cleanup_uploads_now daily at target_hour:target_minute (default 02:00 AM).
    """

    def __init__(self, target_hour: int = 2, target_minute: int = 0):
        self.target_hour = target_hour
        self.target_minute = target_minute
        self._stop_event = threading.Event()
        self._thread: threading.Thread | None = None

    def _run_loop(self):
        print(f"[Cleanup Worker] Initialized. Scheduled to run daily at {self.target_hour:02d}:{self.target_minute:02d} local time.")
        while not self._stop_event.is_set():
            wait_seconds, target = get_seconds_until_next_2am(self.target_hour, self.target_minute)
            print(f"[Cleanup Worker] Next daily cleanup scheduled for {target.strftime('%Y-%m-%d %H:%M:%S')} (in {int(wait_seconds)}s).")

            # Sleep in intervals so stop_event can be checked without freezing on shutdown
            while wait_seconds > 0:
                if self._stop_event.is_set():
                    return
                sleep_chunk = min(wait_seconds, 30.0)
                _time.sleep(sleep_chunk)
                wait_seconds -= sleep_chunk

            if not self._stop_event.is_set():
                print(f"[Cleanup Worker] Daily 02:00 AM maintenance triggered. Purging uploads...")
                # Protect files created within the last 5 minutes in case an upload is in progress
                cleanup_uploads_now(min_age_seconds=300)

    def start(self):
        """Starts the background worker thread if not already running."""
        if self._thread is not None and self._thread.is_alive():
            return
        self._stop_event.clear()
        self._thread = threading.Thread(
            target=self._run_loop,
            name="GaiaScale-CleanupWorker",
            daemon=True
        )
        self._thread.start()

    def stop(self):
        """Signals the background worker to stop gracefully."""
        self._stop_event.set()
        if self._thread is not None and self._thread.is_alive():
            self._thread.join(timeout=2.0)

    @property
    def is_running(self) -> bool:
        return self._thread is not None and self._thread.is_alive()


# Global cleanup worker instance
cleanup_worker = CleanupWorker(target_hour=2, target_minute=0)