Skip to content

Commit 2d027c8

Browse files
committed
feat: implement Redis queue helper functions for Matching Service
1 parent 2abb96c commit 2d027c8

File tree

1 file changed

+40
-0
lines changed
  • services/matching-service/app/services

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import redis
2+
import json
3+
import time
4+
5+
r = redis.Redis(host="localhost", port=6379, db=0, decode_responses=True)
6+
7+
def _queue_key(difficulty: str, topic: str, language: str) -> str:
8+
return f"match_queue:{difficulty}:{topic}:{language}"
9+
10+
def enqueue_user(difficulty: str, topic: str, language: str, user_id: str):
11+
key = _queue_key(difficulty, topic, language)
12+
# add to the end of the queue
13+
r.rpush(key, user_id)
14+
r.hset("match_timestamps", user_id, int(time.time()))
15+
16+
def dequeue_user(difficulty: str, topic: str, language: str):
17+
key = _queue_key(difficulty, topic, language)
18+
# pop from the front (FIFO)
19+
user_id = r.lpop(key)
20+
if user_id:
21+
r.hdel("match_timestamps", user_id)
22+
return user_id
23+
24+
def get_queue_position(difficulty: str, topic: str, language: str, user_id: str):
25+
key = _queue_key(difficulty, topic, language)
26+
queue = r.lrange(key, 0, -1)
27+
try:
28+
return queue.index(user_id) + 1
29+
except ValueError:
30+
return None
31+
32+
def remove_user(difficulty: str, topic: str, language: str, user_id: str):
33+
key = _queue_key(difficulty, topic, language)
34+
removed = r.lrem(key, 0, user_id)
35+
r.hdel("match_timestamps", user_id)
36+
return removed > 0
37+
38+
def get_user_join_time(user_id: str):
39+
ts = r.hget("match_timestamps", user_id)
40+
return int(ts) if ts else None

0 commit comments

Comments
 (0)