22Main FastAPI application
33"""
44import logging
5+ from contextlib import asynccontextmanager
6+
57from fastapi import FastAPI
68from fastapi .middleware .cors import CORSMiddleware
7- from contextlib import asynccontextmanager
89
9- from app .config import settings
1010from app .api .routes import router
11- from app .services .telegram import telegram_service
11+ from app .config import settings
12+ from app .middleware import LoggingMiddleware , SecurityHeadersMiddleware
1213from app .services .mongodb import mongodb_service
14+ from app .services .telegram import telegram_service
1315from app .utils .session_manager import session_manager
1416
1517# Configure logging
1618logging .basicConfig (
1719 level = logging .INFO if not settings .debug else logging .DEBUG ,
18- format = ' %(asctime)s - %(name)s - %(levelname)s - %(message)s'
20+ format = " %(asctime)s - %(name)s - %(levelname)s - %(message)s" ,
1921)
2022logger = logging .getLogger (__name__ )
2123
2224
2325@asynccontextmanager
2426async def lifespan (app : FastAPI ):
25- """
26- Lifespan context manager for startup and shutdown events
27- """
28- # Startup
27+ """Lifespan context manager for startup and shutdown events."""
2928 logger .info ("Starting Telegram Service..." )
30-
31- # Connect to MongoDB
29+
30+ # Connect to MongoDB and initialize session manager
3231 try :
3332 await mongodb_service .connect ()
34- logger .info ("Connected to MongoDB successfully" )
35-
36- # Initialize session manager with MongoDB
3733 session_manager .set_mongodb_service (mongodb_service )
38- logger .info ("Session manager initialized with MongoDB" )
39-
40- except Exception as e :
41- logger .error (f"Failed to connect to MongoDB: { e } " )
34+ logger .info ("Connected to MongoDB and initialized session manager" )
35+ except Exception as exc :
36+ logger .error (f"Failed to connect to MongoDB: { exc } " )
4237 raise
43-
38+
4439 # Reconnect existing sessions
4540 try :
46- active_sessions = session_manager .get_all_active_sessions ()
47- logger .info (f"Found { len (active_sessions )} active sessions to reconnect" )
48-
41+ active_sessions = await session_manager .get_all_active_sessions ()
42+ logger .info (
43+ f"Found { len (active_sessions )} active sessions to reconnect" )
44+
4945 for session in active_sessions :
46+ session_id = session .get ("session_id" )
47+ agent_id = session .get ("agent_id" )
48+ if not session_id :
49+ continue
50+
5051 try :
51- success = await telegram_service .reconnect_client (session . session_id )
52+ success = await telegram_service .reconnect_client (session_id )
5253 if success :
53- logger .info (f"Reconnected session: { session .session_id } " )
54- # Setup message handler
54+ logger .info (f"Reconnected session: { session_id } " )
5555 await telegram_service .setup_message_handler (
56- session_id = session . session_id ,
57- agent_id = session . agent_id
56+ session_id = session_id ,
57+ agent_id = agent_id ,
5858 )
5959 else :
60- logger .warning (f"Failed to reconnect session: { session .session_id } " )
61- session_manager .deactivate_session (session .session_id )
62- except Exception as e :
63- logger .error (f"Error reconnecting session { session .session_id } : { e } " )
64- session_manager .deactivate_session (session .session_id )
65- except Exception as e :
66- logger .error (f"Error during startup reconnection: { e } " )
67-
60+ logger .warning (
61+ f"Failed to reconnect session: { session_id } " )
62+ await session_manager .deactivate_session (session_id )
63+ except Exception as exc : # pragma: no cover - defensive logging
64+ logger .error (f"Error reconnecting session { session_id } : { exc } " )
65+ await session_manager .deactivate_session (session_id )
66+ except Exception as exc : # pragma: no cover - defensive logging
67+ logger .error (f"Error during startup reconnection: { exc } " )
68+
6869 logger .info ("Telegram Service started successfully" )
69-
70+
71+ # Application is running
7072 yield
71-
72- # Shutdown
73+
74+ # Shutdown sequence
7375 logger .info ("Shutting down Telegram Service..." )
74-
75- # Disconnect all clients gracefully
76- for session_id in list (telegram_service .clients .keys ()):
77- # Disconnect from MongoDB
78- try :
79- await mongodb_service .disconnect ()
80- logger .info ("Disconnected from MongoDB" )
81- except Exception as e :
82- logger .error (f"Error disconnecting from MongoDB: { e } " )
83-
76+
77+ # Disconnect Telegram clients
78+ for session_id , client in list (telegram_service .clients .items ()):
8479 try :
85- client = telegram_service .clients [session_id ]
8680 if client .is_connected ():
8781 await client .disconnect ()
8882 logger .info (f"Disconnected session: { session_id } " )
89- except Exception as e :
90- logger .error (f"Error disconnecting session { session_id } : { e } " )
91-
83+ except Exception as exc : # pragma: no cover - defensive logging
84+ logger .error (f"Error disconnecting session { session_id } : { exc } " )
85+
86+ # Disconnect from MongoDB
87+ try :
88+ await mongodb_service .disconnect ()
89+ logger .info ("Disconnected from MongoDB" )
90+ except Exception as exc : # pragma: no cover - defensive logging
91+ logger .error (f"Error disconnecting from MongoDB: { exc } " )
92+
9293 logger .info ("Telegram Service shut down successfully" )
9394
9495
@@ -97,47 +98,45 @@ async def lifespan(app: FastAPI):
9798 title = "Telegram Service API" ,
9899 description = "A Python service for managing Telegram connections and messages" ,
99100 version = "1.0.0" ,
100- lifespan = lifespan
101+ lifespan = lifespan ,
101102)
102103
103- #
104+ # CORS (allow all origins for simplicity; tighten if needed)
105+ app .add_middleware (
106+ CORSMiddleware ,
107+ allow_origins = ["*" ],
108+ allow_credentials = True ,
104109 allow_methods = ["*" ],
105110 allow_headers = ["*" ],
106111)
107112
108- # Add custom middlewares
113+ # Custom middlewares
109114app .add_middleware (LoggingMiddleware )
110115app .add_middleware (SecurityHeadersMiddleware )
111116
112- # Include routers
117+ # Routes
113118app .include_router (router )
114119
115120
116121@app .get ("/" )
117122async def root ():
118123 """Root endpoint"""
119- return {
120- "service" : "Telegram Service" ,
121- "version" : "1.0.0" ,
122- "status" : "running"
123- }
124+ return {"service" : "Telegram Service" , "version" : "1.0.0" , "status" : "running" }
124125
125126
126127@app .get ("/health" )
127128async def health_check ():
128129 """Health check endpoint"""
129130 active_sessions = len (telegram_service .clients )
130- return {
131- "status" : "healthy" ,
132- "active_sessions" : active_sessions
133- }
131+ return {"status" : "healthy" , "active_sessions" : active_sessions }
134132
135133
136134if __name__ == "__main__" :
137135 import uvicorn
136+
138137 uvicorn .run (
139138 "app.main:app" ,
140139 host = settings .host ,
141140 port = settings .port ,
142- reload = settings .debug
141+ reload = settings .debug ,
143142 )
0 commit comments