refactor: update store to use the document ids instead of uuids

Refs: OPS-21 OPS-16
This commit is contained in:
Christoph J. Scherr 2025-02-25 17:38:46 +01:00
parent d7dece3424
commit 6b6f442408
No known key found for this signature in database
GPG key ID: 9EB784BB202BB7BB
2 changed files with 19 additions and 36 deletions

View file

@ -1,8 +1,7 @@
from typing import Optional
from tinydb import TinyDB, Query
from uuid import UUID, uuid1
from tinydb import TinyDB
from pathlib import Path
import time
from logging import Logger
from tinydb.queries import QueryImpl
@ -10,41 +9,23 @@ DEFAULT_DB_PATH: Path = Path("/var/lib/senju.json")
class StoreManager:
__slots__ = "_db"
__slots__ = "_db", "logger"
_db: TinyDB
logger: Logger
def __init__(self, path_to_db: Path = DEFAULT_DB_PATH) -> None:
self._db = TinyDB(path_to_db)
def new_id(self) -> UUID:
_guard: int = 0
while True:
unix_timestamp: int = int(time.time())
id = uuid1(node=None, clock_seq=unix_timestamp)
if len(self._query(Query().id == id)) < 1:
break
_guard += 1
if _guard > 100:
raise Exception(
"tried 100 random UUIDs but found no unused one")
return id
self.logger = Logger(__name__)
def _query(self, query: QueryImpl) -> list[dict]:
return self._db.search(query)
def load(self, key: UUID) -> Optional[dict]:
results = self._query(Query().id == str(key))
if len(results) < 1:
raise Exception("foobar")
elif len(results) > 2:
raise KeyError("The requested item did not exist in our database")
else:
return results[0]["data"]
def _load(self, id: int) -> Optional[dict]:
try:
return self._db.get(doc_id=id)
except IndexError as e:
self.logger.warning(f"could not get item with id {id}: {e}")
return None
def save(self, data: dict) -> UUID:
id = self.new_id()
self._db.insert({
"id": str(id),
"data": data
})
return id
def _save(self, data: dict) -> int:
return self._db.insert(data)