nova-api/api/keys.py

76 lines
2.2 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()
2023-06-24 19:26:36 +02:00
cache = {}
2023-06-24 15:53:02 +02:00
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 19:26:36 +02:00
def __init__(self, key: str, model: str):
2023-06-24 15:53:02 +02:00
self.key = key
2023-06-24 19:26:36 +02:00
self.model = model
2023-06-24 15:53:02 +02:00
if not Keys.cache:
self._load_keys()
def _load_keys(self) -> None:
2023-06-24 19:26:36 +02:00
cursor = Keys.collection.find({}, {'_id': 0, 'key_value': 1, 'model': 1})
2023-06-24 16:18:17 +02:00
for doc in cursor:
key_value = doc['key_value']
2023-06-24 19:26:36 +02:00
model = doc['model']
Keys.cache.setdefault(model, set()).add(key_value)
2023-06-24 15:53:02 +02:00
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
2023-06-24 19:26:36 +02:00
@staticmethod
def get(model: str) -> str:
key_candidates = list(Keys.cache.get(model, set()))
2023-06-24 15:53:02 +02:00
random.shuffle(key_candidates)
for key_candidate in key_candidates:
2023-06-24 19:26:36 +02:00
key = Keys(key_candidate, model)
2023-06-24 15:53:02 +02:00
if not key.is_locked():
key.lock()
return key.key
2023-06-24 19:26:36 +02:00
print(f"[WARN] No unlocked keys found for model '{model}' in get keys request!")
2023-06-24 15:53:02 +02:00
2023-06-24 16:18:17 +02:00
def delete(self) -> None:
2023-06-24 19:26:36 +02:00
Keys.collection.delete_one({'key_value': self.key, 'model': self.model})
2023-06-24 15:53:02 +02:00
# Update cache
try:
2023-06-24 19:26:36 +02:00
Keys.cache[self.model].remove(self.key)
2023-06-24 15:53:02 +02:00
except KeyError:
2023-06-24 19:26:36 +02:00
print(f"[WARN] Tried to remove a key from cache which was not present: {self.key}")
2023-06-24 15:53:02 +02:00
def save(self) -> None:
2023-06-24 19:26:36 +02:00
Keys.collection.insert_one({'key_value': self.key, 'model': self.model})
2023-06-24 15:53:02 +02:00
# Update cache
2023-06-24 19:26:36 +02:00
Keys.cache.setdefault(self.model, set()).add(self.key)
2023-06-24 15:53:02 +02:00
# Usage example:
2023-06-24 16:18:17 +02:00
# os.environ['MONGO_URI'] = "mongodb://localhost:27017"
2023-06-24 19:26:36 +02:00
# key_instance = Keys("example_key", "example_model")
2023-06-24 15:53:02 +02:00
# key_instance.save()
2023-06-24 19:26:36 +02:00
# key_value = Keys.get("example_model")