-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache.py
More file actions
231 lines (168 loc) · 5.59 KB
/
Copy pathcache.py
File metadata and controls
231 lines (168 loc) · 5.59 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
import time
from typing import TypedDict
from datetime import datetime
from zoneinfo import ZoneInfo
from app.utils.config import CACHE_TTL, MAX_RECENT_URLS
class UrlCacheItem(TypedDict):
url: str
expires_at: float
visit_count: int
class RevCacheItem(TypedDict):
short_code: str
expires_at: float
created_at: float
last_accessed: float
class RecentItem(TypedDict):
short_code: str
original_url: str
created_at: float
visit_count: int
# -----------------------
# Performance caches (TTL)
# -----------------------
# short_code -> original_url
url_cache: dict[str, UrlCacheItem] = {}
# original_url -> short_code (+ metadata for recent tracking)
rev_cache: dict[str, RevCacheItem] = {}
# short_code -> visit_count (temporary, in-memory)
visit_cache: dict[str, int] = {}
def _now() -> float:
return time.time()
# -----------------------
# Core cache operations
# -----------------------
def _enforce_recent_limit() -> None:
"""
Ensure rev_cache keeps only MAX_RECENT_URLS most recent items.
Removes the oldest entries by created_at.
"""
if len(rev_cache) <= MAX_RECENT_URLS:
return
sorted_items = sorted(
rev_cache.items(),
key=lambda item: item[1]["created_at"],
)
excess = len(rev_cache) - MAX_RECENT_URLS
for i in range(excess):
original_url, _ = sorted_items[i]
rev_cache.pop(original_url, None)
def set_cache_pair(short_code: str, original_url: str) -> None:
now = _now()
expires_at = now + CACHE_TTL
url_cache[short_code] = {
"url": original_url,
"expires_at": expires_at,
"visit_count": 0,
}
rev_cache[original_url] = {
"short_code": short_code,
"expires_at": expires_at,
"created_at": now,
"last_accessed": now,
}
_enforce_recent_limit()
def increment_visit_cache(short_code: str) -> None:
visit_cache[short_code] = visit_cache.get(short_code, 0) + 1
def get_from_cache(short_code: str) -> str | None:
data = url_cache.get(short_code)
if not data:
return None
if data["expires_at"] < _now():
url_cache.pop(short_code, None)
_remove_recent_if_exists(short_code)
return None
return data["url"]
def get_short_from_cache(original_url: str) -> str | None:
data = rev_cache.get(original_url)
if not data:
return None
if data["expires_at"] < _now():
rev_cache.pop(original_url, None)
return None
data["last_accessed"] = _now()
return data["short_code"]
def get_recent_from_cache(limit: int = MAX_RECENT_URLS) -> list[RecentItem]:
now = _now()
valid_items: list[RecentItem] = []
for original_url, data in rev_cache.items():
if data["expires_at"] >= now:
short_code = data["short_code"]
valid_items.append(
{
"short_code": data["short_code"],
"original_url": original_url,
"created_at": data["created_at"],
"visit_count": visit_cache.get(short_code, 0),
}
)
valid_items.sort(key=lambda x: x["created_at"], reverse=True)
return valid_items[:limit]
def cleanup_expired() -> None:
now = _now()
expired_short_codes = [
short_code for short_code, data in url_cache.items() if data["expires_at"] < now
]
for short_code in expired_short_codes:
url_cache.pop(short_code, None)
_remove_recent_if_exists(short_code)
expired_original_urls = [
original_url
for original_url, data in rev_cache.items()
if data["expires_at"] < now
]
for original_url in expired_original_urls:
rev_cache.pop(original_url, None)
def clear_cache() -> None:
url_cache.clear()
rev_cache.clear()
def _remove_recent_if_exists(short_code: str) -> None:
to_delete = None
for original_url, data in rev_cache.items():
if data["short_code"] == short_code:
to_delete = original_url
break
if to_delete:
rev_cache.pop(to_delete, None)
# -----------------------
# UI helpers
# -----------------------
def list_cache_clean() -> dict:
"""
Clean UI-friendly cache view (TTL-aware, no debug noise).
"""
now = _now()
items = [
{
"short_code": data["short_code"],
"original_url": original_url,
"created_at": datetime.fromtimestamp(
data["created_at"], tz=ZoneInfo("Asia/Kolkata")
).strftime("%d %b %Y, %I:%M %p"),
}
for original_url, data in rev_cache.items()
if data["expires_at"] >= now
]
return {
"count": len(items),
"items": items,
"MAX_RECENT_URLS": MAX_RECENT_URLS,
"CACHE_TTL": CACHE_TTL,
}
def remove_cache_key(key: str) -> bool:
"""
Remove a cache entry by short_code OR original_url.
"""
is_url = key.startswith("http://") or key.startswith("https://")
if is_url:
rev_item = rev_cache.pop(key, None)
if rev_item:
url_cache.pop(rev_item["short_code"], None)
visit_cache.pop(rev_item["short_code"], None)
return True
else:
url_item = url_cache.pop(key, None)
if url_item:
rev_cache.pop(url_item["url"], None)
visit_cache.pop(key, None)
return True
return False