""" app.py — Flask app factory, registers TraceMiddleware first. Wires together the billing route (stripe_webhook.py, backed by a TenantRegistry — one FrappeClient + scoped StateStore per client, see billing/tenants.py) and the QR code route (qrcode_service.py, stateless and shared across every tenant — no tenant concept applies to it at all), plus Sentry error monitoring and the trace-id middleware every request and log line carries per ENTERPRISE_STANDARDS.md's observability section. """ import logging import os import uuid import sentry_sdk from flask import Flask, g, jsonify from sentry_sdk.integrations.flask import FlaskIntegration from werkzeug.exceptions import HTTPException from billing.billing_status import billing_status_bp from billing.contact_lead import contact_lead_bp from billing.stripe_webhook import stripe_webhook_bp from billing.tenants import TenantRegistry, load_tenants from billing.trial_check import trial_check_bp from qrcode.qrcode_service import qrcode_bp class _TraceIdLogFilter(logging.Filter): """Injects the current request's trace_id into every log record, or '-' outside a request context.""" def filter(self, record): try: record.trace_id = g.trace_id except RuntimeError: record.trace_id = "-" return True def _configure_logging(): """Sets up structured-ish logging (level + trace_id + message) once per process.""" handler = logging.StreamHandler() handler.addFilter(_TraceIdLogFilter()) handler.setFormatter( logging.Formatter("%(asctime)s %(levelname)s trace_id=%(trace_id)s %(name)s: %(message)s") ) root = logging.getLogger() root.setLevel(os.environ.get("LOG_LEVEL", "INFO")) root.addHandler(handler) def _register_trace_middleware(app): """ Registers TraceMiddleware as the first before_request/after_request pair — every other hook and route runs with g.trace_id already set. Steps: 1. before_request: generate a UUID trace_id, attach to g 2. after_request: echo it back as the X-Trace-ID response header """ @app.before_request def _assign_trace_id(): # Step 1: one trace_id per incoming request, available to routes/logs via g g.trace_id = str(uuid.uuid4()) # Tags every Sentry event from this request (not just uncaught-exception # captures) so it can be correlated back to the matching log lines and # the X-Trace-ID header returned to the caller. No-op when Sentry isn't # initialized (SENTRY_DSN unset). sentry_sdk.set_tag("trace_id", g.trace_id) @app.after_request def _add_trace_id_header(response): # Step 2: callers (Stripe, monitoring) can correlate a response back to server-side logs response.headers["X-Trace-ID"] = g.trace_id return response def create_app(): """ Builds and configures the Flask application. Data flow: env vars (TENANTS_CONFIG_PATH, SENTRY_DSN, STATE_STORE_PATH) tenants.json — per-tenant Frappe credentials + Stripe webhook secrets returns (Flask app) Steps: 1. Configure logging and register TraceMiddleware first 2. Initialize Sentry, if SENTRY_DSN is set (tags every event with trace_id/environment, PII excluded) 3. Load every configured tenant into one TenantRegistry for the process 4. Register the stripe_webhook and qrcode blueprints 5. Define GET /health """ _configure_logging() app = Flask(__name__) # Step 1: TraceMiddleware must be registered before anything else touches the request _register_trace_middleware(app) # Step 2: silent failure on a billing action is unacceptable regardless of codebase size. # send_default_pii=False is explicit per ENTERPRISE_STANDARDS.md (PII excluded from # payloads) even though it's also the SDK's own default — this service's requests carry # tenant Frappe credentials and Stripe payloads, neither of which belongs in Sentry. sentry_dsn = os.environ.get("SENTRY_DSN") if sentry_dsn: sentry_sdk.init( dsn=sentry_dsn, integrations=[FlaskIntegration()], environment=os.environ.get("ENVIRONMENT", "production"), send_default_pii=False, ) # Step 3: one shared registry per process — each tenant's FrappeClient (and # its circuit breaker) is constructed lazily on first use and cached from # then on, never re-instantiated per request app.config["TENANT_REGISTRY"] = TenantRegistry(load_tenants()) app.config["STATE_STORE_PATH"] = os.environ.get("STATE_STORE_PATH") # Step 4: the routes this service exposes — Stripe billing (tenant-scoped), # the independent trial-expiry check (tenant-scoped, no Stripe involved), # the read-only billing status lookup (tenant-scoped), QR generation # (tenant-agnostic, stateless), and the marketing site's contact-lead # capture (also tenant-agnostic — it's about the product itself, not # any client's site) are unrelated concerns, kept in separate # blueprints/modules rather than sharing any code beyond the app factory app.register_blueprint(stripe_webhook_bp) app.register_blueprint(trial_check_bp) app.register_blueprint(billing_status_bp) app.register_blueprint(qrcode_bp) app.register_blueprint(contact_lead_bp) # Step 5: reports every configured tenant's Frappe API reachability; # Dokploy gates container promotion on the overall status @app.route("/health", methods=["GET"]) def health(): registry = app.config["TENANT_REGISTRY"] checks = { slug: registry.frappe_client_for(slug).ping() for slug in registry.all_slugs() } all_reachable = all(checks.values()) if checks else True status_code = 200 if all_reachable else 503 return ( jsonify( { "status": "ok" if all_reachable else "degraded", "checks": {"frappe_api": checks}, "trace_id": g.trace_id, } ), status_code, ) @app.errorhandler(Exception) def handle_uncaught_exception(exc): """No raw stack trace in any response — log internally, return a generic message externally.""" if isinstance(exc, HTTPException): # Routing errors (404, 405, ...) keep their normal status/body — only unhandled # application exceptions get folded into a generic 500. return exc logging.getLogger("app").exception("trace_id=%s unhandled exception", g.trace_id) sentry_sdk.capture_exception(exc) return jsonify({"error": "internal server error", "trace_id": g.trace_id}), 500 return app app = create_app()