Refactor all main.py
This commit is contained in:
@@ -3,131 +3,150 @@ POS Integration Service
|
||||
Handles integration with external POS systems (Square, Toast, Lightspeed)
|
||||
"""
|
||||
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import JSONResponse
|
||||
import structlog
|
||||
import time
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import FastAPI, Request
|
||||
from app.core.config import settings
|
||||
from app.api import pos_config, webhooks, sync
|
||||
from app.core.database import init_db, close_db
|
||||
from shared.monitoring.health import router as health_router
|
||||
from shared.monitoring.logging import setup_logging
|
||||
from app.core.database import database_manager
|
||||
from shared.service_base import StandardFastAPIService
|
||||
|
||||
|
||||
# Setup logging
|
||||
setup_logging(service_name="pos-service")
|
||||
logger = structlog.get_logger()
|
||||
class POSService(StandardFastAPIService):
|
||||
"""POS Integration Service with standardized setup"""
|
||||
|
||||
def __init__(self):
|
||||
# Define expected database tables for health checks
|
||||
pos_expected_tables = [
|
||||
'pos_configurations', 'pos_transactions', 'pos_transaction_items',
|
||||
'pos_webhook_logs', 'pos_sync_logs'
|
||||
]
|
||||
|
||||
# Define custom metrics for POS service
|
||||
pos_custom_metrics = {
|
||||
"pos_webhooks_received_total": {
|
||||
"type": "counter",
|
||||
"description": "Total POS webhooks received",
|
||||
"labels": ["provider", "event_type"]
|
||||
},
|
||||
"pos_sync_jobs_total": {
|
||||
"type": "counter",
|
||||
"description": "Total POS sync jobs",
|
||||
"labels": ["provider", "status"]
|
||||
},
|
||||
"pos_transactions_synced_total": {
|
||||
"type": "counter",
|
||||
"description": "Total transactions synced",
|
||||
"labels": ["provider"]
|
||||
},
|
||||
"pos_webhook_processing_duration_seconds": {
|
||||
"type": "histogram",
|
||||
"description": "Time spent processing webhooks"
|
||||
},
|
||||
"pos_sync_duration_seconds": {
|
||||
"type": "histogram",
|
||||
"description": "Time spent syncing data"
|
||||
}
|
||||
}
|
||||
|
||||
super().__init__(
|
||||
service_name="pos-service",
|
||||
app_name="POS Integration Service",
|
||||
description="Handles integration with external POS systems",
|
||||
version="1.0.0",
|
||||
cors_origins=settings.CORS_ORIGINS,
|
||||
api_prefix="/api/v1",
|
||||
database_manager=database_manager,
|
||||
expected_tables=pos_expected_tables,
|
||||
custom_metrics=pos_custom_metrics
|
||||
)
|
||||
|
||||
async def on_startup(self, app: FastAPI):
|
||||
"""Custom startup logic for POS service"""
|
||||
# Custom startup completed
|
||||
self.logger.info("POS Integration Service started successfully")
|
||||
|
||||
async def on_shutdown(self, app: FastAPI):
|
||||
"""Custom shutdown logic for POS service"""
|
||||
# Database cleanup is handled by the base class
|
||||
pass
|
||||
|
||||
def get_service_features(self):
|
||||
"""Return POS-specific features"""
|
||||
return [
|
||||
"pos_integration",
|
||||
"square_support",
|
||||
"toast_support",
|
||||
"lightspeed_support",
|
||||
"webhook_handling",
|
||||
"transaction_sync",
|
||||
"real_time_updates"
|
||||
]
|
||||
|
||||
def setup_custom_middleware(self):
|
||||
"""Setup custom middleware for POS service"""
|
||||
# Middleware for request logging and timing
|
||||
@self.app.middleware("http")
|
||||
async def log_requests(request: Request, call_next):
|
||||
start_time = time.time()
|
||||
|
||||
# Log request
|
||||
self.logger.info(
|
||||
"Incoming request",
|
||||
method=request.method,
|
||||
url=str(request.url),
|
||||
client_ip=request.client.host if request.client else None
|
||||
)
|
||||
|
||||
response = await call_next(request)
|
||||
|
||||
# Log response
|
||||
process_time = time.time() - start_time
|
||||
self.logger.info(
|
||||
"Request completed",
|
||||
method=request.method,
|
||||
url=str(request.url),
|
||||
status_code=response.status_code,
|
||||
process_time=f"{process_time:.4f}s"
|
||||
)
|
||||
|
||||
response.headers["X-Process-Time"] = str(process_time)
|
||||
return response
|
||||
|
||||
def setup_custom_endpoints(self):
|
||||
"""Setup custom endpoints for POS service"""
|
||||
@self.app.get("/")
|
||||
async def root():
|
||||
"""Root endpoint"""
|
||||
return {
|
||||
"service": "POS Integration Service",
|
||||
"version": "1.0.0",
|
||||
"status": "running",
|
||||
"supported_pos_systems": ["square", "toast", "lightspeed"]
|
||||
}
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
"""Lifecycle management for FastAPI app"""
|
||||
logger.info("Starting POS Integration Service")
|
||||
|
||||
# Startup
|
||||
try:
|
||||
# Initialize database connection
|
||||
logger.info("Initializing database connection")
|
||||
await init_db()
|
||||
|
||||
# Add any startup logic here
|
||||
logger.info("POS Integration Service started successfully")
|
||||
|
||||
yield
|
||||
|
||||
except Exception as e:
|
||||
logger.error("Failed to start POS Integration Service", error=str(e))
|
||||
raise
|
||||
finally:
|
||||
# Shutdown
|
||||
logger.info("Shutting down POS Integration Service")
|
||||
await close_db()
|
||||
# Create service instance
|
||||
service = POSService()
|
||||
|
||||
|
||||
# Create FastAPI app
|
||||
app = FastAPI(
|
||||
title="POS Integration Service",
|
||||
description="Handles integration with external POS systems",
|
||||
version="1.0.0",
|
||||
# Create FastAPI app with standardized setup
|
||||
app = service.create_app(
|
||||
docs_url="/docs" if settings.ENVIRONMENT != "production" else None,
|
||||
redoc_url="/redoc" if settings.ENVIRONMENT != "production" else None,
|
||||
lifespan=lifespan
|
||||
redoc_url="/redoc" if settings.ENVIRONMENT != "production" else None
|
||||
)
|
||||
|
||||
# Add CORS middleware
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=settings.CORS_ORIGINS,
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
# Setup standard endpoints
|
||||
service.setup_standard_endpoints()
|
||||
|
||||
# Setup custom middleware
|
||||
service.setup_custom_middleware()
|
||||
|
||||
# Middleware for request logging and timing
|
||||
@app.middleware("http")
|
||||
async def log_requests(request: Request, call_next):
|
||||
start_time = time.time()
|
||||
|
||||
# Log request
|
||||
logger.info(
|
||||
"Incoming request",
|
||||
method=request.method,
|
||||
url=str(request.url),
|
||||
client_ip=request.client.host if request.client else None
|
||||
)
|
||||
|
||||
response = await call_next(request)
|
||||
|
||||
# Log response
|
||||
process_time = time.time() - start_time
|
||||
logger.info(
|
||||
"Request completed",
|
||||
method=request.method,
|
||||
url=str(request.url),
|
||||
status_code=response.status_code,
|
||||
process_time=f"{process_time:.4f}s"
|
||||
)
|
||||
|
||||
response.headers["X-Process-Time"] = str(process_time)
|
||||
return response
|
||||
|
||||
|
||||
# Global exception handler
|
||||
@app.exception_handler(Exception)
|
||||
async def global_exception_handler(request: Request, exc: Exception):
|
||||
logger.error(
|
||||
"Unhandled exception",
|
||||
error=str(exc),
|
||||
method=request.method,
|
||||
url=str(request.url)
|
||||
)
|
||||
|
||||
return JSONResponse(
|
||||
status_code=500,
|
||||
content={"detail": "Internal server error"}
|
||||
)
|
||||
|
||||
# Setup custom endpoints
|
||||
service.setup_custom_endpoints()
|
||||
|
||||
# Include routers
|
||||
app.include_router(health_router, prefix="/health", tags=["health"])
|
||||
app.include_router(pos_config.router, prefix="/api/v1", tags=["pos-config"])
|
||||
app.include_router(webhooks.router, prefix="/api/v1", tags=["webhooks"])
|
||||
app.include_router(sync.router, prefix="/api/v1", tags=["sync"])
|
||||
|
||||
|
||||
@app.get("/")
|
||||
async def root():
|
||||
"""Root endpoint"""
|
||||
return {
|
||||
"service": "POS Integration Service",
|
||||
"version": "1.0.0",
|
||||
"status": "running",
|
||||
"supported_pos_systems": ["square", "toast", "lightspeed"]
|
||||
}
|
||||
service.add_router(pos_config.router, tags=["pos-config"])
|
||||
service.add_router(webhooks.router, tags=["webhooks"])
|
||||
service.add_router(sync.router, tags=["sync"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
Reference in New Issue
Block a user