Muttered3 commited on
Commit
6fe06d8
Β·
verified Β·
1 Parent(s): d4685a4

Update database.py

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