Muttered3 commited on
Commit
8dbf484
Β·
verified Β·
1 Parent(s): 8ff3b41

Create database.py

Browse files
Files changed (1) hide show
  1. database.py +227 -0
database.py ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import redis.asyncio as aioredis
2
+ import asyncio
3
+ from datetime import datetime, timezone
4
+ from config import REDIS_URL
5
+ import config
6
+
7
+ _redis: aioredis.Redis | None = None
8
+
9
+ async def get_redis() -> aioredis.Redis:
10
+ global _redis
11
+ if _redis is None:
12
+ _redis = aioredis.from_url(
13
+ REDIS_URL,
14
+ decode_responses=True,
15
+ socket_connect_timeout=5,
16
+ socket_timeout=5,
17
+ retry_on_timeout=True,
18
+ health_check_interval=30,
19
+ )
20
+ return _redis
21
+
22
+ async def close_redis():
23
+ global _redis
24
+ if _redis:
25
+ await _redis.aclose()
26
+ _redis = None
27
+
28
+ # ── Scan results ─────────────────────────────────────────────────
29
+
30
+ async def push_batch(records: list[dict]):
31
+ """Write scan results to Redis using a chunked pipeline."""
32
+ if not records:
33
+ return
34
+
35
+ r = await get_redis()
36
+ for i in range(0, len(records), 500):
37
+ chunk = records[i : i + 500]
38
+ pipe = r.pipeline(transaction=False)
39
+ for rec in chunk:
40
+ w = rec["Username"]
41
+ s = rec["Status"]
42
+ t = rec["Timestamp"]
43
+ j = rec["JobID"]
44
+ pipe.hset(f"frag:result:{w}", mapping={"status": s, "timestamp": t, "job_id": j})
45
+ pipe.sadd("frag:completed", w)
46
+ pipe.sadd(f"frag:status:{s}", w)
47
+ try:
48
+ await pipe.execute()
49
+ except aioredis.RedisError as e:
50
+ print(f"Redis pipeline error during push_batch: {e}")
51
+
52
+ async def get_completed_words() -> set[str]:
53
+ r = await get_redis()
54
+ try:
55
+ return await r.smembers("frag:completed")
56
+ except aioredis.RedisError:
57
+ return set()
58
+
59
+ async def get_stats() -> dict[str, int]:
60
+ r = await get_redis()
61
+ stats = {}
62
+ try:
63
+ cursor = "0"
64
+ status_keys = []
65
+ while cursor != 0:
66
+ cursor, keys = await r.scan(cursor=cursor, match="frag:status:*", count=100)
67
+ status_keys.extend(keys)
68
+ if cursor == "0":
69
+ break
70
+
71
+ for key in set(status_keys):
72
+ status_name = key.replace("frag:status:", "")
73
+ count = await r.scard(key)
74
+ if count > 0:
75
+ stats[status_name] = count
76
+
77
+ stats["Total"] = await r.scard("frag:completed")
78
+ return dict(sorted(stats.items(), key=lambda item: item[1], reverse=True))
79
+ except aioredis.RedisError:
80
+ return {}
81
+
82
+ async def get_available() -> list[dict]:
83
+ r = await get_redis()
84
+ try:
85
+ words = list(await r.smembers("frag:status:Available"))
86
+ results = []
87
+ for i in range(0, len(words), 500):
88
+ chunk = words[i : i + 500]
89
+ pipe = r.pipeline(transaction=False)
90
+ for w in chunk:
91
+ pipe.hgetall(f"frag:result:{w}")
92
+ chunk_res = await pipe.execute()
93
+ for w, res in zip(chunk, chunk_res):
94
+ if res:
95
+ res["username"] = w
96
+ results.append(res)
97
+ results.sort(key=lambda x: x.get("timestamp", ""), reverse=True)
98
+ return results[:500]
99
+ except aioredis.RedisError:
100
+ return []
101
+
102
+ async def export_all() -> list[dict]:
103
+ r = await get_redis()
104
+ try:
105
+ words = list(await r.smembers("frag:completed"))
106
+ results = []
107
+ for i in range(0, len(words), 500):
108
+ chunk = words[i : i + 500]
109
+ pipe = r.pipeline(transaction=False)
110
+ for w in chunk:
111
+ pipe.hgetall(f"frag:result:{w}")
112
+ chunk_res = await pipe.execute()
113
+ for w, res in zip(chunk, chunk_res):
114
+ if res:
115
+ res["username"] = w
116
+ results.append(res)
117
+ return results
118
+ except aioredis.RedisError:
119
+ return []
120
+
121
+ # ── Job metadata ─────────────────────────────────────────────────
122
+
123
+ async def save_job(job_id: str, data: dict):
124
+ r = await get_redis()
125
+ try:
126
+ pipe = r.pipeline(transaction=False)
127
+ pipe.hset(f"frag:job:{job_id}", mapping=data)
128
+ pipe.lpush("frag:jobs", job_id)
129
+ pipe.ltrim("frag:jobs", 0, 99)
130
+ await pipe.execute()
131
+ except aioredis.RedisError as e:
132
+ print(f"Error saving job: {e}")
133
+
134
+ async def update_job_progress(job_id: str, completed: int):
135
+ r = await get_redis()
136
+ try:
137
+ await r.hset(f"frag:job:{job_id}", "completed_words", str(completed))
138
+ except aioredis.RedisError:
139
+ pass
140
+
141
+ async def finish_job(job_id: str, status: str):
142
+ r = await get_redis()
143
+ try:
144
+ await r.hset(f"frag:job:{job_id}", mapping={
145
+ "status": status,
146
+ "finished_at": datetime.now(timezone.utc).isoformat()
147
+ })
148
+ except aioredis.RedisError:
149
+ pass
150
+
151
+ async def get_job(job_id: str) -> dict | None:
152
+ r = await get_redis()
153
+ try:
154
+ res = await r.hgetall(f"frag:job:{job_id}")
155
+ return res if res else None
156
+ except aioredis.RedisError:
157
+ return None
158
+
159
+ async def get_recent_jobs(n: int = 10) -> list[dict]:
160
+ r = await get_redis()
161
+ try:
162
+ job_ids = await r.lrange("frag:jobs", 0, n - 1)
163
+ pipe = r.pipeline(transaction=False)
164
+ for jid in job_ids:
165
+ pipe.hgetall(f"frag:job:{jid}")
166
+ res = await pipe.execute()
167
+ return [dict(d, id=jid) for d, jid in zip(res, job_ids) if d]
168
+ except aioredis.RedisError:
169
+ return []
170
+
171
+ # ── Runtime config ───────────────────────────────────────────────
172
+
173
+ async def load_runtime_config() -> dict:
174
+ r = await get_redis()
175
+ try:
176
+ cfg = await r.hgetall("frag:config")
177
+ if not cfg:
178
+ default_cfg = {
179
+ "workers": str(config.WORKERS),
180
+ "batch_size": str(config.BATCH_SIZE),
181
+ "delay": str(config.DELAY_BETWEEN_REQUESTS),
182
+ "min_len": str(config.MIN_WORD_LEN),
183
+ "max_len": str(config.MAX_WORD_LEN),
184
+ "retries": str(config.MAX_RETRIES),
185
+ }
186
+ await r.hset("frag:config", mapping=default_cfg)
187
+ return default_cfg
188
+ return cfg
189
+ except aioredis.RedisError:
190
+ return {}
191
+
192
+ async def save_runtime_config(data: dict):
193
+ r = await get_redis()
194
+ try:
195
+ str_data = {k: str(v) for k, v in data.items()}
196
+ await r.hset("frag:config", mapping=str_data)
197
+ except aioredis.RedisError:
198
+ pass
199
+
200
+ # ── Proxy management ─────────────────────────────────────────────
201
+
202
+ async def get_proxies() -> list[str]:
203
+ r = await get_redis()
204
+ try:
205
+ return await r.lrange("frag:proxies", 0, -1)
206
+ except aioredis.RedisError:
207
+ return []
208
+
209
+ async def set_proxies(proxies: list[str]):
210
+ r = await get_redis()
211
+ try:
212
+ pipe = r.pipeline(transaction=False)
213
+ pipe.delete("frag:proxies")
214
+ if proxies:
215
+ pipe.rpush("frag:proxies", *proxies)
216
+ await pipe.execute()
217
+ except aioredis.RedisError:
218
+ pass
219
+
220
+ # ── Health ───────────────────────────────────────────────────────
221
+
222
+ async def ping_db() -> bool:
223
+ try:
224
+ r = await get_redis()
225
+ return await r.ping()
226
+ except Exception:
227
+ return False