Добавлена ветка prod_prep

This commit is contained in:
grigorij
2026-07-31 12:58:23 +04:00
parent bf26370da9
commit f289631645
36 changed files with 893 additions and 290 deletions
+40 -4
View File
@@ -4,8 +4,9 @@ import signal
import sys
from aiogram import Bot, Dispatcher
from aiogram.fsm.storage.redis import RedisStorage, DefaultKeyBuilder
from app.config import BOT_TOKEN
from app.config import BOT_TOKEN, USE_POSTGRES
from app.logger import logger
# Import routers
@@ -19,7 +20,13 @@ from app.handlers.contacts import router as contacts_router
from app.handlers.admin import router as admin_router
bot = Bot(token=BOT_TOKEN)
dp = Dispatcher()
# Redis FSM storage — survives bot restarts, persistent across polling sessions
redis_storage = RedisStorage.from_url(
"redis://localhost:6379/0",
key_builder=DefaultKeyBuilder(with_destiny=True)
)
dp = Dispatcher(storage=redis_storage)
# Register routers
dp.include_routers(
@@ -33,9 +40,20 @@ dp.include_routers(
admin_router,
)
_health_runner = None
async def on_startup():
"""Called when bot starts."""
# Initialize Postgres pool if available
if USE_POSTGRES:
try:
from app.db.postgres import PostgresDB
await PostgresDB.init_pool()
logger.info("PostgreSQL pool initialized")
except Exception as e:
logger.warning("PostgreSQL init failed, falling back to JSON: {error}", error=e)
me = await bot.get_me()
logger.info(
"Bot started | @{username} (id={id}) | Token: {token_preview}...",
@@ -43,12 +61,31 @@ async def on_startup():
id=me.id,
token_preview=BOT_TOKEN[:10],
)
# Start healthcheck server
try:
from app.health import start_health_server
global _health_runner
_health_runner = await start_health_server(port=8080)
except Exception as e:
logger.warning("Healthcheck server not started: {error}", error=e)
async def on_shutdown():
"""Called when bot shuts down."""
logger.info("Bot shutting down...")
# Give running tasks time to finish
if USE_POSTGRES:
try:
from app.db.postgres import PostgresDB
await PostgresDB.close()
logger.info("PostgreSQL pool closed")
except Exception as e:
logger.warning("PostgreSQL pool close error: {error}", error=e)
if _health_runner:
await _health_runner.cleanup()
logger.info("Healthcheck server stopped")
if redis_storage:
await redis_storage.close()
logger.info("Redis storage closed")
pending = asyncio.all_tasks()
if pending:
logger.debug("Cancelling {count} pending tasks", count=len(pending))
@@ -74,7 +111,6 @@ async def main():
try:
loop.add_signal_handler(sig, lambda s=sig: _signal_handler(s, None))
except NotImplementedError:
# Windows fallback
signal.signal(sig, _signal_handler)
try: