Spaces:
Paused

File size: 12,539 Bytes
8eb630b
 
 
 
 
 
 
 
 
 
 
 
0743ddc
 
8eb630b
0743ddc
8eb630b
 
0743ddc
8eb630b
0743ddc
8eb630b
 
 
 
0743ddc
8eb630b
 
 
 
 
 
 
 
 
0743ddc
8eb630b
 
0743ddc
8eb630b
0743ddc
8eb630b
 
 
 
 
 
 
 
 
 
 
0743ddc
8eb630b
 
0743ddc
8eb630b
 
 
0743ddc
8eb630b
 
 
 
 
0743ddc
8eb630b
 
 
 
 
 
0743ddc
c85f9e9
0743ddc
 
 
 
8eb630b
0743ddc
 
 
 
 
 
8eb630b
 
 
 
 
 
0743ddc
8eb630b
 
0743ddc
8eb630b
0743ddc
8eb630b
 
0743ddc
 
 
 
8eb630b
 
 
 
 
0743ddc
8eb630b
 
0743ddc
8eb630b
 
0743ddc
8eb630b
0743ddc
8eb630b
 
 
 
 
 
 
 
0743ddc
8eb630b
 
0743ddc
8eb630b
0743ddc
8eb630b
 
 
 
 
 
 
 
 
0743ddc
8eb630b
 
 
0743ddc
8eb630b
 
 
 
 
0743ddc
8eb630b
0743ddc
8eb630b
0743ddc
8eb630b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0743ddc
8eb630b
0743ddc
8eb630b
0743ddc
8eb630b
 
 
 
 
0743ddc
8eb630b
0743ddc
8eb630b
 
0743ddc
8eb630b
0743ddc
8eb630b
 
0743ddc
 
8eb630b
 
 
 
 
0743ddc
8eb630b
 
0743ddc
 
 
 
 
 
8eb630b
 
 
0743ddc
8eb630b
 
 
 
 
 
 
 
0743ddc
8eb630b
 
 
 
0743ddc
8eb630b
 
0743ddc
579285c
8eb630b
 
 
 
0743ddc
8eb630b
0743ddc
8eb630b
0743ddc
8eb630b
 
 
 
0743ddc
 
8eb630b
 
0743ddc
 
 
 
 
8eb630b
 
 
0743ddc
8eb630b
 
 
 
 
 
 
 
 
 
0743ddc
8eb630b
 
 
 
 
0743ddc
8eb630b
 
0743ddc
8eb630b
 
0743ddc
8eb630b
 
 
0743ddc
8eb630b
 
 
 
 
 
0743ddc
8eb630b
0743ddc
8eb630b
 
 
 
 
 
0743ddc
8eb630b
0743ddc
579285c
0743ddc
8eb630b
 
 
 
 
 
 
0743ddc
 
 
 
 
 
 
 
8eb630b
 
 
0743ddc
8eb630b
 
 
 
 
 
 
 
 
 
 
 
0743ddc
8eb630b
 
 
 
0743ddc
8eb630b
 
0743ddc
8eb630b
 
 
 
 
 
0743ddc
8eb630b
0743ddc
579285c
0743ddc
8eb630b
 
0743ddc
 
8eb630b
 
 
 
0743ddc
8eb630b
 
 
 
 
 
0743ddc
8eb630b
 
 
 
 
0743ddc
8eb630b
 
 
 
 
0743ddc
8eb630b
 
 
 
 
0743ddc
8eb630b
 
 
 
 
0743ddc
8eb630b
 
 
 
 
 
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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
"""
YAZ Care Platform - Standardized API Response Wrapper
State-of-the-Art response patterns with HATEOAS support

Implements best practices from the comprehensive guide:
- Consistent response format across all endpoints
- HATEOAS links for API discoverability
- Detailed metadata for pagination and tracing
- Type-safe response models
"""

from __future__ import annotations

from datetime import UTC, datetime, timezone
from enum import Enum
from typing import Any, Dict, Generic, List, Optional, TypeVar, Union

from fastapi import status
from pydantic import BaseModel, ConfigDict, Field

T = TypeVar("T")


class ResponseStatus(str, Enum):
    """Standard response status values"""

    SUCCESS = "success"
    ERROR = "error"
    PARTIAL = "partial"
    PENDING = "pending"


class PaginationMeta(BaseModel):
    """
    Pagination metadata following REST best practices

    Standards Compliance: REST API Pagination Pattern
    """

    model_config = ConfigDict(frozen=True)

    page: int = Field(..., ge=1, description="Current page number (1-indexed)")
    per_page: int = Field(..., ge=1, le=1000, description="Items per page")
    total: int = Field(..., ge=0, description="Total number of items")
    total_pages: int = Field(..., ge=0, description="Total number of pages")
    has_next: bool = Field(..., description="Whether there is a next page")
    has_prev: bool = Field(..., description="Whether there is a previous page")


class HATEOASLink(BaseModel):
    """
    HATEOAS link for API discoverability

    Standards Compliance: HATEOAS (Hypermedia as the Engine of Application State)
    """

    href: str = Field(..., description="URL to the linked resource")
    rel: str = Field(..., description="Relationship type (self, next, prev, etc.)")
    method: str = Field(default="GET", description="HTTP method for the link")
    title: str | None = Field(None, description="Human-readable link description")


class ResponseMeta(BaseModel):
    """
    Response metadata with observability support

    Includes:
    - Request tracing (request_id, trace_id)
    - Timing information
    - Pagination data
    - HATEOAS links
    """

    model_config = ConfigDict(frozen=True)

    timestamp: datetime = Field(
        default_factory=lambda: datetime.now(UTC), description="Response timestamp (UTC)"
    )
    request_id: str = Field(..., description="Unique request identifier for tracing")
    trace_id: str | None = Field(None, description="Distributed tracing ID (OpenTelemetry)")
    duration_ms: float | None = Field(
        None, ge=0, description="Request processing time in milliseconds"
    )
    pagination: PaginationMeta | None = Field(None, description="Pagination metadata")
    links: list[HATEOASLink] | None = Field(None, description="HATEOAS navigation links")
    api_version: str = Field(default="v1", description="API version")


class ErrorDetail(BaseModel):
    """
    Detailed error information with context

    Standards Compliance: RFC 7807 Problem Details for HTTP APIs
    """

    model_config = ConfigDict(frozen=True)

    code: str = Field(..., description="Machine-readable error code")
    message: str = Field(..., description="Human-readable error message")
    field: str | None = Field(None, description="Field name for validation errors")
    details: dict[str, Any] | None = Field(None, description="Additional error context")
    suggestion: str | None = Field(None, description="How to fix the error")
    documentation_url: str | None = Field(None, description="Link to relevant documentation")


class StandardErrorResponse(BaseModel):
    """
    Standard error response format

    Clinical Context: Clear error communication is critical in healthcare to prevent
    misinterpretation and ensure proper action can be taken.

    Standards Compliance: RFC 7807, FHIR OperationOutcome pattern
    """

    model_config = ConfigDict(frozen=True)

    status: ResponseStatus = Field(default=ResponseStatus.ERROR, description="Response status")
    error: ErrorDetail = Field(..., description="Error details")
    meta: ResponseMeta = Field(..., description="Response metadata")


class StandardSuccessResponse(BaseModel, Generic[T]):
    """
    Standard success response format with generic data type

    Clinical Context: Consistent response structure helps clinical systems
    reliably parse and display data.

    Performance: Target <200ms p95 for all API endpoints

    Example:
        ```python
        response = StandardSuccessResponse(
            status=ResponseStatus.SUCCESS,
            data={"patient_id": "12345", "name": "John Doe"},
            meta=ResponseMeta(request_id="req-abc123")
        )
        ```
    """

    status: ResponseStatus = Field(default=ResponseStatus.SUCCESS, description="Response status")
    data: T = Field(..., description="Response payload")
    meta: ResponseMeta = Field(..., description="Response metadata")
    message: str | None = Field(None, description="Optional success message")


class StandardListResponse(BaseModel, Generic[T]):
    """
    Standard response for list/collection endpoints

    Includes pagination metadata and HATEOAS links automatically.

    Performance: Implements keyset pagination for large datasets (>10K records)

    Example:
        ```python
        response = StandardListResponse(
            status=ResponseStatus.SUCCESS,
            data=[patient1, patient2, patient3],
            meta=ResponseMeta(
                request_id="req-xyz",
                pagination=PaginationMeta(
                    page=1, per_page=20, total=150,
                    total_pages=8, has_next=True, has_prev=False
                )
            )
        )
        ```
    """

    status: ResponseStatus = Field(default=ResponseStatus.SUCCESS, description="Response status")
    data: list[T] = Field(..., description="Array of items")
    meta: ResponseMeta = Field(..., description="Response metadata with pagination")
    message: str | None = Field(None, description="Optional message")


class HealthCheckResponse(BaseModel):
    """
    Standard health check response

    Standards Compliance: Kubernetes liveness/readiness probe pattern

    Performance: Health checks must respond in <50ms
    """

    model_config = ConfigDict(frozen=True)

    status: str = Field(..., description="Overall health status (healthy, degraded, unhealthy)")
    version: str = Field(..., description="Application version")
    timestamp: datetime = Field(default_factory=lambda: datetime.now(UTC))
    checks: dict[str, dict[str, Any]] = Field(..., description="Individual component health")
    uptime_seconds: float = Field(..., ge=0, description="Application uptime")


# Helper functions for creating standardized responses


def success_response(
    data: Any,
    request_id: str | None = None,
    trace_id: str | None = None,
    message: str | None = None,
    links: list[HATEOASLink] | None = None,
    duration_ms: float | None = None,
    api_version: str = "v1",
) -> StandardSuccessResponse:
    """
    Create a standardized success response

    Args:
        data: Response payload
        request_id: Unique request identifier (auto-generated if not provided)
        trace_id: OpenTelemetry trace ID
        message: Optional success message
        links: HATEOAS navigation links
        duration_ms: Request processing time
        api_version: API version

    Returns:
        Standardized success response
    """
    import uuid

    if request_id is None:
        request_id = f"req-{uuid.uuid4().hex[:12]}"

    meta = ResponseMeta(  # type: ignore[call-arg, call-overload, no-redef]
        request_id=request_id,
        trace_id=trace_id,
        duration_ms=duration_ms,
        links=links,
        api_version=api_version,
    )

    return StandardSuccessResponse(
        status=ResponseStatus.SUCCESS, data=data, meta=meta, message=message
    )


def list_response(
    data: list[Any],
    request_id: str | None = None,
    page: int = 1,
    per_page: int = 20,
    total: int | None = None,
    trace_id: str | None = None,
    links: list[HATEOASLink] | None = None,
    duration_ms: float | None = None,
    api_version: str = "v1",
) -> StandardListResponse:
    """
    Create a standardized list/collection response with pagination

    Args:
        data: Array of items
        request_id: Unique request identifier (auto-generated if not provided)
        page: Current page number (default: 1)
        per_page: Items per page (default: 20)
        total: Total number of items (calculated from data if not provided)
        trace_id: OpenTelemetry trace ID
        links: HATEOAS navigation links
        duration_ms: Request processing time
        api_version: API version

    Returns:
        Standardized list response with pagination
    """
    import math
    import uuid

    if request_id is None:
        request_id = f"req-{uuid.uuid4().hex[:12]}"

    if total is None:
        total = len(data)

    total_pages = math.ceil(total / per_page) if per_page > 0 else 0
    has_next = page < total_pages
    has_prev = page > 1

    pagination = PaginationMeta(
        page=page,
        per_page=per_page,
        total=total,
        total_pages=total_pages,
        has_next=has_next,
        has_prev=has_prev,
    )

    meta = ResponseMeta(
        request_id=request_id,
        trace_id=trace_id,
        duration_ms=duration_ms,
        pagination=pagination,
        links=links,
        api_version=api_version,
    )

    return StandardListResponse(  # type: ignore[call-arg, call-overload, no-redef]
        status=ResponseStatus.SUCCESS, data=data, meta=meta
    )


def error_response(
    code: str,
    message: str,
    status_code: int = 400,
    request_id: str | None = None,
    trace_id: str | None = None,
    field: str | None = None,
    details: dict[str, Any] | None = None,
    suggestion: str | None = None,
    documentation_url: str | None = None,
    duration_ms: float | None = None,
    api_version: str = "v1",
) -> StandardErrorResponse:
    """
    Create a standardized error response

    Args:
        code: Machine-readable error code
        message: Human-readable error message
        status_code: HTTP status code (default: 400)
        request_id: Unique request identifier (auto-generated if not provided)
        trace_id: OpenTelemetry trace ID
        field: Field name for validation errors
        details: Additional error context
        suggestion: How to fix the error
        documentation_url: Link to relevant documentation
        duration_ms: Request processing time
        api_version: API version

    Returns:
        Standardized error response
    """
    import uuid

    if request_id is None:
        request_id = f"req-{uuid.uuid4().hex[:12]}"

    error_detail = ErrorDetail(
        code=code,
        message=message,
        field=field,
        details=details,
        suggestion=suggestion,
        documentation_url=documentation_url,
    )

    meta = ResponseMeta(  # type: ignore[call-arg, call-overload, no-redef]
        request_id=request_id, trace_id=trace_id, duration_ms=duration_ms, api_version=api_version
    )

    return StandardErrorResponse(status=ResponseStatus.ERROR, error=error_detail, meta=meta)


# Standard error codes
class ErrorCodes:
    """Standard error codes for YAZ Care Platform"""

    # Authentication & Authorization (1xxx)
    UNAUTHORIZED = "AUTH_1001"
    INVALID_TOKEN = "AUTH_1002"
    TOKEN_EXPIRED = "AUTH_1003"
    INSUFFICIENT_PERMISSIONS = "AUTH_1004"
    MFA_REQUIRED = "AUTH_1005"

    # Validation (2xxx)
    VALIDATION_ERROR = "VAL_2001"
    INVALID_INPUT = "VAL_2002"
    MISSING_REQUIRED_FIELD = "VAL_2003"
    INVALID_FORMAT = "VAL_2004"

    # Resource Management (3xxx)
    RESOURCE_NOT_FOUND = "RES_3001"
    RESOURCE_ALREADY_EXISTS = "RES_3002"
    RESOURCE_CONFLICT = "RES_3003"
    RESOURCE_DELETED = "RES_3004"

    # Multi-Tenancy (4xxx)
    TENANT_NOT_FOUND = "TNT_4001"
    TENANT_ISOLATION_VIOLATION = "TNT_4002"
    TENANT_QUOTA_EXCEEDED = "TNT_4003"
    TENANT_SUSPENDED = "TNT_4004"

    # Clinical Operations (5xxx)
    CLINICAL_VALIDATION_ERROR = "CLN_5001"
    UNSAFE_OPERATION = "CLN_5002"
    PROTOCOL_VIOLATION = "CLN_5003"
    INVALID_CLINICAL_DATA = "CLN_5004"

    # System Errors (9xxx)
    INTERNAL_SERVER_ERROR = "SYS_9001"
    SERVICE_UNAVAILABLE = "SYS_9002"
    DATABASE_ERROR = "SYS_9003"
    EXTERNAL_SERVICE_ERROR = "SYS_9004"
    RATE_LIMIT_EXCEEDED = "SYS_9005"