nova-api/api/keys.py

73 lines
1.9 KiB
Python
Raw Normal View History

2023-06-24 15:53:02 +02:00
import json
import os
import random
2023-06-24 16:18:17 +02:00
from pymongo import MongoClient
2023-06-24 15:53:02 +02:00
with open('./config.json', 'r') as file:
config = json.load(file)
class Keys:
# --- START OF CONFIG ---
2023-06-24 16:18:17 +02:00
MONGO_URI = os.getenv('MONGO_URI') or config.get('MONGO_URI')
2023-06-24 15:53:02 +02:00
# --- END OF CONFIG ---
locked_keys = set()
cache = set()
2023-06-24 16:18:17 +02:00
# Initialize MongoDB
client = MongoClient(MONGO_URI)
db = client.get_database('keys_db')
collection = db['keys']
2023-06-24 15:53:02 +02:00
def __init__(self, key: str):
self.key = key
if not Keys.cache:
self._load_keys()
def _load_keys(self) -> None:
2023-06-24 16:18:17 +02:00
cursor = self.collection.find({}, {'_id': 0, 'key_value': 1})
for doc in cursor:
key_value = doc['key_value']
2023-06-24 15:53:02 +02:00
self.cache.add(key_value)
def lock(self) -> None:
self.locked_keys.add(self.key)
def unlock(self) -> None:
self.locked_keys.remove(self.key)
def is_locked(self) -> bool:
return self.key in self.locked_keys
def get() -> str:
key_candidates = list(Keys.cache)
random.shuffle(key_candidates)
for key_candidate in key_candidates:
key = Keys(key_candidate)
if not key.is_locked():
key.lock()
return key.key
print("[WARN] No unlocked keys found in get keys request!")
2023-06-24 16:18:17 +02:00
def delete(self) -> None:
self.collection.delete_one({'key_value': self.key})
2023-06-24 15:53:02 +02:00
# Update cache
try:
Keys.cache.remove(self.key)
except KeyError:
print("[WARN] Tried to remove a key from cache which was not present: " + self.key)
def save(self) -> None:
2023-06-24 16:18:17 +02:00
self.collection.insert_one({'key_value': self.key})
2023-06-24 15:53:02 +02:00
# Update cache
Keys.cache.add(self.key)
# Usage example:
2023-06-24 16:18:17 +02:00
# os.environ['MONGO_URI'] = "mongodb://localhost:27017"
# key_instance = Keys("example_key")
2023-06-24 15:53:02 +02:00
# key_instance.save()
# key_value = Keys.get()