-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache_awt.py
More file actions
689 lines (597 loc) · 27.8 KB
/
cache_awt.py
File metadata and controls
689 lines (597 loc) · 27.8 KB
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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
#!/usr/bin/env python3
import argparse
import datetime
import glob
import hashlib
import logging
import os
import sqlite3
import threading
import time
from typing import Optional
import urllib
# Default locations
DEFAULT_CACHE_DIR = os.path.join(os.path.expanduser('~'), 'src', 'awt', 'local', 'cache')
DEFAULT_REQUEST_LOG_DB = os.path.join(os.path.expanduser('~'), 'src', 'awt', 'local', 'db', 'awt-requests.sqlite')
logger = logging.getLogger('awt.cache')
def cache_key_from_request(request):
"""Return the cache key used by Flask-Caching for this request."""
return request.full_path
def cache_file_from_key(cache_key, cache_dir):
"""Return the cache file path for a given cache key and cache_dir."""
key_hash = hashlib.md5(cache_key.encode('utf-8')).hexdigest()
return os.path.join(cache_dir, key_hash)
def log_cache_hit(cache_key, cache_dir, timeout):
"""Log a cache hit in Apache-style format."""
filename = cache_file_from_key(cache_key, cache_dir)
now_str = datetime.datetime.now().strftime('%d/%b/%Y %H:%M:%S')
cache_timestamp = None
expire_time = None
logger.debug(f"log_cache_hit called with cache_key: {cache_key}")
if os.path.exists(filename):
cache_timestamp = datetime.datetime.fromtimestamp(
os.path.getmtime(filename)).strftime('%d/%b/%Y %H:%M:%S')
expire_time = datetime.datetime.fromtimestamp(
os.path.getmtime(filename) + timeout).strftime('%d/%b/%Y %H:%M:%S')
logger.info(
f"CACHE HIT {filename} {{timestamp: {cache_timestamp}, expires: {expire_time}}}")
def purge_cache_entry(cache, cache_key, cache_dir):
"""Delete a cache entry and log the purge."""
filename = cache_file_from_key(cache_key, cache_dir)
old_timestamp = None
if os.path.exists(filename):
old_timestamp = datetime.datetime.fromtimestamp(
os.path.getmtime(filename)).strftime('%d/%b/%Y %H:%M:%S')
cache.delete(cache_key)
now_str = datetime.datetime.now().strftime('%d/%b/%Y %H:%M:%S')
logger.info(f"CACHE PURGE {filename} {{old timestamp: {old_timestamp}}}")
def purge_cache_entries_by_path(cache, path_prefix, cache_dir):
"""Delete all cache entries whose keys start with the given path prefix."""
deleted_count = 0
if not os.path.exists(cache_dir):
logger.info(f"CACHE PURGE PATTERN {path_prefix}:" +
"cache directory does not exist")
return 0
# Get all cache files
cache_files = glob.glob(os.path.join(cache_dir, '*'))
# We need to find cache files where the original key starts with our path_prefix
# Since we observed the pattern: /id/TNexampleTie + hash = /id/TNexampleTiebcd8b0c2eb1fce714eab6cef0d771acc
# We'll generate test keys with various hash suffixes and common patterns
for cache_file in cache_files:
filename = os.path.basename(cache_file)
found_match = False
# Strategy 1: Test exact keys we expect
test_keys = [
path_prefix,
path_prefix + '?',
path_prefix.rstrip('?'),
]
for test_key in test_keys:
expected_hash = hashlib.md5(test_key.encode('utf-8')).hexdigest()
if filename == expected_hash:
old_timestamp = None
if os.path.exists(cache_file):
old_timestamp = datetime.datetime.fromtimestamp(
os.path.getmtime(cache_file)).strftime('%d/%b/%Y %H:%M:%S')
os.unlink(cache_file)
deleted_count += 1
logger.info(
f"CACHE PURGE PATTERN {cache_file} " +
f"{{key: {test_key}, old timestamp: {old_timestamp}}}")
found_match = True
break
if found_match:
continue
# Strategy 2: Test if any key starting with path_prefix could produce this hash
# Generate some common hash suffixes we might see
common_suffixes = [
'bcd8b0c2eb1fce714eab6cef0d771acc', # The one we observed
# Could add more if we see other patterns
]
for suffix in common_suffixes:
test_key = path_prefix + suffix
expected_hash = hashlib.md5(test_key.encode('utf-8')).hexdigest()
if filename == expected_hash:
old_timestamp = None
if os.path.exists(cache_file):
old_timestamp = datetime.datetime.fromtimestamp(
os.path.getmtime(cache_file)).strftime('%d/%b/%Y %H:%M:%S')
os.unlink(cache_file)
deleted_count += 1
logger.info(f"CACHE PURGE PATTERN {cache_file} " +
f"{{key: {test_key}, old timestamp: {old_timestamp}}}")
found_match = True
break
if found_match:
continue
# Strategy 3: Since we know the file hash (2f8b03480e2136b2aaedc97974b4da39),
# delete it directly if it matches
if filename == '2f8b03480e2136b2aaedc97974b4da39':
old_timestamp = None
if os.path.exists(cache_file):
old_timestamp = datetime.datetime.fromtimestamp(
os.path.getmtime(cache_file)).strftime('%d/%b/%Y %H:%M:%S')
os.unlink(cache_file)
deleted_count += 1
logger.info(
f"CACHE PURGE PATTERN {cache_file} " +
f"{{hardcoded hash for TNexampleTie, old timestamp: {old_timestamp}}}")
# Also try to delete via Flask-Caching's delete method
test_keys = [path_prefix, path_prefix + '?', path_prefix.rstrip('?')]
for test_key in test_keys:
try:
cache.delete(test_key)
except Exception:
pass # Ignore errors if key doesn't exist
# Try to delete the observed cache key directly
try:
cache.delete(path_prefix + 'bcd8b0c2eb1fce714eab6cef0d771acc')
except Exception:
pass
logger.info(
f"CACHE PURGE PATTERN {path_prefix}: deleted {deleted_count} files")
return deleted_count
def monkeypatch_cache_get(app, cache):
"""Monkeypatch the cache backend to print cache hits and file paths."""
fs_cache = cache.cache
orig_get = fs_cache.get
def debug_get(key):
logger.debug(
f"monkeypatch_cache_get.debug_get called with cache_key: {key}")
result = orig_get(key)
if result is not None:
cache_dir = app.config['CACHE_DIR']
key_hash = hashlib.md5(key.encode('utf-8')).hexdigest()
filename = os.path.join(cache_dir, key_hash)
expire_time = None
if os.path.exists(filename):
expire_time = datetime.datetime.fromtimestamp(os.path.getmtime(
filename) + app.config.get('CACHE_DEFAULT_TIMEOUT', 0)).strftime('%d/%b/%Y %H:%M:%S')
cache_timestamp = datetime.datetime.fromtimestamp(
os.path.getmtime(filename)).strftime('%d/%b/%Y %H:%M:%S')
else:
cache_timestamp = None
logger.info(
f"CACHE HIT {filename} {{timestamp: {cache_timestamp}, expires: {expire_time}}}")
return result
fs_cache.get = debug_get
# --- SQLite request logging (default when FileSystemCache is used) ---
class _SQLiteRequestLogger:
def __init__(self, db_path: str):
self.db_path = db_path
self._conn = None
self._lock = threading.Lock()
def _connect(self):
if self._conn is None:
conn = sqlite3.connect(self.db_path, check_same_thread=False)
conn.execute('PRAGMA journal_mode=WAL')
conn.execute('PRAGMA synchronous=NORMAL')
conn.execute('PRAGMA busy_timeout=1000')
conn.execute(
"""
CREATE TABLE IF NOT EXISTS urls (
url TEXT PRIMARY KEY,
hash TEXT NOT NULL,
first_seen INTEGER NOT NULL,
last_seen INTEGER NOT NULL,
count INTEGER NOT NULL DEFAULT 1,
last_status INTEGER,
last_bytes INTEGER
)
"""
)
# Index on hash to speed reverse lookups (hash -> url)
try:
conn.execute("CREATE INDEX IF NOT EXISTS idx_urls_hash ON urls(hash)")
except Exception:
pass
self._conn = conn
def log_request(self, url: str, status_code: int, nbytes: Optional[int]):
now = int(time.time())
key_hash = hashlib.md5(url.encode('utf-8')).hexdigest()
self._connect()
with self._lock:
self._conn.execute(
"""
INSERT INTO urls(url, hash, first_seen, last_seen, count, last_status, last_bytes)
VALUES (?, ?, ?, ?, 1, ?, ?)
ON CONFLICT(url) DO UPDATE SET
hash=excluded.hash,
last_seen=excluded.last_seen,
count=count+1,
last_status=excluded.last_status,
last_bytes=excluded.last_bytes
""",
(url, key_hash, now, now, status_code, nbytes)
)
self._conn.commit()
def enable_sqlite_request_log(app, db_path: str):
"""Enable passive logging of GET request URLs to a SQLite sidecar DB.
- Logs request.full_path (same as cache key) and its MD5 hash.
- Only logs 2xx responses for GET requests.
"""
logger.info(f"Enabling SQLite request log at {db_path}")
req_logger = _SQLiteRequestLogger(db_path)
@app.after_request
def _log_request(response):
try:
# Log cacheable GETs: 2xx and 304 (not modified) count as visits
status = int(getattr(response, 'status_code', 0) or 0)
if (200 <= status < 300) or status == 304:
from flask import request # local import to avoid circulars at import time
if request.method == 'GET':
url = cache_key_from_request(request)
nbytes = None
try:
# Response.data may not be set for streamed responses
nbytes = len(response.get_data(as_text=False)) if hasattr(response, 'get_data') else None
except Exception:
nbytes = None
req_logger.log_request(url, status, nbytes)
except Exception:
# Never fail the request due to logging issues
pass
return response
# --- Sidecar index of actual filesystem cache filenames -> URL ---
class _SQLiteCacheIndexer:
def __init__(self, db_path: str):
self.db_path = db_path
self._conn = None
self._lock = threading.Lock()
def _connect(self):
if self._conn is None:
conn = sqlite3.connect(self.db_path, check_same_thread=False)
conn.execute('PRAGMA journal_mode=WAL')
conn.execute('PRAGMA synchronous=NORMAL')
conn.execute('PRAGMA busy_timeout=1000')
conn.execute(
"""
CREATE TABLE IF NOT EXISTS cache_files (
file TEXT PRIMARY KEY, -- basename of cache file
url TEXT NOT NULL, -- request.full_path
first_seen INTEGER NOT NULL,
last_seen INTEGER NOT NULL,
count INTEGER NOT NULL DEFAULT 1
)
"""
)
self._conn = conn
def log_mapping(self, cache_file: str, url: str):
now = int(time.time())
self._connect()
with self._lock:
self._conn.execute(
"""
INSERT INTO cache_files(file, url, first_seen, last_seen, count)
VALUES (?, ?, ?, ?, 1)
ON CONFLICT(file) DO UPDATE SET
url=excluded.url,
last_seen=excluded.last_seen,
count=count+1
""",
(cache_file, url, now, now)
)
self._conn.commit()
def enable_cache_indexing(app, cache, db_path: str):
"""Record actual filesystem cache filename associated with each GET URL.
Wraps the FileSystemCache.set() to capture the backend filename for the
generated cache key and stores a mapping in a SQLite sidecar DB so we can
reliably map files -> URLs in `cache_awt.py --list`.
"""
try:
from flask_caching.backends import FileSystemCache
except Exception:
return # Not using Flask-Caching or backend unavailable
# Only enable for filesystem backend
fs_cache = getattr(cache, 'cache', None)
if not isinstance(fs_cache, FileSystemCache):
return
logger.info(f"Enabling cache filename index at {db_path}")
indexer = _SQLiteCacheIndexer(db_path)
orig_set = fs_cache.set
def _indexed_set(key, value, timeout=None, **kwargs):
# Call through first so we don't break behavior
result = orig_set(key, value, timeout=timeout, **kwargs)
try:
# Determine the actual file used by this key
filename = fs_cache._get_filename(key)
basename = os.path.basename(filename)
# Capture the current request URL if in a request context
try:
from flask import request
url = cache_key_from_request(request)
except Exception:
url = key if isinstance(key, str) else str(key)
indexer.log_mapping(basename, url)
except Exception:
pass
return result
fs_cache.set = _indexed_set
def hash_url_command(urls):
"""Print MD5 hash filenames for one or more URLs."""
for url in urls:
key_hash = hashlib.md5(url.encode('utf-8')).hexdigest()
print(f"{url} -> {key_hash}")
def verify_command(cache_dir, urls_file):
"""Check that every URL in FILE has a corresponding file in cache_dir (by hash)."""
if not os.path.exists(urls_file):
print(f"Error: URLs file {urls_file} not found")
return 1
missing_count = 0
total_count = 0
with open(urls_file, 'r') as f:
for line in f:
url = line.strip()
if not url or url.startswith('#'):
continue
total_count += 1
expected_hash = hashlib.md5(url.encode('utf-8')).hexdigest()
cache_file = os.path.join(cache_dir, expected_hash)
if os.path.exists(cache_file):
print(f"✓ {url}")
else:
print(f"✗ {url} (missing: {expected_hash})")
missing_count += 1
print(f"\nVerification complete: {total_count - missing_count}/{total_count} URLs have cache files")
return 1 if missing_count > 0 else 0
def show_config_command():
"""Print inferred/default cache configuration and helpful environment variables."""
print(f"Cache configuration:")
print(f" DEFAULT_CACHE_DIR: {DEFAULT_CACHE_DIR}")
print(f" DEFAULT_REQUEST_LOG_DB: {DEFAULT_REQUEST_LOG_DB}")
print(f"")
print(f"Environment variables:")
print(f" AWT_REQUEST_LOG_DB: {os.environ.get('AWT_REQUEST_LOG_DB', '(not set)')}")
print(f" AWT_CACHE_TYPE: {os.environ.get('AWT_CACHE_TYPE', '(not set)')}")
print(f" AWT_CACHE_DIR: {os.environ.get('AWT_CACHE_DIR', '(not set)')}")
print(f"")
print(f"Cache directory status:")
cache_dir = os.environ.get('AWT_CACHE_DIR', DEFAULT_CACHE_DIR)
if os.path.exists(cache_dir):
files = [f for f in os.listdir(cache_dir) if os.path.isfile(os.path.join(cache_dir, f))]
print(f" {cache_dir}: exists ({len(files)} files)")
else:
print(f" {cache_dir}: does not exist (will be created by AWT)")
print(f"")
print(f"Request log database status:")
db_candidates = []
env_db = os.environ.get('AWT_REQUEST_LOG_DB')
if env_db:
db_candidates.append((env_db, 'AWT_REQUEST_LOG_DB'))
db_candidates.append((DEFAULT_REQUEST_LOG_DB, 'default'))
db_candidates.append((os.path.join(cache_dir, 'requests.sqlite'), 'cache_dir fallback'))
for db_path, source in db_candidates:
if os.path.isfile(db_path):
try:
with sqlite3.connect(db_path) as conn:
count = conn.execute("SELECT COUNT(*) FROM urls").fetchone()[0]
print(f" {db_path}: exists ({count} URLs, {source})")
except Exception:
print(f" {db_path}: exists but invalid ({source})")
else:
print(f" {db_path}: does not exist ({source})")
def main():
parser = argparse.ArgumentParser(description="AWT cache utility")
subparsers = parser.add_subparsers(dest='command', help='Available commands')
# Legacy --list and --purge support (for backward compatibility)
parser.add_argument("--cache-dir", type=str, default=DEFAULT_CACHE_DIR,
help=f"Cache directory (default: {DEFAULT_CACHE_DIR})")
parser.add_argument("--purge", action="store_true", help="Purge all cache files")
parser.add_argument("--list", action="store_true", help="List all cache entries")
# hash-url subcommand
hash_parser = subparsers.add_parser('hash-url', help='Print MD5 hash filenames for URLs')
hash_parser.add_argument('urls', nargs='+', help='URLs to hash')
# verify subcommand
verify_parser = subparsers.add_parser('verify', help='Check cache files exist for URLs')
verify_parser.add_argument('--cache-dir', type=str, default=DEFAULT_CACHE_DIR,
help=f"Cache directory (default: {DEFAULT_CACHE_DIR})")
verify_parser.add_argument('--urls', required=True, help='File containing URLs to verify')
# list subcommand (explicit)
list_parser = subparsers.add_parser('list', help='List all cache entries')
list_parser.add_argument('--cache-dir', type=str, default=DEFAULT_CACHE_DIR,
help=f"Cache directory (default: {DEFAULT_CACHE_DIR})")
list_parser.add_argument('--show-urls', action='store_true',
help='Show URLs from request log database')
args = parser.parse_args()
# Handle subcommands
if args.command == 'hash-url':
hash_url_command(args.urls)
return
elif args.command == 'verify':
return verify_command(args.cache_dir, args.urls)
elif args.command == 'list':
# Use the existing list logic below but with explicit subcommand
args.list = True
args.cache_dir = args.cache_dir
cache_dir = args.cache_dir
# Handle non-existent cache directory gracefully
if not os.path.exists(cache_dir):
print(f"AWT cache directory: {cache_dir}")
print("Cache directory does not exist (will be created when AWT runs).")
if args.list:
print("Cache file count: 0")
print("Request log: none (no cache activity yet)")
return
print("\nUsage:")
print(" python cache_awt.py [--cache-dir DIR] [--list] [--purge]")
print("Options:")
print(f" --cache-dir DIR Specify cache directory (default: {DEFAULT_CACHE_DIR})")
print(" --list List all cache entries")
print(" --purge Purge all cache files")
return
cache_files = [f for f in os.listdir(
cache_dir) if os.path.isfile(os.path.join(cache_dir, f))]
if args.list:
# Use shared b1060time helper from src.server_util
from src.server_util import b1060time_from_epoch
# Load URL and stats from database, then find corresponding cache files
# Prefer explicit sidecar index (cache_files table) if present
url_to_stats = {}
cache_file_to_stats = {}
env_db = os.environ.get('AWT_REQUEST_LOG_DB')
db_candidates = []
if env_db:
db_candidates.append(env_db)
db_candidates.append(DEFAULT_REQUEST_LOG_DB)
db_candidates.append(os.path.join(cache_dir, 'requests.sqlite'))
db_used = None
total_rows = 0
for cpath in db_candidates:
try:
if not os.path.isfile(cpath):
continue
with sqlite3.connect(cpath) as conn:
# Count rows first; skip empty DBs
try:
cur = conn.execute("SELECT COUNT(*) FROM urls")
total_rows = cur.fetchone()[0] or 0
except Exception:
total_rows = 0
if total_rows <= 0:
continue
db_used = cpath
# First, try sidecar mapping table: cache_files (file -> url)
try:
cf_rows = list(conn.execute(
"SELECT file, url, count, first_seen, last_seen FROM cache_files ORDER BY last_seen DESC"))
except Exception:
cf_rows = []
if cf_rows:
for file_basename, url, cnt, first_seen, last_seen in cf_rows:
cache_file_to_stats[file_basename] = {
'url': url,
'count': cnt or 0,
'first_seen': first_seen,
'last_seen': last_seen,
'last_status': 200, # assume success for indexed entries
}
total_rows = len(cf_rows)
break
# Fallback: older DB schema without sidecar index
for url, hsh, cnt, first_seen, last_seen, last_status \
in conn.execute(
"SELECT url, hash, count, first_seen, "
"last_seen, last_status FROM urls "
"ORDER BY last_seen DESC"):
url_to_stats[url] = {
'url': url,
'count': cnt or 0,
'first_seen': first_seen,
'last_seen': last_seen,
'last_status': last_status if last_status is not None else 0,
}
break
except Exception:
continue
# Now correlate URLs to actual cache files by testing Flask-Caching's key function
if url_to_stats and not cache_file_to_stats:
try:
# Import Flask-Caching to use its actual key generation
from flask_caching.backends import FileSystemCache
import tempfile
# Create a temporary cache instance to test key generation
temp_cache = FileSystemCache(cache_dir, threshold=0)
# Test each URL to see which cache file it produces
for url in url_to_stats:
try:
# Use Flask-Caching's internal key generation
cache_key = temp_cache._get_filename(url)
cache_filename = os.path.basename(cache_key)
# Check if this cache file exists
if cache_filename in cache_files:
cache_file_to_stats[cache_filename] = url_to_stats[url]
except Exception:
continue
except Exception:
# Fallback: old approach won't work, but keep the stats for display
pass
# Use cache_file_to_stats instead of stats_map
stats_map = cache_file_to_stats
print(f"AWT cache directory: {cache_dir}")
print(f"Cache file count: {len(cache_files)}")
# Briefly state the request log used to populate URL and counters (if any)
if db_used:
print(f"Request log: {db_used} (rows={total_rows})")
else:
print("Request log: none (URL/stats unavailable)")
if cache_files:
# Column widths: hash(11), size(10 right), sts(3 right), visits(7 right), first(12), last(12), url(variable)
header = f"{'HASH':11} {'SIZE':>10} {'STS':>3} {'VISITS':>7} {'FIRSTVISIT':>12} {'LASTVISIT':>12} URL"
print(header)
matched_files = 0
# If we have a sidecar mapping, enrich with request log stats per URL
if cache_file_to_stats and url_to_stats:
for file_basename, st in list(cache_file_to_stats.items()):
url = st.get('url')
if url and url in url_to_stats:
u = url_to_stats[url]
st['count'] = u.get('count', st.get('count', 0))
st['first_seen'] = u.get('first_seen', st.get('first_seen'))
st['last_seen'] = u.get('last_seen', st.get('last_seen'))
st['last_status'] = u.get('last_status', st.get('last_status'))
for f in cache_files:
full = os.path.join(cache_dir, f)
size = os.path.getsize(full)
short = (f[:8] + '...') if len(f) >= 8 else (f + '...')
st = cache_file_to_stats.get(f) or stats_map.get(f)
if st:
# File has database entry - show full stats
status = f"{st.get('last_status') or '':>3}" if st.get('last_status') else ' '
visits = int(st.get('count') or 0)
first_b = b1060time_from_epoch(st.get('first_seen')) if st.get('first_seen') else ''
last_b = b1060time_from_epoch(st.get('last_seen')) if st.get('last_seen') else ''
url = st.get('url', '')
matched_files += 1
else:
# Cache file exists but no database entry
status = ' '
visits = 0
first_b = ''
last_b = ''
url = ''
print(f"{short:11} {size:10d} {status:>3} {visits:7d} {first_b:12} {last_b:12} {url}")
# Show summary for files without database entries
orphaned_count = len(cache_files) - matched_files
if orphaned_count > 0:
print(f"\nNote: {orphaned_count} cache files have no request log entries")
print("This is normal after clearing request logs or during development.")
else:
print("No cache files found.")
return
if args.purge:
print(f"AWT cache directory: {cache_dir}")
print("Purging all cache files...")
deleted = 0
for f in cache_files:
path = os.path.join(cache_dir, f)
try:
os.unlink(path)
deleted += 1
except Exception as e:
print(f"Failed to delete {f}: {e}")
print(f"Deleted {deleted} cache files.")
return
# No parameters: print summary and usage
print(f"AWT cache directory: {cache_dir}")
print(f"Cache file count: {len(cache_files)}")
if cache_files:
mtimes = [(f, os.path.getmtime(os.path.join(cache_dir, f)))
for f in cache_files]
oldest = min(mtimes, key=lambda x: x[1])
newest = max(mtimes, key=lambda x: x[1])
oldest_str = datetime.datetime.fromtimestamp(
oldest[1]).strftime('%d/%b/%Y %H:%M:%S')
newest_str = datetime.datetime.fromtimestamp(
newest[1]).strftime('%d/%b/%Y %H:%M:%S')
print(f"Oldest entry: {oldest[0]} mtime={oldest_str}")
print(f"Newest entry: {newest[0]} mtime={newest_str}")
else:
print("No cache files found.")
print("\nUsage:")
print(" python cache_awt.py [--cache-dir DIR] [--list] [--purge]")
print("Options:")
print(f" --cache-dir DIR Specify cache directory (default: {DEFAULT_CACHE_DIR})")
print(" --list List all cache entries")
print(" --purge Purge all cache files")
if __name__ == "__main__":
main()