topobathykit 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- topobathykit/__init__.py +33 -0
- topobathykit/api/cache_api.py +530 -0
- topobathykit/api/models.py +157 -0
- topobathykit/config.py +65 -0
- topobathykit/fusion.py +263 -0
- topobathykit/manifest.py +193 -0
- topobathykit/operators/__init__.py +9 -0
- topobathykit/operators/blend.py +114 -0
- topobathykit/policy/__init__.py +1 -0
- topobathykit/policy/loader.py +75 -0
- topobathykit/policy/schema.py +121 -0
- topobathykit/providers/__init__.py +22 -0
- topobathykit/providers/base.py +272 -0
- topobathykit/providers/copernicus_dsm.py +507 -0
- topobathykit/providers/gebco_2025.py +520 -0
- topobathykit/providers/jcu_gbr100.py +170 -0
- topobathykit/providers/nasadem.py +506 -0
- topobathykit/providers/ncei_bag.py +1482 -0
- topobathykit/providers/ncei_cudem.py +467 -0
- topobathykit/providers/noaa_bluetopo.py +1922 -0
- topobathykit/providers/noaa_topobathy.py +1609 -0
- topobathykit/providers/registry.py +105 -0
- topobathykit/providers/source_classifier.py +46 -0
- topobathykit/providers/usgs_3dep.py +526 -0
- topobathykit/providers/usgs_lidar.py +997 -0
- topobathykit/quality.py +245 -0
- topobathykit/runtime.py +1216 -0
- topobathykit/scripts/__init__.py +1 -0
- topobathykit/scripts/build_noaa_index.py +241 -0
- topobathykit/scripts/cache_manager.py +1561 -0
- topobathykit/scripts/hydrate_cache.py +265 -0
- topobathykit/utils/cache.py +93 -0
- topobathykit/vdatum.py +434 -0
- topobathykit-0.1.0.dist-info/METADATA +304 -0
- topobathykit-0.1.0.dist-info/RECORD +38 -0
- topobathykit-0.1.0.dist-info/WHEEL +4 -0
- topobathykit-0.1.0.dist-info/licenses/LICENSE +21 -0
- topobathysim/__init__.py +53 -0
topobathykit/__init__.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import contextlib
|
|
2
|
+
import logging
|
|
3
|
+
import os
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
from dotenv import load_dotenv
|
|
7
|
+
|
|
8
|
+
# Load .env variables
|
|
9
|
+
env_path = Path(__file__).resolve().parent.parent.parent / ".env"
|
|
10
|
+
if env_path.exists():
|
|
11
|
+
load_dotenv(env_path)
|
|
12
|
+
|
|
13
|
+
# Disable PROJ network to avoid HTTP 404s for obscure regional datum shift grids
|
|
14
|
+
# (e.g. Canadian shifts like NS778301.gsb or NVI27_05.GSB) that fail to download.
|
|
15
|
+
# We don't need mm-level horizontal shifts for our 15m resolution bathymetry tiles.
|
|
16
|
+
# NOTE: Forced overwrite because Conda activate scripts explicitly set PROJ_NETWORK=ON.
|
|
17
|
+
os.environ["PROJ_NETWORK"] = "OFF"
|
|
18
|
+
with contextlib.suppress(ImportError):
|
|
19
|
+
import pyproj
|
|
20
|
+
|
|
21
|
+
pyproj.network.set_network_enabled(False)
|
|
22
|
+
|
|
23
|
+
from .providers.registry import registry # noqa: E402
|
|
24
|
+
from .quality import TIDClassifier, source_report # noqa: E402
|
|
25
|
+
|
|
26
|
+
# Set up NullHandler to prevent "No handler found" warnings
|
|
27
|
+
logging.getLogger(__name__).addHandler(logging.NullHandler())
|
|
28
|
+
|
|
29
|
+
__all__ = [
|
|
30
|
+
"TIDClassifier",
|
|
31
|
+
"registry",
|
|
32
|
+
"source_report",
|
|
33
|
+
]
|
|
@@ -0,0 +1,530 @@
|
|
|
1
|
+
# Import from scripts.cache_manager, suppressing output if any
|
|
2
|
+
import contextlib
|
|
3
|
+
import io
|
|
4
|
+
import json
|
|
5
|
+
import logging
|
|
6
|
+
import math
|
|
7
|
+
import shutil
|
|
8
|
+
import time
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
from topobathykit.api.models import (
|
|
13
|
+
CacheDetail,
|
|
14
|
+
CacheSummary,
|
|
15
|
+
CacheTierInfo,
|
|
16
|
+
CacheTierSummary,
|
|
17
|
+
CheckResult,
|
|
18
|
+
DiscoveryDetail,
|
|
19
|
+
OrphansResult,
|
|
20
|
+
ProviderDetail,
|
|
21
|
+
PurgeResult,
|
|
22
|
+
RawFileDetail,
|
|
23
|
+
Tier1Detail,
|
|
24
|
+
Tier2Detail,
|
|
25
|
+
Tier3Detail,
|
|
26
|
+
Tier4Detail,
|
|
27
|
+
Tier5Detail,
|
|
28
|
+
TileSubdir,
|
|
29
|
+
ZoomDetail,
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
# We need to suppress strict type checking on this import because it's a script
|
|
33
|
+
# and mypy might complain about missing stubs or side effects.
|
|
34
|
+
try:
|
|
35
|
+
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
|
|
36
|
+
import topobathykit.scripts.cache_manager as cm
|
|
37
|
+
except ImportError:
|
|
38
|
+
# Fallback or error if script is missing
|
|
39
|
+
raise ImportError("Could not import topobathykit.scripts.cache_manager") from None
|
|
40
|
+
|
|
41
|
+
logger = logging.getLogger(__name__)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _safe_float(val: Any, default: float = 0.0) -> float:
|
|
45
|
+
"""Ensure a value is a finite float, returning default if NaN/Inf."""
|
|
46
|
+
try:
|
|
47
|
+
f = float(val)
|
|
48
|
+
if not math.isfinite(f):
|
|
49
|
+
return default
|
|
50
|
+
return f
|
|
51
|
+
except (ValueError, TypeError):
|
|
52
|
+
return default
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
# Re-export some constants for convenience
|
|
56
|
+
CACHE_ROOT = cm.CACHE_ROOT
|
|
57
|
+
TIERS = cm.TIERS
|
|
58
|
+
|
|
59
|
+
# Cache for get_summary to avoid scanning too often
|
|
60
|
+
_SUMMARY_CACHE: tuple[float, CacheSummary] | None = None
|
|
61
|
+
_SUMMARY_TTL = 5.0 # seconds
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def get_tiers() -> list[CacheTierInfo]:
|
|
65
|
+
"""Return static metadata about cache tiers."""
|
|
66
|
+
return [
|
|
67
|
+
CacheTierInfo(
|
|
68
|
+
number=t.number,
|
|
69
|
+
name=t.name,
|
|
70
|
+
short_desc=t.short_desc,
|
|
71
|
+
long_desc=t.long_desc,
|
|
72
|
+
purge_reason=t.purge_reason,
|
|
73
|
+
warning=t.warning,
|
|
74
|
+
)
|
|
75
|
+
for t in TIERS
|
|
76
|
+
]
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def get_cache_summary(cache_bust: bool = False) -> CacheSummary:
|
|
80
|
+
"""Return a lightweight summary of cache tiers."""
|
|
81
|
+
global _SUMMARY_CACHE
|
|
82
|
+
now = time.time()
|
|
83
|
+
|
|
84
|
+
if not cache_bust and _SUMMARY_CACHE is not None:
|
|
85
|
+
ts, summary = _SUMMARY_CACHE
|
|
86
|
+
if now - ts < _SUMMARY_TTL:
|
|
87
|
+
return summary
|
|
88
|
+
|
|
89
|
+
total_bytes = 0
|
|
90
|
+
tier_summaries: list[CacheTierSummary] = []
|
|
91
|
+
|
|
92
|
+
# Map tier numbers to the API endpoint that generates them
|
|
93
|
+
tier_origins = {
|
|
94
|
+
1: "/tiles",
|
|
95
|
+
2: "/fuse",
|
|
96
|
+
3: "auto-rasterized",
|
|
97
|
+
4: "auto-discovery",
|
|
98
|
+
5: "download",
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
for tier in TIERS:
|
|
102
|
+
# These methods scan the filesystem, hence the caching
|
|
103
|
+
try:
|
|
104
|
+
items = int(tier.item_count())
|
|
105
|
+
except Exception:
|
|
106
|
+
logger.exception(f"Error getting item count for tier {tier.number}")
|
|
107
|
+
items = 0
|
|
108
|
+
|
|
109
|
+
try:
|
|
110
|
+
sz = int(tier.size_bytes())
|
|
111
|
+
except Exception:
|
|
112
|
+
logger.exception(f"Error getting size bytes for tier {tier.number}")
|
|
113
|
+
sz = 0
|
|
114
|
+
|
|
115
|
+
total_bytes += sz
|
|
116
|
+
|
|
117
|
+
mb_val = 0.0
|
|
118
|
+
try:
|
|
119
|
+
# Check for insane values before division
|
|
120
|
+
if sz > 1e15: # 1 PB
|
|
121
|
+
logger.warning(f"Tier {tier.number} size is massive: {sz}")
|
|
122
|
+
mb_val = 0.0 # Cap visual display to avoid float overflow in extreme cases
|
|
123
|
+
else:
|
|
124
|
+
raw_mb = sz / (1024 * 1024)
|
|
125
|
+
if not math.isfinite(raw_mb):
|
|
126
|
+
logger.warning(f"Tier {tier.number} raw_mb is not finite: {raw_mb}")
|
|
127
|
+
mb_val = 0.0
|
|
128
|
+
else:
|
|
129
|
+
mb_val = round(raw_mb, 2)
|
|
130
|
+
except Exception as e:
|
|
131
|
+
logger.exception(f"Error calculating MB for tier {tier.number}: {e}")
|
|
132
|
+
mb_val = 0.0
|
|
133
|
+
|
|
134
|
+
if sz > 1e16: # Trap insane values
|
|
135
|
+
logger.warning(f"Tier {tier.number} reports insane size: {sz}")
|
|
136
|
+
|
|
137
|
+
tier_summaries.append(
|
|
138
|
+
CacheTierSummary(
|
|
139
|
+
number=tier.number,
|
|
140
|
+
name=tier.name,
|
|
141
|
+
items=items,
|
|
142
|
+
bytes=sz,
|
|
143
|
+
mb=mb_val,
|
|
144
|
+
warning=tier.warning,
|
|
145
|
+
origin=tier_origins.get(tier.number),
|
|
146
|
+
)
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
total_mb_val = 0.0
|
|
150
|
+
try:
|
|
151
|
+
if total_bytes > 1e15:
|
|
152
|
+
logger.warning(f"Total size is massive: {total_bytes}")
|
|
153
|
+
total_mb_val = 0.0
|
|
154
|
+
else:
|
|
155
|
+
raw_total_mb = total_bytes / (1024 * 1024)
|
|
156
|
+
if not math.isfinite(raw_total_mb):
|
|
157
|
+
logger.warning(f"Total raw_mb is not finite: {raw_total_mb}")
|
|
158
|
+
total_mb_val = 0.0
|
|
159
|
+
else:
|
|
160
|
+
total_mb_val = round(raw_total_mb, 2)
|
|
161
|
+
except Exception as e:
|
|
162
|
+
logger.exception(f"Error calculating total MB: {e}")
|
|
163
|
+
total_mb_val = 0.0
|
|
164
|
+
|
|
165
|
+
summary = CacheSummary(
|
|
166
|
+
cache_root=str(CACHE_ROOT),
|
|
167
|
+
total_bytes=total_bytes,
|
|
168
|
+
total_mb=total_mb_val,
|
|
169
|
+
tiers=tier_summaries,
|
|
170
|
+
last_updated=now,
|
|
171
|
+
)
|
|
172
|
+
|
|
173
|
+
# Paranoia check: Validate JSON compliance before returning
|
|
174
|
+
try:
|
|
175
|
+
# allow_nan=False is CRITICAL to catch the error that FastAPI/Starlette throws
|
|
176
|
+
json.dumps(summary.dict(), allow_nan=False)
|
|
177
|
+
except ValueError as e:
|
|
178
|
+
logger.error(f"JSON Serialization Check Failed: {e}")
|
|
179
|
+
logger.error(f"Diagnostics: Total MB={summary.total_mb}, LastUpdated={summary.last_updated}")
|
|
180
|
+
|
|
181
|
+
# Check Tiers
|
|
182
|
+
for t in summary.tiers:
|
|
183
|
+
if not math.isfinite(t.mb):
|
|
184
|
+
logger.error(f"Tier {t.number} has BAD MB: {t.mb}")
|
|
185
|
+
t.mb = 0.0
|
|
186
|
+
|
|
187
|
+
# Check Total
|
|
188
|
+
if not math.isfinite(summary.total_mb):
|
|
189
|
+
logger.error(f"Total MB is BAD: {summary.total_mb}")
|
|
190
|
+
summary.total_mb = 0.0
|
|
191
|
+
|
|
192
|
+
# Check Timestamp
|
|
193
|
+
if not math.isfinite(summary.last_updated):
|
|
194
|
+
logger.error(f"Last Updated is BAD: {summary.last_updated}")
|
|
195
|
+
summary.last_updated = 0.0
|
|
196
|
+
|
|
197
|
+
# Run check again, if it fails, we are doomed but at least we tried
|
|
198
|
+
try:
|
|
199
|
+
json.dumps(summary.dict(), allow_nan=False)
|
|
200
|
+
except ValueError:
|
|
201
|
+
logger.critical("Failed to sanitize CacheSummary! Returning zeroed fallback.")
|
|
202
|
+
# Fallback to zeroed summary
|
|
203
|
+
summary.total_mb = 0.0
|
|
204
|
+
for t in summary.tiers:
|
|
205
|
+
t.mb = 0.0
|
|
206
|
+
|
|
207
|
+
_SUMMARY_CACHE = (now, summary)
|
|
208
|
+
return summary
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def get_cache_detail(cache_bust: bool = True) -> CacheDetail:
|
|
212
|
+
"""Return full detailed inventory of the cache."""
|
|
213
|
+
# We reuse the logic from cache_manager._gather_status_data
|
|
214
|
+
# but map it to our Pydantic models.
|
|
215
|
+
# Note: cache_manager._gather_status_data is not async, so this blocks.
|
|
216
|
+
# In a real app we might want to run this in a thread pool.
|
|
217
|
+
|
|
218
|
+
# Force re-scan
|
|
219
|
+
d = cm._gather_status_data()
|
|
220
|
+
|
|
221
|
+
# Map Tier 1
|
|
222
|
+
t1_subdirs = [TileSubdir(label=label, files=files, bytes=sz) for label, files, sz in d.tile_subdirs]
|
|
223
|
+
t1 = Tier1Detail(
|
|
224
|
+
tile_subdirs=t1_subdirs,
|
|
225
|
+
meta_count=d.tile_meta_count,
|
|
226
|
+
npz_count=d.tile_npz_count,
|
|
227
|
+
)
|
|
228
|
+
|
|
229
|
+
# Map Tier 2
|
|
230
|
+
from topobathykit.api.models import PolicyHashGroup
|
|
231
|
+
|
|
232
|
+
policies_mapped = []
|
|
233
|
+
|
|
234
|
+
for phash, pdict in getattr(d, "fused_policies", {}).items():
|
|
235
|
+
by_zoom = {}
|
|
236
|
+
for z, info in pdict.get("by_zoom", {}).items():
|
|
237
|
+
by_zoom[float(z)] = ZoomDetail(
|
|
238
|
+
count=info["count"],
|
|
239
|
+
bytes=info["bytes"],
|
|
240
|
+
lon_min=_safe_float(info["lon_min"]),
|
|
241
|
+
lon_max=_safe_float(info["lon_max"]),
|
|
242
|
+
lat_min=_safe_float(info["lat_min"]),
|
|
243
|
+
lat_max=_safe_float(info["lat_max"]),
|
|
244
|
+
origin_zoom=info.get("origin_zoom", 0),
|
|
245
|
+
origin_meters=info.get("origin_meters", 0),
|
|
246
|
+
origin_unknown=info.get("origin_unknown", 0),
|
|
247
|
+
resolution_m=_safe_float(info["resolution_m"])
|
|
248
|
+
if info.get("resolution_m") is not None
|
|
249
|
+
else None,
|
|
250
|
+
)
|
|
251
|
+
|
|
252
|
+
# Extract policy name from YAML snippet if available
|
|
253
|
+
policy_name = None
|
|
254
|
+
snippet = pdict.get("yaml_snippet")
|
|
255
|
+
if snippet:
|
|
256
|
+
import re
|
|
257
|
+
|
|
258
|
+
m = re.search(r"^name:\s*(.+)$", snippet, re.MULTILINE)
|
|
259
|
+
if m:
|
|
260
|
+
policy_name = m.group(1).strip()
|
|
261
|
+
|
|
262
|
+
policies_mapped.append(
|
|
263
|
+
PolicyHashGroup(
|
|
264
|
+
policy_hash=phash,
|
|
265
|
+
policy_name=policy_name,
|
|
266
|
+
yaml_snippet=snippet,
|
|
267
|
+
count=pdict.get("count", 0),
|
|
268
|
+
bytes=pdict.get("bytes", 0),
|
|
269
|
+
by_zoom=by_zoom,
|
|
270
|
+
)
|
|
271
|
+
)
|
|
272
|
+
|
|
273
|
+
t2 = Tier2Detail(
|
|
274
|
+
count=d.fused_count,
|
|
275
|
+
bytes=d.fused_total_bytes,
|
|
276
|
+
newest=_safe_float(d.fused_newest),
|
|
277
|
+
oldest=_safe_float(d.fused_oldest),
|
|
278
|
+
policies=policies_mapped,
|
|
279
|
+
)
|
|
280
|
+
|
|
281
|
+
# Map Tier 3
|
|
282
|
+
providers = []
|
|
283
|
+
for p, count, sz, newest, oldest in d.provider_zarr:
|
|
284
|
+
providers.append(
|
|
285
|
+
ProviderDetail(
|
|
286
|
+
name=p,
|
|
287
|
+
count=count,
|
|
288
|
+
bytes=sz,
|
|
289
|
+
newest=_safe_float(newest),
|
|
290
|
+
oldest=_safe_float(oldest),
|
|
291
|
+
)
|
|
292
|
+
)
|
|
293
|
+
t3 = Tier3Detail(providers=providers)
|
|
294
|
+
|
|
295
|
+
# Map Tier 4
|
|
296
|
+
discovery = []
|
|
297
|
+
for label, ok, sz, entries, mtime in d.discovery:
|
|
298
|
+
discovery.append(
|
|
299
|
+
DiscoveryDetail(
|
|
300
|
+
label=label,
|
|
301
|
+
ok=ok,
|
|
302
|
+
bytes=sz,
|
|
303
|
+
entries=entries,
|
|
304
|
+
mtime=_safe_float(mtime),
|
|
305
|
+
)
|
|
306
|
+
)
|
|
307
|
+
|
|
308
|
+
t4 = Tier4Detail(
|
|
309
|
+
discovery=discovery,
|
|
310
|
+
bluetopo_scheme={
|
|
311
|
+
"exists": d.bluetopo_scheme[0],
|
|
312
|
+
"bytes": d.bluetopo_scheme[1],
|
|
313
|
+
"mtime": _safe_float(d.bluetopo_scheme[2]),
|
|
314
|
+
},
|
|
315
|
+
bluetopo_sidecars={
|
|
316
|
+
"ok_count": d.bluetopo_sidecars[0],
|
|
317
|
+
"failed_count": d.bluetopo_sidecars[1],
|
|
318
|
+
"bytes": d.bluetopo_sidecars[2],
|
|
319
|
+
"mtime": _safe_float(d.bluetopo_sidecars[3]),
|
|
320
|
+
},
|
|
321
|
+
topobathy_zips={
|
|
322
|
+
"count": d.topobathy_zips[0],
|
|
323
|
+
"bytes": d.topobathy_zips[1],
|
|
324
|
+
"mtime": _safe_float(d.topobathy_zips[2]),
|
|
325
|
+
},
|
|
326
|
+
)
|
|
327
|
+
|
|
328
|
+
# Map Tier 5
|
|
329
|
+
raw_files = []
|
|
330
|
+
for p, count, sz, newest, oldest in d.raw_files:
|
|
331
|
+
raw_files.append(
|
|
332
|
+
RawFileDetail(
|
|
333
|
+
provider=p,
|
|
334
|
+
count=count,
|
|
335
|
+
bytes=sz,
|
|
336
|
+
newest=_safe_float(newest),
|
|
337
|
+
oldest=_safe_float(oldest),
|
|
338
|
+
)
|
|
339
|
+
)
|
|
340
|
+
t5 = Tier5Detail(raw_files=raw_files)
|
|
341
|
+
|
|
342
|
+
detail = CacheDetail(
|
|
343
|
+
cache_root=str(CACHE_ROOT),
|
|
344
|
+
total_bytes=d.total_bytes,
|
|
345
|
+
tier_1=t1,
|
|
346
|
+
tier_2=t2,
|
|
347
|
+
tier_3=t3,
|
|
348
|
+
tier_4=t4,
|
|
349
|
+
tier_5=t5,
|
|
350
|
+
)
|
|
351
|
+
|
|
352
|
+
# Paranoia check
|
|
353
|
+
try:
|
|
354
|
+
json.dumps(detail.dict(), allow_nan=False)
|
|
355
|
+
except ValueError as e:
|
|
356
|
+
logger.error(f"JSON Check Failed in get_cache_detail: {e}")
|
|
357
|
+
# If checks failed, we might crash, but at least we know WHERE.
|
|
358
|
+
# Since we applied _safe_float above, this should pass.
|
|
359
|
+
|
|
360
|
+
return detail
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def purge_tiers(
|
|
364
|
+
tiers: list[int],
|
|
365
|
+
dry_run: bool = True,
|
|
366
|
+
yes: bool = False,
|
|
367
|
+
tier_2_hashes: list[str] | None = None,
|
|
368
|
+
) -> PurgeResult:
|
|
369
|
+
"""Purge specified cache tiers."""
|
|
370
|
+
|
|
371
|
+
# Safety check for Tier 5
|
|
372
|
+
if 5 in tiers and not yes:
|
|
373
|
+
# This should have been caught by the API router/controller,
|
|
374
|
+
# but double check here.
|
|
375
|
+
pass
|
|
376
|
+
|
|
377
|
+
affected_paths: list[str] = []
|
|
378
|
+
summary: dict[str, dict[str, int]] = {}
|
|
379
|
+
|
|
380
|
+
# Sort tiers to process
|
|
381
|
+
tiers_to_process = [t for t in TIERS if t.number in tiers]
|
|
382
|
+
|
|
383
|
+
for tier in tiers_to_process:
|
|
384
|
+
paths = tier.purge_paths()
|
|
385
|
+
|
|
386
|
+
# Filter Tier 2 paths if tier_2_hashes is provided
|
|
387
|
+
if tier.number == 2 and tier_2_hashes is not None:
|
|
388
|
+
paths = [p for p in paths if p.name in tier_2_hashes]
|
|
389
|
+
|
|
390
|
+
deleted_count = 0
|
|
391
|
+
deleted_bytes = 0
|
|
392
|
+
|
|
393
|
+
tier_paths_str = []
|
|
394
|
+
|
|
395
|
+
for p in paths:
|
|
396
|
+
# Gather stats before deletion attempt
|
|
397
|
+
try:
|
|
398
|
+
if p.exists():
|
|
399
|
+
sz = cm._dir_size_bytes(p) if p.is_dir() else p.stat().st_size
|
|
400
|
+
deleted_bytes += sz
|
|
401
|
+
except OSError:
|
|
402
|
+
sz = 0
|
|
403
|
+
|
|
404
|
+
p_str = str(p)
|
|
405
|
+
tier_paths_str.append(p_str)
|
|
406
|
+
|
|
407
|
+
if not dry_run:
|
|
408
|
+
try:
|
|
409
|
+
if p.is_dir():
|
|
410
|
+
shutil.rmtree(p)
|
|
411
|
+
else:
|
|
412
|
+
p.unlink()
|
|
413
|
+
deleted_count += 1
|
|
414
|
+
except Exception as e:
|
|
415
|
+
logger.error(f"Failed to delete {p}: {e}")
|
|
416
|
+
else:
|
|
417
|
+
deleted_count += 1
|
|
418
|
+
|
|
419
|
+
summary[f"tier_{tier.number}"] = {"count": deleted_count, "bytes": deleted_bytes}
|
|
420
|
+
affected_paths.extend(tier_paths_str)
|
|
421
|
+
|
|
422
|
+
msg = "Dry-run complete." if dry_run else "Purge complete."
|
|
423
|
+
mode = "dry-run" if dry_run else "committed"
|
|
424
|
+
|
|
425
|
+
return PurgeResult(status="success", mode=mode, message=msg, summary=summary, paths=affected_paths)
|
|
426
|
+
|
|
427
|
+
|
|
428
|
+
def check_integrity(clean: bool = False, lock_timeout: int = 3600) -> CheckResult:
|
|
429
|
+
"""Scan provider integrity and orphaned files."""
|
|
430
|
+
checks: dict[str, Any] = {}
|
|
431
|
+
|
|
432
|
+
# 1. Scan providers
|
|
433
|
+
for p in cm.PROVIDERS:
|
|
434
|
+
# _scan_provider_integrity is available in cm
|
|
435
|
+
# It returns dict with keys: stale_locks, corrupt_src, corrupt_zarr (int counts)
|
|
436
|
+
try:
|
|
437
|
+
counts = cm._scan_provider_integrity(p, clean=clean, lock_timeout=lock_timeout)
|
|
438
|
+
checks[p] = counts
|
|
439
|
+
except Exception as e:
|
|
440
|
+
logger.error(f"Error checking provider {p}: {e}")
|
|
441
|
+
checks[p] = {"error": str(e)}
|
|
442
|
+
|
|
443
|
+
# 2. Discovery checks (adapted from cmd_check)
|
|
444
|
+
disco_status = []
|
|
445
|
+
for label, path in cm._DISCOVERY_FILES:
|
|
446
|
+
status = "ok"
|
|
447
|
+
if not path.exists():
|
|
448
|
+
status = "missing"
|
|
449
|
+
else:
|
|
450
|
+
try:
|
|
451
|
+
with open(path) as f:
|
|
452
|
+
json.load(f)
|
|
453
|
+
except json.JSONDecodeError:
|
|
454
|
+
status = "corrupt"
|
|
455
|
+
if clean:
|
|
456
|
+
try:
|
|
457
|
+
path.unlink()
|
|
458
|
+
status = "deleted"
|
|
459
|
+
except OSError:
|
|
460
|
+
status = "delete_failed"
|
|
461
|
+
disco_status.append({"label": label, "status": status})
|
|
462
|
+
|
|
463
|
+
checks["discovery"] = disco_status
|
|
464
|
+
|
|
465
|
+
# 3. Scan orphans (adapted from _scan_global_orphans)
|
|
466
|
+
# _scan_global_orphans prints to console and returns (stale_count, removed_count)
|
|
467
|
+
# We want more detail. Implementing custom logic similar to _scan_global_orphans.
|
|
468
|
+
|
|
469
|
+
orphans = _scan_orphans_internal(clean=clean, lock_timeout=lock_timeout)
|
|
470
|
+
|
|
471
|
+
return CheckResult(status="complete", checks=checks, orphans=orphans)
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
def manage_orphans(clean: bool = False) -> OrphansResult:
|
|
475
|
+
"""List or clean orphaned locks/tmp files."""
|
|
476
|
+
orphans = _scan_orphans_internal(clean=clean, lock_timeout=3600) # Default timeout for manual action
|
|
477
|
+
|
|
478
|
+
mode = "committed" if clean else "list-only"
|
|
479
|
+
|
|
480
|
+
return OrphansResult(status="success", mode=mode, orphans=orphans)
|
|
481
|
+
|
|
482
|
+
|
|
483
|
+
def _scan_orphans_internal(clean: bool, lock_timeout: int) -> dict[str, Any]:
|
|
484
|
+
now = time.time()
|
|
485
|
+
patterns = ["*.lock", ".tmp*", "__temp__*"]
|
|
486
|
+
candidates: list[Path] = []
|
|
487
|
+
|
|
488
|
+
for pat in patterns:
|
|
489
|
+
candidates.extend(CACHE_ROOT.rglob(pat))
|
|
490
|
+
|
|
491
|
+
unique_candidates = sorted(list(set(candidates)), key=lambda p: str(p))
|
|
492
|
+
|
|
493
|
+
stale_locks = []
|
|
494
|
+
tmp_files = []
|
|
495
|
+
total_bytes = 0
|
|
496
|
+
|
|
497
|
+
for p in unique_candidates:
|
|
498
|
+
if not p.exists():
|
|
499
|
+
continue
|
|
500
|
+
try:
|
|
501
|
+
stat = p.stat()
|
|
502
|
+
age = now - stat.st_mtime
|
|
503
|
+
|
|
504
|
+
# For .lock files, check timeout. For tmp files, maybe just delete if old?
|
|
505
|
+
# Matching logic from cache_manager: usage of lock_timeout implies it applies to all.
|
|
506
|
+
if age > lock_timeout:
|
|
507
|
+
sz = cm._dir_size_bytes(p) if p.is_dir() else stat.st_size
|
|
508
|
+
info = {"path": str(p), "age_sec": age, "bytes": sz}
|
|
509
|
+
|
|
510
|
+
if p.name.endswith(".lock"):
|
|
511
|
+
stale_locks.append(info)
|
|
512
|
+
else:
|
|
513
|
+
tmp_files.append(info)
|
|
514
|
+
|
|
515
|
+
total_bytes += sz
|
|
516
|
+
|
|
517
|
+
if clean:
|
|
518
|
+
if p.is_dir():
|
|
519
|
+
shutil.rmtree(p)
|
|
520
|
+
else:
|
|
521
|
+
p.unlink()
|
|
522
|
+
except Exception as e:
|
|
523
|
+
logger.warning(f"Error processing orphan {p}: {e}")
|
|
524
|
+
|
|
525
|
+
return {
|
|
526
|
+
"locks": stale_locks,
|
|
527
|
+
"tmp_files": tmp_files,
|
|
528
|
+
"total_bytes": total_bytes,
|
|
529
|
+
"count": len(stale_locks) + len(tmp_files),
|
|
530
|
+
}
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
from typing import Any
|
|
2
|
+
|
|
3
|
+
from pydantic import BaseModel
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class CacheTierInfo(BaseModel):
|
|
7
|
+
number: int
|
|
8
|
+
name: str
|
|
9
|
+
short_desc: str
|
|
10
|
+
long_desc: str
|
|
11
|
+
purge_reason: str
|
|
12
|
+
warning: bool
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class CacheTierSummary(BaseModel):
|
|
16
|
+
number: int
|
|
17
|
+
name: str
|
|
18
|
+
items: int
|
|
19
|
+
bytes: int
|
|
20
|
+
mb: float
|
|
21
|
+
warning: bool
|
|
22
|
+
origin: str | None = None
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class CacheSummary(BaseModel):
|
|
26
|
+
cache_root: str
|
|
27
|
+
total_bytes: int
|
|
28
|
+
total_mb: float
|
|
29
|
+
tiers: list[CacheTierSummary]
|
|
30
|
+
last_updated: float
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class TileSubdir(BaseModel):
|
|
34
|
+
label: str
|
|
35
|
+
files: int
|
|
36
|
+
bytes: int
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class Tier1Detail(BaseModel):
|
|
40
|
+
tile_subdirs: list[TileSubdir]
|
|
41
|
+
meta_count: int
|
|
42
|
+
npz_count: int
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class ZoomDetail(BaseModel):
|
|
46
|
+
count: int
|
|
47
|
+
bytes: int
|
|
48
|
+
lon_min: float
|
|
49
|
+
lon_max: float
|
|
50
|
+
lat_min: float
|
|
51
|
+
lat_max: float
|
|
52
|
+
origin_zoom: int = 0
|
|
53
|
+
origin_meters: int = 0
|
|
54
|
+
origin_unknown: int = 0
|
|
55
|
+
resolution_m: float | None = None
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class PolicyHashGroup(BaseModel):
|
|
59
|
+
policy_hash: str
|
|
60
|
+
policy_name: str | None = None
|
|
61
|
+
yaml_snippet: str | None
|
|
62
|
+
count: int
|
|
63
|
+
bytes: int
|
|
64
|
+
by_zoom: dict[float, ZoomDetail]
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class Tier2Detail(BaseModel):
|
|
68
|
+
count: int
|
|
69
|
+
bytes: int
|
|
70
|
+
newest: float
|
|
71
|
+
oldest: float
|
|
72
|
+
policies: list[PolicyHashGroup]
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class ProviderDetail(BaseModel):
|
|
76
|
+
name: str
|
|
77
|
+
count: int
|
|
78
|
+
bytes: int
|
|
79
|
+
newest: float
|
|
80
|
+
oldest: float
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class Tier3Detail(BaseModel):
|
|
84
|
+
providers: list[ProviderDetail]
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class DiscoveryDetail(BaseModel):
|
|
88
|
+
label: str
|
|
89
|
+
ok: bool
|
|
90
|
+
bytes: int
|
|
91
|
+
entries: int
|
|
92
|
+
mtime: float
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class Tier4Detail(BaseModel):
|
|
96
|
+
discovery: list[DiscoveryDetail]
|
|
97
|
+
bluetopo_scheme: dict[str, Any]
|
|
98
|
+
bluetopo_sidecars: dict[str, Any]
|
|
99
|
+
topobathy_zips: dict[str, Any]
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class RawFileDetail(BaseModel):
|
|
103
|
+
provider: str
|
|
104
|
+
count: int
|
|
105
|
+
bytes: int
|
|
106
|
+
newest: float
|
|
107
|
+
oldest: float
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class Tier5Detail(BaseModel):
|
|
111
|
+
raw_files: list[RawFileDetail]
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
class CacheDetail(BaseModel):
|
|
115
|
+
cache_root: str
|
|
116
|
+
total_bytes: int
|
|
117
|
+
tier_1: Tier1Detail
|
|
118
|
+
tier_2: Tier2Detail
|
|
119
|
+
tier_3: Tier3Detail
|
|
120
|
+
tier_4: Tier4Detail
|
|
121
|
+
tier_5: Tier5Detail
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
class PurgeRequest(BaseModel):
|
|
125
|
+
tiers: list[int]
|
|
126
|
+
tier_2_hashes: list[str] | None = None
|
|
127
|
+
dry_run: bool = True
|
|
128
|
+
yes: bool = False
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
class PurgeResult(BaseModel):
|
|
132
|
+
status: str
|
|
133
|
+
mode: str
|
|
134
|
+
message: str | None = None
|
|
135
|
+
summary: dict[str, dict[str, int]]
|
|
136
|
+
paths: list[str]
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
class CheckRequest(BaseModel):
|
|
140
|
+
clean: bool = False
|
|
141
|
+
lock_timeout: int = 3600
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
class CheckResult(BaseModel):
|
|
145
|
+
status: str
|
|
146
|
+
checks: dict[str, Any]
|
|
147
|
+
orphans: dict[str, Any]
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
class OrphansRequest(BaseModel):
|
|
151
|
+
clean: bool = False
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
class OrphansResult(BaseModel):
|
|
155
|
+
status: str
|
|
156
|
+
mode: str
|
|
157
|
+
orphans: dict[str, Any]
|