Compare commits

...

3 Commits

Author SHA1 Message Date
itqop 736e12cd08 fix: fix colldown 2025-10-15 22:56:19 +03:00
itqop b47d461934 fix: small fixes 2025-10-15 22:52:40 +03:00
itqop 90ac8c6b7e fix: edit config.py 2025-10-15 22:50:21 +03:00
8 changed files with 38 additions and 35 deletions

View File

@ -1,11 +1,11 @@
"""Dependency providers for FastAPI."""
from collections.abc import AsyncGenerator
from fastapi import Depends, HTTPException, Header
from sqlalchemy.ext.asyncio import AsyncSession
from typing import Annotated
from hubgw.context import AppContext
from hubgw.core.config import AppSettings
from hubgw.services.homes_service import HomesService
from hubgw.services.kits_service import KitsService
from hubgw.services.cooldowns_service import CooldownsService
@ -20,7 +20,9 @@ async def get_context() -> AppContext:
return AppContext()
async def get_session(context: Annotated[AppContext, Depends(get_context)]) -> AsyncSession:
async def get_session(
context: Annotated[AppContext, Depends(get_context)]
) -> AsyncGenerator[AsyncSession, None]:
"""Get database session."""
async with context.session_factory() as session:
yield session
@ -31,12 +33,11 @@ async def verify_api_key(
context: Annotated[AppContext, Depends(get_context)]
) -> str:
"""Verify API key."""
if x_api_key != context.settings.API_KEY:
if x_api_key != context.settings.security.api_key:
raise HTTPException(status_code=401, detail="Invalid API key")
return x_api_key
# Service dependencies
def get_homes_service(session: Annotated[AsyncSession, Depends(get_session)]) -> HomesService:
"""Get homes service."""
return HomesService(session)

View File

@ -28,10 +28,10 @@ async def check_cooldown(
@router.put("/touch")
async def touch_cooldown(
key: CooldownKey,
seconds: int = Query(..., description="Cooldown duration in seconds"),
player_uuid: UUID = Query(..., description="Player UUID"),
service: Annotated[CooldownsService, Depends(get_cooldowns_service)],
_: Annotated[str, Depends(verify_api_key)]
_: Annotated[str, Depends(verify_api_key)],
seconds: int = Query(..., description="Cooldown duration in seconds"),
player_uuid: UUID = Query(..., description="Player UUID")
):
"""Touch cooldown."""
try:

View File

@ -5,7 +5,7 @@ from hubgw.api.v1 import health, homes, kits, cooldowns, warps, whitelist, punis
api_router = APIRouter()
# Include all sub-routers
api_router.include_router(health.router, prefix="/health", tags=["health"])
api_router.include_router(homes.router, prefix="/homes", tags=["homes"])
api_router.include_router(kits.router, prefix="/kits", tags=["kits"])

View File

@ -1,7 +1,7 @@
"""Application context singleton."""
from sqlalchemy.ext.asyncio import AsyncEngine, async_sessionmaker, create_async_engine
from hubgw.core.config import AppSettings
from hubgw.core.config import APP_CONFIG
class AppContext:
@ -16,7 +16,7 @@ class AppContext:
def __init__(self):
if not hasattr(self, 'initialized'):
self.settings = AppSettings()
self.settings = APP_CONFIG
self.engine: AsyncEngine = None
self.session_factory: async_sessionmaker = None
self.initialized = True
@ -24,9 +24,10 @@ class AppContext:
async def startup(self):
"""Initialize database engine and session factory."""
self.engine = create_async_engine(
self.settings.DB_DSN,
pool_size=self.settings.DB_POOL_SIZE,
max_overflow=self.settings.DB_MAX_OVERFLOW
self.settings.database.dsn,
pool_size=self.settings.database.pool_size,
max_overflow=self.settings.database.max_overflow,
echo=self.settings.database.echo
)
self.session_factory = async_sessionmaker(
self.engine,

View File

@ -1 +1,6 @@
"""Core module for hubgw."""
from .config import APP_CONFIG
__all__ = [
"APP_CONFIG",
]

View File

@ -120,5 +120,4 @@ class Secrets(BaseSettings):
)
# Global configuration instance
APP_CONFIG = Secrets()

View File

@ -2,12 +2,12 @@
import sys
from loguru import logger
from hubgw.core.config import AppSettings
from hubgw.core.config import APP_CONFIG
def setup_logging():
"""Setup loguru logging configuration."""
settings = AppSettings()
settings = APP_CONFIG.app
# Remove default handler
logger.remove()
@ -15,16 +15,16 @@ def setup_logging():
# Add console handler
logger.add(
sys.stdout,
level=settings.APP_LOG_LEVEL,
level=settings.log_level,
format="<green>{time:YYYY-MM-DD HH:mm:ss}</green> | <level>{level: <8}</level> | <cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>",
colorize=True
)
# Add file handler for production
if settings.APP_ENV == "prod":
if settings.env == "prod":
logger.add(
"logs/hubgw.log",
level=settings.APP_LOG_LEVEL,
level=settings.log_level,
format="{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {name}:{function}:{line} - {message}",
rotation="1 day",
retention="30 days",

View File

@ -1,8 +1,18 @@
"""FastAPI application factory."""
from contextlib import asynccontextmanager
from fastapi import FastAPI
from hubgw.core.logging import setup_logging
from hubgw.context import AppContext
from hubgw.api.v1.router import api_router
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Application lifespan context."""
ctx = AppContext()
await ctx.startup()
yield
await ctx.shutdown()
def create_app() -> FastAPI:
@ -10,25 +20,12 @@ def create_app() -> FastAPI:
app = FastAPI(
title="HubGW",
description="FastAPI Gateway for HubMC",
version="0.1.0"
version="0.1.0",
lifespan=lifespan
)
# Setup logging
setup_logging()
# Initialize context
ctx = AppContext()
@app.on_event("startup")
async def startup():
await ctx.startup()
@app.on_event("shutdown")
async def shutdown():
await ctx.shutdown()
# Include routers
from hubgw.api.v1.router import api_router
app.include_router(api_router, prefix="/api/v1")
return app