Skip to content

Commit 673af9e

Browse files
committed
Move more cache functions over
1 parent 0258597 commit 673af9e

File tree

2 files changed

+77
-74
lines changed

2 files changed

+77
-74
lines changed

tools/analytics/org/analyze_runner_usage.py

Lines changed: 1 addition & 73 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,6 @@
5555
"""
5656

5757
import argparse
58-
import json
5958
import logging
6059
import os
6160
from collections import defaultdict
@@ -65,10 +64,9 @@
6564

6665
import requests
6766
import yaml
67+
from cache_manager import get_cache_stats, make_cached_request
6868
from dotenv import load_dotenv
6969

70-
from cache_manager import CACHE_DIR, CacheManager
71-
7270

7371
load_dotenv()
7472

@@ -149,50 +147,6 @@
149147
BASE_URL = "https://api.github.com"
150148
WORKFLOW_RUN_LOOKBACK = (datetime.utcnow() - timedelta(days=180)).isoformat() + "Z"
151149

152-
# Global cache manager instance
153-
cache_manager = CacheManager()
154-
155-
156-
def make_cached_request(
157-
url: str, headers: Optional[Dict[str, str]] = None
158-
) -> Optional[Dict]:
159-
"""
160-
Make an HTTP request with caching. Returns the JSON response if successful.
161-
162-
Args:
163-
url: The URL to request
164-
headers: Optional headers for the request
165-
166-
Returns:
167-
JSON response data if successful, None if failed
168-
"""
169-
# Check cache first
170-
cached_response = cache_manager.get(url)
171-
if cached_response:
172-
logging.info(f"[make_cached_request] Using cached response for: {url}")
173-
return cached_response
174-
175-
# Make actual HTTP request
176-
logging.info(f"[make_cached_request] Making HTTP request to: {url}")
177-
try:
178-
response = requests.get(url, headers=headers or HEADERS)
179-
response.raise_for_status()
180-
data = response.json()
181-
182-
# Cache successful response
183-
cache_manager.set(url, data)
184-
logging.info(f"[make_cached_request] Successfully cached response for: {url}")
185-
return data
186-
187-
except requests.exceptions.RequestException as e:
188-
logging.error(f"[make_cached_request] HTTP request failed for {url}: {e}")
189-
return None
190-
except json.JSONDecodeError as e:
191-
logging.error(
192-
f"[make_cached_request] Failed to parse JSON response for {url}: {e}"
193-
)
194-
return None
195-
196150

197151
def get_repos(org: str) -> List[str]:
198152
logging.info(f"[get_repos] Start fetching repositories for org: {org}")
@@ -445,32 +399,6 @@ def save_to_yaml(data: Dict, filename: str = "runner_labels_summary.yml"):
445399
logging.info(f"[save_to_yaml] Data successfully saved to {filename}")
446400

447401

448-
def clear_cache():
449-
"""Clear all cached data."""
450-
import shutil
451-
452-
if CACHE_DIR.exists():
453-
shutil.rmtree(CACHE_DIR)
454-
CACHE_DIR.mkdir(exist_ok=True)
455-
logging.info(f"[clear_cache] Cleared cache directory: {CACHE_DIR}")
456-
else:
457-
logging.info(f"[clear_cache] Cache directory does not exist: {CACHE_DIR}")
458-
459-
460-
def get_cache_stats():
461-
"""Get statistics about the cache."""
462-
if not CACHE_DIR.exists():
463-
return {"total_files": 0, "total_size_mb": 0}
464-
465-
cache_files = list(CACHE_DIR.glob("*.json"))
466-
total_size = sum(f.stat().st_size for f in cache_files)
467-
468-
return {
469-
"total_files": len(cache_files),
470-
"total_size_mb": round(total_size / (1024 * 1024), 2),
471-
}
472-
473-
474402
def download_scale_config(url: str, dest: str = "scale-config.yml") -> bool:
475403
"""Download scale-config.yml from the given URL if it does not exist locally."""
476404
if os.path.exists(dest):

tools/analytics/org/cache_manager.py

Lines changed: 76 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,10 @@
44
from pathlib import Path
55
from typing import Dict, Optional
66

7+
import requests
8+
9+
from tools.analytics.org.analyze_runner_usage import cache_manager, HEADERS
10+
711

812
# Cache configuration
913
CACHE_DIR = Path("cache")
@@ -95,4 +99,75 @@ def set(self, url: str, data: Dict) -> None:
9599
json.dump(data, f, indent=2)
96100
logging.debug(f"[CacheManager] Cached response for URL: {url}")
97101
except IOError as e:
98-
logging.error(f"[CacheManager] Failed to write cache for {url}: {e}")
102+
logging.error(f"[CacheManager] Failed to write cache for {url}: {e}")
103+
104+
105+
# Global cache manager instance
106+
cache_manager = CacheManager()
107+
108+
109+
def get_cache_stats():
110+
"""Get statistics about the cache."""
111+
if not CACHE_DIR.exists():
112+
return {"total_files": 0, "total_size_mb": 0}
113+
114+
cache_files = list(CACHE_DIR.glob("*.json"))
115+
total_size = sum(f.stat().st_size for f in cache_files)
116+
117+
return {
118+
"total_files": len(cache_files),
119+
"total_size_mb": round(total_size / (1024 * 1024), 2),
120+
}
121+
122+
123+
def clear_cache():
124+
"""Clear all cached data."""
125+
import shutil
126+
127+
if CACHE_DIR.exists():
128+
shutil.rmtree(CACHE_DIR)
129+
CACHE_DIR.mkdir(exist_ok=True)
130+
logging.info(f"[clear_cache] Cleared cache directory: {CACHE_DIR}")
131+
else:
132+
logging.info(f"[clear_cache] Cache directory does not exist: {CACHE_DIR}")
133+
134+
135+
def make_cached_request(
136+
url: str, headers: Optional[Dict[str, str]] = None
137+
) -> Optional[Dict]:
138+
"""
139+
Make an HTTP request with caching. Returns the JSON response if successful.
140+
141+
Args:
142+
url: The URL to request
143+
headers: Optional headers for the request
144+
145+
Returns:
146+
JSON response data if successful, None if failed
147+
"""
148+
# Check cache first
149+
cached_response = cache_manager.get(url)
150+
if cached_response:
151+
logging.info(f"[make_cached_request] Using cached response for: {url}")
152+
return cached_response
153+
154+
# Make actual HTTP request
155+
logging.info(f"[make_cached_request] Making HTTP request to: {url}")
156+
try:
157+
response = requests.get(url, headers=headers or HEADERS)
158+
response.raise_for_status()
159+
data = response.json()
160+
161+
# Cache successful response
162+
cache_manager.set(url, data)
163+
logging.info(f"[make_cached_request] Successfully cached response for: {url}")
164+
return data
165+
166+
except requests.exceptions.RequestException as e:
167+
logging.error(f"[make_cached_request] HTTP request failed for {url}: {e}")
168+
return None
169+
except json.JSONDecodeError as e:
170+
logging.error(
171+
f"[make_cached_request] Failed to parse JSON response for {url}: {e}"
172+
)
173+
return None

0 commit comments

Comments
 (0)