Spaces:
Paused

File size: 13,569 Bytes
d80907b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e7af6d
d80907b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e7af6d
d80907b
 
 
 
 
 
 
 
 
 
 
 
 
 
2e7af6d
d80907b
579285c
d80907b
 
 
 
 
 
 
 
 
 
 
 
2e7af6d
 
d80907b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e7af6d
d80907b
 
 
 
 
 
 
 
 
 
 
2e7af6d
d80907b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e7af6d
d80907b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e7af6d
d80907b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e7af6d
d80907b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e7af6d
d80907b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
579285c
d80907b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e7af6d
d80907b
 
 
 
 
 
 
 
 
 
2e7af6d
d80907b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e7af6d
d80907b
 
 
 
 
 
2e7af6d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
"""
YAZ Platform — Unified Observability Setup
==========================================
Single function ``configure_observability(app)`` to call once at startup.

Wires together:
  • OpenTelemetry (OTLP exporter → Grafana Cloud / local collector)
  • Prometheus  (``/metrics`` endpoint + FastAPI middleware counters)
  • loguru       (JSON in production, human-readable in development)
  • Sentry SDK   (error tracking + performance traces)

Usage (src/main.py or app factory)
-----------------------------------
    from src.core.observability.setup import configure_observability
    app = FastAPI(...)
    configure_observability(app)

Environment variables read
--------------------------
    YAZ_ENV                         development | testing | production
    OTEL_EXPORTER_OTLP_ENDPOINT     e.g. https://otlp.grafana.net:4318
    OTEL_EXPORTER_OTLP_HEADERS      e.g. Authorization=Basic <token>
    OTEL_SERVICE_NAME               default: yaz-care
    SENTRY_DSN                      Sentry ingestion URL (optional)
    LOG_LEVEL                       DEBUG | INFO | WARNING | ERROR
"""

from __future__ import annotations

import json
import logging
import os
import sys
import time
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from fastapi import FastAPI

logger = logging.getLogger(__name__)


# ── Loguru ─────────────────────────────────────────────────────────────────────


def _configure_loguru(log_level: str = "INFO", json_logs: bool = True) -> None:
    """
    Replace stdlib root logger with loguru.

    In production: newline-delimited JSON (compatible with Loki / Cloud Logging).
    In development: colourful human-readable format.
    """
    try:
        from loguru import logger as _loguru

        # Remove default loguru handler
        _loguru.remove()

        if json_logs:

            def _json_sink(message: object) -> None:
                record = message.record  # type: ignore[attr-defined, union-attr]
                payload = {
                    "ts": record["time"].isoformat(),
                    "level": record["level"].name,
                    "logger": record["name"],
                    "msg": record["message"],
                    "module": record["module"],
                    "line": record["line"],
                }
                if record["exception"]:
                    payload["exc"] = str(record["exception"])
                if record["extra"]:
                    payload["extra"] = {
                        k: v
                        for k, v in record["extra"].items()
                        # Skip PHI-tagged values from log output
                        if k not in {"patient_name", "ssn", "dob", "phi"}
                    }
                sys.stdout.write(json.dumps(payload) + "\n")
                sys.stdout.flush()

            _loguru.add(_json_sink, level=log_level, enqueue=True)
        else:
            _loguru.add(
                sys.stdout,
                level=log_level,
                format=(
                    "<green>{time:HH:mm:ss}</green> | "
                    "<level>{level: <8}</level> | "
                    "<cyan>{name}</cyan>:<cyan>{line}</cyan> — {message}"
                ),
                colorize=True,
                enqueue=True,
            )

        # Bridge stdlib → loguru so third-party libs appear in the same stream
        class _InterceptHandler(logging.Handler):
            def emit(self, record: logging.LogRecord) -> None:
                try:
                    level = _loguru.level(record.levelname).name
                except ValueError:
                    level = str(record.levelno)
                frame, depth = sys._getframe(6), 6
                while frame and frame.f_code.co_filename == logging.__file__:
                    frame = frame.f_back  # type: ignore[assignment]
                    depth += 1
                _loguru.opt(depth=depth, exception=record.exc_info).log(level, record.getMessage())

        logging.basicConfig(handlers=[_InterceptHandler()], level=0, force=True)
        logger.info("loguru configured (json=%s, level=%s)", json_logs, log_level)

    except ImportError:
        logging.basicConfig(level=log_level, stream=sys.stdout)
        logging.warning("loguru not installed — using stdlib logging")


# ── OpenTelemetry ─────────────────────────────────────────────────────────────


def _configure_otel(
    app: "FastAPI",
    service_name: str,
    otlp_endpoint: str,
    otlp_headers: str,
) -> None:
    """
    Instrument FastAPI, asyncpg, Redis, and httpx with OpenTelemetry.
    Exports via OTLP/HTTP to Grafana Cloud (or any OTLP-compatible backend).
    """
    if not otlp_endpoint:
        logger.info("OTEL_EXPORTER_OTLP_ENDPOINT not set — tracing disabled")
        return

    try:
        from opentelemetry import trace
        from opentelemetry.sdk.resources import Resource, SERVICE_NAME
        from opentelemetry.sdk.trace import TracerProvider
        from opentelemetry.sdk.trace.export import BatchSpanProcessor
        from opentelemetry.exporter.otlp.proto.http.trace_exporter import (
            OTLPSpanExporter,
        )
        from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
        from opentelemetry.instrumentation.asyncpg import AsyncPGInstrumentor
        from opentelemetry.instrumentation.redis import RedisInstrumentor
        from opentelemetry.instrumentation.httpx import HTTPXClientInstrumentor

        resource = Resource.create({SERVICE_NAME: service_name})
        provider = TracerProvider(resource=resource)

        headers: dict[str, str] = {}
        if otlp_headers:
            for pair in otlp_headers.split(","):
                pair = pair.strip()
                if "=" in pair:
                    k, _, v = pair.partition("=")
                    headers[k.strip()] = v.strip()

        exporter = OTLPSpanExporter(endpoint=otlp_endpoint, headers=headers)
        provider.add_span_processor(BatchSpanProcessor(exporter))
        trace.set_tracer_provider(provider)

        FastAPIInstrumentor.instrument_app(app)
        AsyncPGInstrumentor().instrument()
        RedisInstrumentor().instrument()
        HTTPXClientInstrumentor().instrument()

        logger.info(
            "OpenTelemetry initialised (service=%s, endpoint=%s)",
            service_name,
            otlp_endpoint,
        )

    except ImportError as exc:
        logger.warning("OpenTelemetry packages missing (%s) — tracing disabled", exc)


# ── Prometheus ────────────────────────────────────────────────────────────────


def _configure_prometheus(app: "FastAPI") -> None:
    """
    Mount Prometheus /metrics endpoint and register HTTP request middleware.
    Reuses (and does NOT re-register) any counters already created by
    src.core.observability.monitoring.MetricsCollector.
    """
    try:
        from prometheus_client import (
            Counter,
            Histogram,
            generate_latest,
            CONTENT_TYPE_LATEST,
            REGISTRY,
        )
        from fastapi import Request, Response
        from fastapi.routing import APIRoute

        # Only register if not already present (avoid duplicate registration)
        existing_names = {m.name for m in REGISTRY.collect()}

        if "yaz_http_requests_total" not in existing_names:
            request_counter = Counter(
                "yaz_http_requests_total",
                "Total HTTP requests",
                ["method", "path", "status"],
            )
        else:
            request_counter = REGISTRY._names_to_collectors.get(
                "yaz_http_requests_total"
            )  # type: ignore[assignment]

        if "yaz_http_request_duration_seconds" not in existing_names:
            request_histogram = Histogram(
                "yaz_http_request_duration_seconds",
                "HTTP request latency in seconds",
                ["method", "path"],
                buckets=[0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0],
            )
        else:
            request_histogram = REGISTRY._names_to_collectors.get(
                "yaz_http_request_duration_seconds"
            )  # type: ignore[assignment]

        @app.middleware("http")
        async def _prometheus_middleware(request: Request, call_next: object) -> Response:
            start = time.perf_counter()
            response: Response = await call_next(request)  # type: ignore[operator]
            duration = time.perf_counter() - start

            # Normalise path to avoid high-cardinality (e.g. /cases/uuid → /cases/{id})
            path = request.url.path
            for route in app.routes:
                if isinstance(route, APIRoute) and route.path_regex.match(path):
                    path = route.path
                    break

            if request_counter:
                request_counter.labels(
                    method=request.method,
                    path=path,
                    status=response.status_code,
                ).inc()
            if request_histogram:
                request_histogram.labels(method=request.method, path=path).observe(duration)

            return response

        @app.get("/metrics", include_in_schema=False)
        async def _metrics() -> Response:
            return Response(
                content=generate_latest(),
                media_type=CONTENT_TYPE_LATEST,
            )

        logger.info("Prometheus /metrics endpoint registered")

    except ImportError as exc:
        logger.warning("prometheus_client missing (%s) — /metrics disabled", exc)


# ── Sentry ────────────────────────────────────────────────────────────────────


def _configure_sentry(dsn: str, environment: str, release: str) -> None:
    """
    Initialise Sentry SDK with FastAPI + SQLAlchemy integrations.
    No-op if SENTRY_DSN is empty.
    """
    if not dsn:
        return

    try:
        import sentry_sdk
        from sentry_sdk.integrations.fastapi import FastApiIntegration
        from sentry_sdk.integrations.sqlalchemy import SqlalchemyIntegration
        from sentry_sdk.integrations.logging import LoggingIntegration
        from sentry_sdk.integrations.redis import RedisIntegration

        sentry_sdk.init(
            dsn=dsn,
            environment=environment,
            release=release,
            traces_sample_rate=0.1 if environment == "production" else 1.0,
            profiles_sample_rate=0.05,
            integrations=[
                FastApiIntegration(transaction_style="url"),
                SqlalchemyIntegration(),
                RedisIntegration(),
                LoggingIntegration(level=logging.WARNING, event_level=logging.ERROR),
            ],
            # Never send PHI to Sentry
            before_send=_sentry_scrub_phi,  # type: ignore[arg-type, assignment]
        )
        logger.info("Sentry initialised (env=%s)", environment)

    except ImportError as exc:
        logger.warning("sentry-sdk missing (%s) — error tracking disabled", exc)


def _sentry_scrub_phi(event: dict, hint: object) -> dict | None:
    """
    Strip known PHI fields from Sentry events before transmission.
    Returns None to drop the event entirely if it contains raw PHI.
    """
    _phi_keys = {"patient_name", "ssn", "birth_date", "dob", "phone", "address"}

    def _scrub(obj: object) -> object:
        if isinstance(obj, dict):
            return {
                k: "[redacted]" if k.lower() in _phi_keys else _scrub(v) for k, v in obj.items()
            }
        if isinstance(obj, list):
            return [_scrub(item) for item in obj]
        return obj

    return _scrub(event)  # type: ignore[return-value]


# ── Public API ─────────────────────────────────────────────────────────────────


def configure_observability(app: "FastAPI") -> None:
    """
    One-call setup for the full observability stack.
    Call this once after ``FastAPI()`` is instantiated, before any routes are
    registered (so OTEL instrumentation wraps all endpoints).

    Args:
        app: The FastAPI application instance.
    """
    env = os.getenv("YAZ_ENV", "production")
    is_prod = env == "production"

    log_level = os.getenv("LOG_LEVEL", "INFO").upper()
    _configure_loguru(log_level=log_level, json_logs=is_prod)

    _configure_otel(
        app=app,
        service_name=os.getenv("OTEL_SERVICE_NAME", "yaz-care"),
        otlp_endpoint=os.getenv("OTEL_EXPORTER_OTLP_ENDPOINT", ""),
        otlp_headers=os.getenv("OTEL_EXPORTER_OTLP_HEADERS", ""),
    )

    _configure_prometheus(app)

    from src.__version__ import __version__ as _version  # type: ignore[import]

    _configure_sentry(
        dsn=os.getenv("SENTRY_DSN", ""),
        environment=env,
        release=_version,
    )

    logger.info("Observability stack configured (env=%s, log_level=%s)", env, log_level)