|
7 | 7 | import json |
8 | 8 | import shutil |
9 | 9 | import urllib.request |
| 10 | +import time |
10 | 11 |
|
11 | 12 | from transformerlab.shared import dirs |
12 | 13 |
|
@@ -103,6 +104,41 @@ def update_cache_from_remote(gallery_filename: str): |
103 | 104 | print(f"❌ Failed to update gallery from remote: {remote_gallery}") |
104 | 105 |
|
105 | 106 |
|
| 107 | +def update_cache_from_remote_if_stale(gallery_filename: str, max_age_seconds: int = 3600): |
| 108 | + """ |
| 109 | + Updates the gallery cache from remote only if the cache is older than max_age_seconds. |
| 110 | + Default max_age_seconds is 3600 (1 hour). |
| 111 | + |
| 112 | + Handles fused filesystems where getmtime() might be unreliable. |
| 113 | + """ |
| 114 | + local_cache_filename = gallery_cache_file_path(gallery_filename) |
| 115 | + |
| 116 | + # If file doesn't exist, update it |
| 117 | + if not os.path.isfile(local_cache_filename): |
| 118 | + update_cache_from_remote(gallery_filename) |
| 119 | + return |
| 120 | + |
| 121 | + # Check if cache is stale |
| 122 | + # Handle fused filesystems where getmtime() might be unreliable or unavailable |
| 123 | + try: |
| 124 | + mtime = os.path.getmtime(local_cache_filename) |
| 125 | + current_time = time.time() |
| 126 | + file_age = current_time - mtime |
| 127 | + |
| 128 | + # Sanity check: if mtime is in the future or file_age is negative, treat as unreliable |
| 129 | + if file_age < 0 or mtime > current_time: |
| 130 | + # Fused filesystem returned unreliable timestamp, update to be safe |
| 131 | + update_cache_from_remote(gallery_filename) |
| 132 | + return |
| 133 | + |
| 134 | + if file_age > max_age_seconds: |
| 135 | + update_cache_from_remote(gallery_filename) |
| 136 | + except (OSError, ValueError) as e: |
| 137 | + # getmtime() failed (e.g., on some fused filesystems), update to be safe |
| 138 | + print(f"⚠️ Could not determine cache age for {gallery_filename}, updating: {e}") |
| 139 | + update_cache_from_remote(gallery_filename) |
| 140 | + |
| 141 | + |
106 | 142 | def get_gallery_file(filename: str): |
107 | 143 | # default empty gallery returned in case of failed gallery file open |
108 | 144 | gallery = [] |
|
0 commit comments