This commit is contained in:
@@ -5,6 +5,10 @@ from starlette.exceptions import HTTPException
|
||||
from services.core import get_author_by_user
|
||||
from settings import AUTH_URL
|
||||
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger("[services.auth] ")
|
||||
logger.setLevel(logging.DEBUG)
|
||||
|
||||
async def check_auth(req) -> str | None:
|
||||
token = req.headers.get("Authorization")
|
||||
@@ -38,14 +42,14 @@ async def check_auth(req) -> str | None:
|
||||
data = await response.json()
|
||||
errors = data.get("errors")
|
||||
if errors:
|
||||
print(f"[services.auth] errors: {errors}")
|
||||
logger.error(f"{errors}")
|
||||
else:
|
||||
user_id = data.get("data", {}).get(query_name, {}).get("claims", {}).get("sub")
|
||||
print(f"[services.auth] got user_id: {user_id}")
|
||||
logger.info(f"[services.auth] got user_id: {user_id}")
|
||||
return user_id
|
||||
except Exception as e:
|
||||
# Handling and logging exceptions during authentication check
|
||||
print(f"[services.auth] {e}")
|
||||
logger.error(e)
|
||||
|
||||
if not user_id:
|
||||
raise HTTPException(status_code=401, detail="Unauthorized")
|
||||
|
@@ -6,21 +6,30 @@ from datetime import datetime, timezone, timedelta
|
||||
from models.member import ChatMember
|
||||
from settings import API_BASE
|
||||
|
||||
import time
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger("[services.core] ")
|
||||
logger.setLevel(logging.DEBUG)
|
||||
|
||||
|
||||
def _request_endpoint(query_name, body) -> dict:
|
||||
print(f"[services.core] requesting {query_name}...")
|
||||
ts1 = time.time()
|
||||
logger.debug(f"requesting {query_name}...")
|
||||
response = requests.post(API_BASE, headers={"Content-Type": "application/json"}, json=body)
|
||||
print(f"[services.core] {query_name} response: <{response.status_code}> {response.text[:32]}..")
|
||||
ts2 = time.time()
|
||||
logger.debug(f"{query_name} response in {ts1-ts2} secs: <{response.status_code}> {response.text[:32]}..")
|
||||
|
||||
|
||||
if response.status_code == 200:
|
||||
try:
|
||||
r = response.json()
|
||||
result = r.get("data", {}).get(query_name, {})
|
||||
if result:
|
||||
print(f"[services.core] entries amount in result: {len(result)} ")
|
||||
logger.info(f"entries amount in result: {len(result)} ")
|
||||
return result
|
||||
except ValueError as e:
|
||||
print(f"[services.core] Error decoding JSON response: {e}")
|
||||
logger.error(f"Error decoding JSON response: {e}")
|
||||
|
||||
return {}
|
||||
|
||||
@@ -42,7 +51,7 @@ def get_author_by_user(user: str):
|
||||
gql = {
|
||||
"query": f"query {operation}($user: String!) {{ {query_name}(user: $user){{ id }} }}",
|
||||
"operationName": operation,
|
||||
"variables": {"user": user},
|
||||
"variables": {"user": user.strip()},
|
||||
}
|
||||
|
||||
return _request_endpoint(query_name, gql)
|
||||
@@ -74,14 +83,14 @@ class CacheStorage:
|
||||
self = CacheStorage
|
||||
async with self.lock:
|
||||
task = asyncio.create_task(self.worker())
|
||||
print(task)
|
||||
logger.info(task)
|
||||
|
||||
@staticmethod
|
||||
async def update_authors():
|
||||
self = CacheStorage
|
||||
async with self.lock:
|
||||
result = get_all_authors()
|
||||
print(f"[services.core] loaded {len(result)}")
|
||||
logger.info(f"cache loaded {len(result)}")
|
||||
if result:
|
||||
CacheStorage.authors = result
|
||||
for a in result:
|
||||
@@ -95,20 +104,20 @@ class CacheStorage:
|
||||
self = CacheStorage
|
||||
while True:
|
||||
try:
|
||||
print("[services.core] - updating profiles data...")
|
||||
logger.info(" - updating profiles data...")
|
||||
await self.update_authors()
|
||||
failed = 0
|
||||
except Exception as er:
|
||||
failed += 1
|
||||
print(f"[services.core] {er} - update failed #{failed}, wait 10 seconds")
|
||||
logger.error(f"{er} - update failed #{failed}, wait 10 seconds")
|
||||
if failed > 3:
|
||||
print("[services.core] - not trying to update anymore")
|
||||
logger.error(" - not trying to update anymore")
|
||||
break
|
||||
if failed == 0:
|
||||
when = datetime.now(timezone.utc) + timedelta(seconds=self.period)
|
||||
t = format(when.astimezone().isoformat())
|
||||
print("[services.core] ⎩ next update: %s" % (t.split("T")[0] + " " + t.split("T")[1].split(".")[0]))
|
||||
logger.info(" ⎩ next update: %s" % (t.split("T")[0] + " " + t.split("T")[1].split(".")[0]))
|
||||
await asyncio.sleep(self.period)
|
||||
else:
|
||||
await asyncio.sleep(10)
|
||||
print("[services.core] - trying to update data again")
|
||||
logger.info(" - trying to update data again")
|
||||
|
@@ -24,7 +24,6 @@ class RedisCache:
|
||||
return r
|
||||
except Exception as e:
|
||||
print(f"[redis] error: {e}")
|
||||
return None
|
||||
|
||||
async def subscribe(self, *channels):
|
||||
if self._client:
|
||||
@@ -46,11 +45,6 @@ class RedisCache:
|
||||
return
|
||||
await self._client.publish(channel, data)
|
||||
|
||||
async def lrange(self, key, start, stop):
|
||||
if self._client:
|
||||
print(f"[redis] LRANGE {key} {start} {stop}")
|
||||
return await self._client.lrange(key, start, stop)
|
||||
|
||||
async def mget(self, key, *keys):
|
||||
if self._client:
|
||||
print(f"[redis] MGET {key} {keys}")
|
||||
|
Reference in New Issue
Block a user