diff --git a/.github/AI_CODER_INSTRUCTIONS.md b/.github/AI_CODER_INSTRUCTIONS.md deleted file mode 100644 index 890b708ec67d5578c89c94bdcd5800fa0ee9ccfc..0000000000000000000000000000000000000000 --- a/.github/AI_CODER_INSTRUCTIONS.md +++ /dev/null @@ -1,998 +0,0 @@ -# YAZ Care Platform - AI Coder Instructions v7.0.0 - -**Version**: 7.0.0 (Intelligence Platform Edition) -**Date**: March 6, 2026 -**Sprint**: 41 of 52 -**Status**: βœ… PRODUCTION - Multi-Domain Intelligence Platform - -> **🎯 v7.0.0 UPGRADE**: This document extends v5.3.0 with **Domain Engines**, **Intelligence Packaging**, -> and **Multi-Domain Architecture** β€” the foundational concepts that make YAZ a universal platform: -> -> | Concept | Description | -> |---------|-------------| -> | **Domain Engines** | Specialized subsystems per professional field (Surgio, Movio, Banko…) | -> | **Intelligences** | Packaged expertise modules created by professionals | -> | **24 Pillars** | Domain-agnostic primitives that all engines compose | -> | **Marketplace** | Discover, install, fork, and monetise intelligence modules | -> | **Dual Licensing** | Open (AGPL-3.0) for learners/NGOs, Licensed for commercial | - ---- - -## πŸš€ Quick Start - -**Before coding, verify you understand:** -1. The 9 Commandments β†’ [COMMANDMENTS.md](../docs/COMMANDMENTS.md) - **NON-NEGOTIABLE** -2. DDD Standards β†’ [DDD_STANDARDS.md](../docs/architecture/DDD_STANDARDS.md) -3. Domain Engines β†’ [DOMAIN_ENGINES.md](../docs/architecture/DOMAIN_ENGINES.md) -4. Intelligence Packaging β†’ [INTELLIGENCE_PACKAGING.md](../docs/architecture/INTELLIGENCE_PACKAGING.md) -5. The Four Pillars Architecture β†’ This document (Part 9) -6. Governance hierarchy and case management patterns - ---- - -## πŸ”’ PUBLIC vs INTERNAL Visibility Rules - -### ⚠️ CRITICAL: User-Facing Exposure Rules - -| Layer | PUBLIC (User-Visible) | INTERNAL (Backend Only) | -|-------|----------------------|------------------------| -| **Operating Companies** | βœ… YAZ, AYRAD, AZUL, EFRI, LUIZ | ❌ Never expose parent entities | -| **Products/Apps** | βœ… Surgio, Clinica, Labo, Pharma, etc. | ❌ Governance structure | -| **Tenants** | βœ… Hospital names, clinic names | ❌ Tenant IDs in URLs | -| **Legal Entities** | ❌ NEVER in UI/docs/web | βœ… Database & admin only | - -### What Users See vs What Backend Uses - -``` -USER-FACING (Web, Docs, UI): -β”œβ”€β”€ YAZ Care Platform (brand) -β”œβ”€β”€ Apps: Surgio, Clinica, Labo, Pharma, Hospi... -β”œβ”€β”€ Tenant: "Hospital ABC", "Clinic XYZ" -└── Features: Cases, Reports, Analytics - -BACKEND-ONLY (Database, Admin, Internal): -β”œβ”€β”€ LegalEntity (governance layer - NEVER expose) -β”œβ”€β”€ System (operational config) -β”œβ”€β”€ Contract (licensing agreements) -└── SLAMetric (performance tracking) -``` - -### βœ… DO: User-Facing Content -```html - -

YAZ Care Platform

-

Powered by AYRAD Intelligence

- - - -``` - -### ❌ DON'T: Never Expose Governance -```html - - - - - -Licensed by YEMA Holding -``` - ---- - -## πŸ“Š Part 1: Internal Governance Architecture - -> **πŸ”’ INTERNAL ONLY**: This section is for backend developers. -> Never expose these concepts in user-facing UI, documentation, or APIs. - -### Governance Hierarchy (DATABASE ONLY) - -The platform implements a 4-tier governance hierarchy stored in database: - -``` -[INTERNAL - Database Schema: governance] -LegalEntity (parent_trust) - └─→ LegalEntity (holding_company) - └─→ LegalEntity (foundation) - └─→ System (yaz, ayrad, azul, efri, luiz) - └─→ Tenant (hospital-a, clinic-b) - └─→ Users & Cases -``` - -### Internal Database Models - -| Model | Location | Visibility | -|-------|----------|------------| -| `LegalEntity` | [src/core/database/governance.py](../src/core/database/governance.py) | πŸ”’ Admin API only | -| `LegalEntityKind` | [src/core/database/governance.py](../src/core/database/governance.py) | πŸ”’ Internal enum | -| `System` | [src/core/database/governance.py](../src/core/database/governance.py) | ⚠️ Brand names public | -| `Contract` | [src/core/governance/contracts.py](../src/core/governance/contracts.py) | πŸ”’ Internal only | - -### LegalEntityKind Enum (INTERNAL) - -```python -# src/core/database/governance.py - INTERNAL USE ONLY -class LegalEntityKind(str, Enum): - """ - πŸ”’ INTERNAL: Types of legal entities in governance hierarchy. - Never expose kind names or hierarchy to users. - """ - TRUST = "trust" # Parent asset protection - HOLDING_FOR_PROFIT = "holding_for_profit" # Commercial licensing - FOUNDATION_NON_PROFIT = "foundation_non_profit" # OSS stewardship -``` - -### SystemType Enum (PARTIALLY PUBLIC) - -```python -# src/core/database/governance.py -class SystemType(str, Enum): - """ - System types - Brand names (YAZ, AYRAD) are PUBLIC. - Internal classification is PRIVATE. - """ - SOFTWARE_VENDOR = "software_vendor" # YAZ Care Platform (PUBLIC brand) - OPERATOR = "operator" # AYRAD Intelligence (PUBLIC brand) - SERVICE_PROVIDER = "service_provider" # AZUL (PUBLIC brand) - RESEARCH_ENTITY = "research_entity" # Research partners -``` - -### Contract Model (INTERNAL ONLY) - -```python -# src/core/governance/contracts.py - ADMIN ACCESS ONLY -class Contract(SQLModel, table=True): - """ - πŸ”’ INTERNAL: Contracts between legal entities. - Never expose contract details to regular users. - """ - __tablename__ = "contracts" - __table_args__ = {"schema": "governance"} - - id: UUID = Field(default_factory=uuid4, primary_key=True) - contract_type: ContractType - licensor_id: UUID - licensee_id: UUID - effective_date: datetime - expiration_date: datetime - sla_metrics: List[SLAMetric] -``` - ---- - -## πŸ“‹ Part 2: Domain-Agnostic Case Management - -### Universal Vocabulary (EXISTING) - -All case types across YAZ tools share a common vocabulary. **These enums exist**: - -| Enum | Location | Purpose | -|------|----------|---------| -| `CaseStatus` | [src/core/domain/cases.py](../src/core/domain/cases.py) | DRAFT β†’ ARCHIVED lifecycle | -| `CaseType` | [src/core/domain/cases.py](../src/core/domain/cases.py) | SURGICAL, CLINICAL, LABORATORY, etc. | -| `CasePriority` | [src/core/domain/cases.py](../src/core/domain/cases.py) | ROUTINE β†’ STAT | -| `InteractionType` | [src/core/domain/cases.py](../src/core/domain/cases.py) | VIEW, EDIT, COMMENT, etc. | - -### CaseStatus Enum (EXISTING) - -```python -# src/core/domain/cases.py (Lines 38-65) -class CaseStatus(str, Enum): - """ - Universal case status across all YAZ tools. - - Workflow: DRAFT β†’ PENDING β†’ ACTIVE β†’ ON_HOLD β†’ COMPLETED β†’ ARCHIVED - Terminal states: CANCELLED, ARCHIVED - """ - DRAFT = "draft" # Initial creation - PENDING = "pending" # Awaiting approval/action - ACTIVE = "active" # In progress - ON_HOLD = "on_hold" # Temporarily paused - COMPLETED = "completed" # Successfully finished - CANCELLED = "cancelled" # Terminated early - ARCHIVED = "archived" # Stored for records -``` - -### CaseType Enum (EXISTING) - -```python -# src/core/domain/cases.py (Lines 67-95) -class CaseType(str, Enum): - """ - Domain-specific case types mapping to YAZ tools. - """ - SURGICAL = "surgical" # Surgio - CLINICAL = "clinical" # Clinica - LABORATORY = "laboratory" # Labo - PHARMACEUTICAL = "pharmaceutical" # Pharma - ADMINISTRATIVE = "administrative" # Hospi - FINANCIAL = "financial" # Banko, Insura - EDUCATIONAL = "educational" # Educa, Trena - LOGISTICS = "logistics" # Movio, Stoka - FIELD = "field" # Campo - ACCOMMODATION = "accommodation" # Lodger - MANUFACTURING = "manufacturing" # Fabrica -``` - -### CasePriority Enum (EXISTING) - -```python -# src/core/domain/cases.py (Lines 97-115) -class CasePriority(str, Enum): - """ - Universal priority levels for clinical urgency. - """ - ROUTINE = "routine" # Standard processing - URGENT = "urgent" # Elevated priority - STAT = "stat" # Immediate action required - CRITICAL = "critical" # Life-threatening emergency -``` - -### BaseCase Aggregate Root (EXISTING) - -```python -# src/core/domain/cases.py (Lines 222-350) -@dataclass -class BaseCase(ABC): - """ - Abstract base case aggregate root. - All domain-specific cases should extend this. - - Provides: - - Universal case lifecycle management - - Cross-tool case linking - - Interaction tracking - - Event publishing - """ - id: UUID = field(default_factory=uuid4) - tenant_id: str = "" - case_type: CaseType = CaseType.CLINICAL - case_number: str = "" - status: CaseStatus = CaseStatus.DRAFT - priority: CasePriority = CasePriority.ROUTINE - subject_id: Optional[UUID] = None - owner_id: str = "" - linked_cases: List[CaseLink] = field(default_factory=list) - _uncommitted_events: List[DomainEvent] = field(default_factory=list) -``` - -### Domain Events (EXISTING) - -```python -# src/core/domain/cases.py (Lines 130-200) -@dataclass(frozen=True) -class CaseCreatedEvent(DomainEvent): - """Emitted when a new case is created""" - event_type: str = "case.created" - case_id: str = "" - case_type: str = "" - subject_id: str = "" - -@dataclass(frozen=True) -class CaseStatusChangedEvent(DomainEvent): - """Emitted when case status changes""" - event_type: str = "case.status_changed" - case_id: str = "" - old_status: str = "" - new_status: str = "" - changed_by: str = "" - reason: str = "" -``` - -### Cross-Domain Case API (EXISTING) - -The platform has a unified case API for cross-tool interactions: - -```python -# src/core/api/cases.py (507 lines) -# Provides: -# - GET /api/v1/cases/search - Cross-domain case search -# - POST /api/v1/cases/link - Link cases across tools -# - POST /api/v1/cases/interaction - Record case interactions -# - POST /api/v1/cases/status - Change case status -# - POST /api/v1/cases/assign - Assign cases -# - POST /api/v1/cases/escalate - Escalate priority -``` - ---- - -## πŸ—οΈ Part 3: Engine Architecture & Registry - -> **Key Principle**: Surgio, Clinica, Labo, etc. are **domain engines** β€” specialized subsystems -> encapsulating professional intelligence. Each engine implements the `DomainEngine` ABC -> and composes platform pillars. Any professional can create their own domain engine -> to solve cases in any field and commercialise them via the Marketplace. - -### Tool Registration (EXISTING) - -All tools are registered in [src/apps_routes.py](../src/apps_routes.py): - -```python -# src/apps_routes.py (Lines 10-120) -APPS = { - "surgio": {"name": "Surgio", "icon": "scissors", ...}, - "clinica": {"name": "Clinica", "icon": "clipboard-list", ...}, - "labo": {"name": "Labo", "icon": "flask-conical", ...}, - "pharma": {"name": "Pharma", "icon": "pill", ...}, - "hospi": {"name": "Hospi", "icon": "building-2", ...}, - "medio": {"name": "Medio", "icon": "heart-pulse", ...}, - "educa": {"name": "Educa", "icon": "book-open", ...}, - "insura": {"name": "Insura", "icon": "shield-check", ...}, - "movio": {"name": "Movio", "icon": "package", ...}, - "stoka": {"name": "Stoka", "icon": "layers", ...}, - "campo": {"name": "Campo", "icon": "map-pin", ...}, - "banko": {"name": "Banko", "icon": "wallet", ...}, - "lodger": {"name": "Lodger", "icon": "home", ...}, - "fabrica": {"name": "Fabrica", "icon": "cog", ...}, - "trena": {"name": "Trena", "icon": "graduation-cap", ...}, - "security": {"name": "Security", "icon": "shield-check", ...}, -} -``` - -### Tool Directory Structure - -Each tool follows this standard structure: - -``` -src/apps/{tool_slug}/ -β”œβ”€β”€ __init__.py # Package init, exports -β”œβ”€β”€ models.py # SQLModel domain models -β”œβ”€β”€ schemas.py # Pydantic V2 request/response -β”œβ”€β”€ routes.py # FastAPI routes (or router.py) -β”œβ”€β”€ services/ # Business logic layer -β”‚ β”œβ”€β”€ __init__.py -β”‚ └── {app}_service.py -└── tests/ - └── test_{app}.py -``` - -### Template Structure - -``` -src/ui/templates/ -β”œβ”€β”€ shared/ -β”‚ β”œβ”€β”€ base.html # Base template with nav -β”‚ └── app_base.html # App-specific base -β”œβ”€β”€ apps/ -β”‚ β”œβ”€β”€ surgio.html # Simple app dashboard -β”‚ β”œβ”€β”€ clinica.html -β”‚ └── ... (per-app templates) -β”œβ”€β”€ {app_slug}/ -β”‚ β”œβ”€β”€ dashboard.html # Rich dashboard -β”‚ β”œβ”€β”€ list.html # Entity list view -β”‚ β”œβ”€β”€ detail.html # Entity detail view -β”‚ └── new.html # Create form -└── cases/ - β”œβ”€β”€ dashboard.html # Cross-domain case view - β”œβ”€β”€ list.html # Case list - └── detail.html # Case detail -``` - ---- - -## 🎨 Part 4: UI/UX Patterns - -### Dashboard Template Pattern (EXISTING) - -All app dashboards follow this structure: - -```html - -{% extends "shared/app_base.html" %} - -{% set app_config = { - 'slug': 'surgio', - 'name': 'Surgio', - 'icon': 'scissors', - 'gradient_from': '#7c8ab8', - 'gradient_to': '#9b7cb8' -} %} - -{% block dashboard_content %} - -
- {% include "shared/components/stat_card.html" %} -
- - -
- - - New Case - - - - View All - -
- - -
- -
-{% endblock %} -``` - -### Color Palette (v2.0 Minimalist) - -```css -/* src/ui/static/css/theme.css */ -:root { - /* Light Mode */ - --bg: #f8f9fa; - --surface: #ffffff; - --border: #e5e7eb; - --text: #1f2937; - --text-muted: #6b7280; - - --primary: #5c6bc0; - --primary-hover: #4a5ab8; - --success: #56a066; - --warning: #c2883b; - --error: #c74b4b; -} - -[data-theme="dark"] { - --bg: #111827; - --surface: #1f2937; - --border: #374151; - --text: #f9fafb; - --text-muted: #9ca3af; - - --primary: #7c8aca; - --primary-hover: #8b97d1; -} -``` - -### HTMX Patterns (EXISTING) - -```html - - - - -
-
-
- - -
- -
-``` - ---- - -## πŸ” Part 5: Security & Multi-Tenancy - -### Tenant Isolation (MANDATORY) - -**Every query MUST filter by tenant_id first**: - -```python -# βœ… CORRECT - Always filter by tenant_id -from sqlalchemy import select - -query = select(SurgeryCase).where( - SurgeryCase.tenant_id == tenant_id, # MANDATORY FIRST - SurgeryCase.status == 'active' -) - -# ❌ WRONG - No tenant filter = SECURITY BREACH -query = select(SurgeryCase) # Returns ALL tenants' data! -``` - -### RBAC System (EXISTING) - -```python -# src/core/security/rbac.py -from core.security.rbac import require_permission, Permission - -@router.get("/cases/{case_id}") -@require_permission(Permission("surgio", "read", "cases")) -async def get_case( - case_id: UUID, - current_user: User = Depends(get_current_user), - tenant_id: UUID = Depends(verify_tenant_access) -): - """Get case with RBAC enforcement""" - pass -``` - -### Audit Logging (EXISTING) - -```python -# src/core/security/audit.py -from core.security.audit import audit_log - -@audit_log( - action="case.viewed", - resource_type="surgical_case", - phi_access=True # Marks PHI access for HIPAA -) -async def get_case_details(case_id: UUID): - pass -``` - ---- - -## πŸ“Š Part 6: Performance Standards - -### SLA Targets (EXISTING) - -| Operation | Target | Enforcement | -|-----------|--------|-------------| -| API Response (p95) | <200ms | Prometheus alert | -| List Operations | <100ms | Indexed queries | -| Algorithm Execution | <50ms | Caching | -| Cache Hit Rate | >90% | 4-tier strategy | -| WebSocket Latency | <20ms | Connection pooling | - -### 4-Tier Caching (EXISTING) - -```python -# src/core/cache/strategy.py -CACHE_TIERS = { - "request": {"ttl": 5, "scope": "in-memory"}, # functools.lru_cache - "session": {"ttl": 60, "scope": "redis"}, # User session data - "tenant": {"ttl": 3600, "scope": "redis"}, # Tenant config - "global": {"ttl": 86400, "scope": "redis"} # Reference data -} -``` - -### Query Optimization (MANDATORY) - -```python -# βœ… GOOD - Indexed, specific columns, eager loading -from sqlalchemy.orm import selectinload - -query = select(SurgeryCase.id, SurgeryCase.case_number, SurgeryCase.status).where( - SurgeryCase.tenant_id == tenant_id # Uses index -).options( - selectinload(SurgeryCase.team_members) # Prevent N+1 -).order_by( - SurgeryCase.created_at.desc() -).limit(50) - -# ❌ BAD - SELECT *, no index, N+1 queries -query = select(SurgeryCase) # Loads all columns -for case in cases: - case.team_members # N+1 query! -``` - ---- - -## πŸ§ͺ Part 7: Testing Standards - -### Coverage Requirements - -| Type | Target | Location | -|------|--------|----------| -| Unit Tests | 85%+ | `tests/unit/` | -| Integration Tests | All APIs | `tests/integration/` | -| Isolation Tests | 15 mandatory | `tests/isolation/` | -| Performance Tests | SLA validation | `tests/performance/` | - -### Test Pattern (EXISTING) - -```python -# tests/apps/surgio/test_case_service.py -import pytest -from uuid import uuid4 - -@pytest.mark.asyncio -async def test_case_creation_with_tenant(): - """Unit test for case creation""" - tenant_id = uuid4() - case = await case_service.create( - data=CaseCreate(procedure_name="Total Knee Replacement"), - tenant_id=tenant_id, - user_id=uuid4() - ) - assert case.tenant_id == tenant_id - assert case.status == CaseStatus.DRAFT - - -@pytest.mark.isolation -async def test_tenant_isolation(): - """MANDATORY: Verify tenant isolation""" - tenant_a = uuid4() - tenant_b = uuid4() - - case = await case_service.create(data, tenant_a, user_id) - - # Tenant B cannot access Tenant A's case - result = await case_service.get(case.id, tenant_b) - assert result is None - - -@pytest.mark.performance -async def test_case_creation_sla(): - """Verify <200ms SLA""" - import time - - start = time.time() - await case_service.create(data, tenant_id, user_id) - duration_ms = (time.time() - start) * 1000 - - assert duration_ms < 200, f"SLA violation: {duration_ms}ms" -``` - ---- - -## πŸ› οΈ Part 8: Development Workflow - -### 1. Creating a New Tool - -```bash -# Use the generator script -python scripts/generators/create_app.py \ - --name newtool \ - --display-name "New Tool" \ - --category clinical \ - --standards "HL7 FHIR" - -# Creates: -# src/apps/newapp/ -# β”œβ”€β”€ __init__.py -# β”œβ”€β”€ models.py -# β”œβ”€β”€ schemas.py -# β”œβ”€β”€ routes.py -# └── services/ -# src/ui/templates/newapp/ -# └── dashboard.html -``` - -### 2. Creating a New Entity - -Follow the 5-phase workflow in [CODEBASE_CREATION_LOGIC.md](../docs/architecture/CODEBASE_CREATION_LOGIC.md): - -1. **Domain Model** (`models.py`) -2. **API Schemas** (`schemas.py`) -3. **Business Logic** (`services/`) -4. **Routes** (`routes.py`) -5. **Tests** (`tests/`) - -### 3. Running the Platform - -```bash -# Development with hot reload -python main.py serve --debug --port 8000 - -# Or use the VS Code task -# Tasks: Run Task β†’ "Start Dev Server (Hot Reload)" - -# Tests -pytest tests/ -v --cov=src --cov-fail-under=85 - -# Type checking -mypy src/ - -# Formatting -black src/ tests/ && isort src/ tests/ -``` - ---- - -## πŸ“š Related Documentation - -| Document | Purpose | Location | -|----------|---------|----------| -| **COMMANDMENTS** | 7 unbreakable rules | [docs/COMMANDMENTS.md](../docs/COMMANDMENTS.md) | -| **PRACTICES** | Best practices guide | [docs/PRACTICES.md](../docs/PRACTICES.md) | -| **DDD_STANDARDS** | Domain patterns | [docs/architecture/DDD_STANDARDS.md](../docs/architecture/DDD_STANDARDS.md) | -| **ACCESS_SECURITY** | RBAC, audit, secrets | [docs/architecture/ACCESS_SECURITY.md](../docs/architecture/ACCESS_SECURITY.md) | -| **TARGET** | Technology roadmap | [docs/TARGET.md](../docs/TARGET.md) | -| **UI_UX_SYSTEM** | Design system v2.0 | [docs/architecture/UI_UX_SYSTEM.md](../docs/architecture/UI_UX_SYSTEM.md) | - ---- - -## βœ… AI Assistant Checklist - -Before submitting code, verify: - -### Code Quality -- [ ] All type hints present (100% coverage) -- [ ] Docstrings with clinical context -- [ ] Tests written (85%+ coverage) -- [ ] No mypy errors - -### Security -- [ ] tenant_id filter on every query -- [ ] No PHI in logs -- [ ] RBAC decorators applied -- [ ] Audit logging for sensitive ops - -### Performance -- [ ] Queries use indexes -- [ ] No N+1 queries (use selectinload) -- [ ] Caching for expensive operations -- [ ] <200ms SLA validated - -### Standards -- [ ] Follows DDD patterns -- [ ] Uses existing enums (CaseStatus, CaseType) -- [ ] Extends base classes (BaseCase, BaseService) -- [ ] Events raised for state changes - ---- - -**Last Updated**: February 05, 2026 -**Maintainer**: YAZ Care Development Team -**Status**: βœ… v5.3.0 - Production Ready with Four Pillars Architecture - ---- - -## πŸ—οΈ Part 9: The Four Pillars Architecture (v5.3.0) - -> **CRITICAL**: These are **architectural instructions**, not code examples. They define how to design, -> implement, test, deploy, and maintain the foundational services. - -### Core Philosophy - -- Services are **primitives**, not features -- Domain packs **compose** services, not implement them -- Everything is **configurable** via schemas -- Everything is **auditable** via events -- Everything is **extensible** without core changes - -### Architecture Overview - -``` -β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” -β”‚ DOMAIN PACK LAYER β”‚ -β”‚ (Healthcare, Logistics, Insurance, Manufacturing, Education...) β”‚ -β”‚ β”‚ -β”‚ Domain Packs DO: β”‚ -β”‚ - Define schemas (checklist templates, journal entry types) β”‚ -β”‚ - Configure monitors (vital signs, inventory levels) β”‚ -β”‚ - Define protocol workflows (surgical pathways, shipping routes) β”‚ -β”‚ - Provide UI templates and visualizations β”‚ -β”‚ β”‚ -β”‚ Domain Packs DO NOT: β”‚ -β”‚ - Implement core service logic β”‚ -β”‚ - Manage multi-tenancy β”‚ -β”‚ - Handle event sourcing β”‚ -β”‚ - Control access permissions β”‚ -β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ - β”‚ - β–Ό -β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” -β”‚ CORE SERVICE LAYER (The 4 Pillars) β”‚ -β”‚ β”‚ -β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ -β”‚ β”‚ CHECKLIST β”‚ β”‚ JOURNAL β”‚ β”‚ MONITOR β”‚ β”‚PROTOCOLβ”‚ β”‚ -β”‚ β”‚ SERVICE β”‚ β”‚ SERVICE β”‚ β”‚ SERVICE β”‚ β”‚WORKFLOWβ”‚ β”‚ -β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚SERVICE β”‚ β”‚ -β”‚ β”‚ - Templates β”‚ β”‚ - Streams β”‚ β”‚ - Defs β”‚ β”‚ - Defs β”‚ β”‚ -β”‚ β”‚ - Instances β”‚ β”‚ - Entries β”‚ β”‚ - Instances β”‚ β”‚ - Runs β”‚ β”‚ -β”‚ β”‚ - Responses β”‚ β”‚ - Amendments β”‚ β”‚ - Alerts β”‚ β”‚ - Stepsβ”‚ β”‚ -β”‚ β”‚ - Validation β”‚ β”‚ - Signatures β”‚ β”‚ - Trends β”‚ β”‚ - Transβ”‚ β”‚ -β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ -β”‚ β”‚ -β”‚ All services share: β”‚ -β”‚ - Event sourcing pattern β”‚ -β”‚ - Hash chain integrity β”‚ -β”‚ - Multi-tenant isolation β”‚ -β”‚ - RBAC enforcement β”‚ -β”‚ - Metrics & tracing β”‚ -β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ - β”‚ - β–Ό -β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” -β”‚ INFRASTRUCTURE LAYER β”‚ -β”‚ β”‚ -β”‚ - Event Store (append-only, hash-chained) β”‚ -β”‚ - Parameter Store (versioned, audited) β”‚ -β”‚ - Evidence Store (immutable attachments) β”‚ -β”‚ - Audit Log (compliance, forensics) β”‚ -β”‚ - Notification Bus (real-time alerts) β”‚ -β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ -``` - -### Pillar 1: Checklist Service - -**Purpose**: Structured, sequential task completion with validation. - -**Core Entities**: -| Entity | Purpose | Storage | -|--------|---------|---------| -| `ChecklistTemplate` | Reusable blueprint | `checklist.templates` | -| `ChecklistInstance` | Active execution | `checklist.instances` | -| `ChecklistItemResponse` | User responses | `checklist.responses` | - -**Input Types**: `boolean`, `text_input`, `numeric_input`, `choice`, `multi_choice`, -`signature`, `photo`, `barcode`, `measurement`, `timestamp`, `calculated` - -**API Endpoints**: -``` -POST /api/v1/checklists/templates -GET /api/v1/checklists/templates/{id} -POST /api/v1/checklists/instances -POST /api/v1/checklists/instances/{id}/respond -POST /api/v1/checklists/instances/{id}/complete -``` - -**Domain Pack Example** (Surgical Care): -```python -WHO_SSC_TEMPLATE = { - "name": "WHO Surgical Safety Checklist 2.0", - "version": "2.0.0", - "domain": "surgical_care", - "items": [ - {"item_id": "confirm_patient", "type": "boolean", "required": True}, - {"item_id": "site_marked", "type": "choice", "required": True} - ] -} -``` - -### Pillar 2: Journal Service - -**Purpose**: Chronological, append-only documentation with amendments. - -**Core Entities**: -| Entity | Purpose | Storage | -|--------|---------|---------| -| `JournalStream` | Container for entries | `journal.streams` | -| `JournalEntry` | Immutable record | `journal.entries` | -| `Amendment` | Entry corrections | `journal.amendments` | - -**Entry Types**: `narrative`, `observation`, `assessment`, `plan`, `procedure_note`, -`progress_note`, `incident`, `handoff`, `communication` - -**Key Feature**: Hash chain integrity (each entry includes prev_hash) - -**API Endpoints**: -``` -POST /api/v1/journal/streams -POST /api/v1/journal/streams/{id}/entries -POST /api/v1/journal/entries/{id}/amend -POST /api/v1/journal/entries/{id}/sign -GET /api/v1/journal/search -POST /api/v1/journal/streams/{id}/export -``` - -### Pillar 3: Monitor Service - -**Purpose**: Continuous parameter surveillance with alerting. - -**Monitor Types**: -| Type | Description | Use Case | -|------|-------------|----------| -| `threshold` | Value crosses limit | HR > 120 bpm | -| `range` | Value outside bounds | BP 90-140 mmHg | -| `trend` | Rate of change | Temp rising 0.5Β°C/hr | -| `composite` | Multiple parameters | SIRS criteria | -| `statistical` | Westgard QC rules | Lab QC | -| `heartbeat` | Missing signal | Device offline | - -**Core Entities**: -| Entity | Purpose | Storage | -|--------|---------|---------| -| `MonitorDefinition` | Reusable blueprint | `monitor.definitions` | -| `MonitorInstance` | Active monitor | `monitor.instances` | -| `Alert` | Triggered notification | `monitor.alerts` | - -**API Endpoints**: -``` -POST /api/v1/monitors/definitions -POST /api/v1/monitors/instances -POST /api/v1/monitors/instances/{id}/evaluate -POST /api/v1/monitors/alerts/{id}/acknowledge -POST /api/v1/monitors/alerts/{id}/resolve -``` - -### Pillar 4: Protocol Workflow Service - -**Purpose**: Multi-step coordinated processes with state machine execution. - -**Core Concepts**: -- **States**: Discrete phases (pre-op, timeout, incision, closure) -- **Transitions**: How to move between states -- **Guards**: Conditions that must be met (checklist complete) -- **Actions**: What happens on transition (notify team) -- **Timeouts**: Max time in state before alert - -**Core Entities**: -| Entity | Purpose | Storage | -|--------|---------|---------| -| `ProtocolDefinition` | State machine blueprint | `protocol.definitions` | -| `ProtocolRun` | Active execution | `protocol.runs` | -| `StateTransition` | Transition record | `protocol.state_transitions` | - -**Guard Types**: `checklist_complete`, `parameter_value`, `journal_entry_exists`, -`time_elapsed`, `alert_resolved`, `user_role` - -**Action Types**: `initiate_checklist`, `create_journal_entry`, `start_monitor`, -`stop_monitor`, `notify`, `set_variable` - -**API Endpoints**: -``` -POST /api/v1/protocols/definitions -POST /api/v1/protocols/runs -POST /api/v1/protocols/runs/{id}/transition -POST /api/v1/protocols/runs/{id}/abort -GET /api/v1/protocols/runs/{id}/status -``` - -### Service Composition Patterns - -**Pattern 1: Protocol Orchestrates Checklist + Journal** -``` -Protocol Run β†’ State "Pre-Op" β†’ Initiate Checklist β†’ -User completes β†’ Auto Journal Entry β†’ Guard passes β†’ Next State -``` - -**Pattern 2: Monitor Triggers Protocol Transition** -``` -Monitor evaluates β†’ Threshold exceeded β†’ Alert β†’ -Protocol listens β†’ Auto-transition to Emergency State -``` - -**Pattern 3: Cross-Service References** -```json -{ - "protocol_run_variables": { - "checklist_pre_op": "01HWFX7K...", - "journal_stream": "01HWFX9N...", - "monitor_heart_rate": "01HWFXAP..." - } -} -``` - -### Implementation Roadmap - -| Phase | Timeline | Focus | -|-------|----------|-------| -| 1 | Weeks 1-2 | Foundation: DB schemas, service modules | -| 2 | Weeks 3-4 | Surgical Care domain pack pilot | -| 3 | Weeks 5-8 | Healthcare tools integration | -| 4 | Weeks 9-12 | Non-healthcare tools (logistics, inventory) | -| 5 | Weeks 13-14 | Optimization & documentation | - -### Testing Requirements - -| Service | Unit | Integration | Performance | Isolation | -|---------|------|-------------|-------------|-----------| -| Checklist | Template/response validation | Full lifecycle | <50ms p95 | 15 tests | -| Journal | Hash computation, amendments | Entry chain | <100ms p95 | 15 tests | -| Monitor | Threshold evaluation, trends | Alert escalation | <30ms p95 | 15 tests | -| Protocol | Guard/action execution | State machine | <200ms p95 | 15 tests | - -### Event Types Summary - -```python -# Checklist Events -checklist.template_created, checklist.initiated, checklist.item_responded, -checklist.completed, checklist.abandoned - -# Journal Events -journal.stream_created, journal.entry_added, journal.entry_amended, -journal.entry_signed, journal.stream_closed - -# Monitor Events -monitor.started, monitor.evaluated, monitor.alert_triggered, -monitor.alert_acknowledged, monitor.alert_resolved - -# Protocol Events -protocol.started, protocol.state_transitioned, protocol.action_executed, -protocol.completed, protocol.aborted -``` - ---- - -## βœ… AI Assistant Checklist (v5.3.0 Extended) diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS deleted file mode 100755 index ed6d22e38d1fb048e6c1cd73ccf405194b881075..0000000000000000000000000000000000000000 --- a/.github/CODEOWNERS +++ /dev/null @@ -1,9 +0,0 @@ -* @yaz-care/platform-team -/src/apps/surgio/ @yaz-care/surgio-team -/src/apps/clinica/ @yaz-care/clinica-team -/src/apps/educa/ @yaz-care/educa-team -/src/apps/insura/ @yaz-care/insura-team -/src/apps/movit/ @yaz-care/movit-team -/deployment/ @yaz-care/devops-team -/docs/ @yaz-care/docs-team -/.github/ @yaz-care/platform-team diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md deleted file mode 100644 index 42a0f7537d2af44c352c2b5b65ff71bcafe28bb5..0000000000000000000000000000000000000000 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ /dev/null @@ -1,208 +0,0 @@ -## Pull Request Description - -### Summary - - -### Related Issues - -Closes # - -### Type of Change -- [ ] πŸ› Bug fix (non-breaking change which fixes an issue) -- [ ] ✨ New feature (non-breaking change which adds functionality) -- [ ] πŸ’₯ Breaking change (fix or feature that would cause existing functionality to not work as expected) -- [ ] πŸ“ Documentation update -- [ ] πŸ”§ Configuration change -- [ ] ♻️ Code refactoring -- [ ] πŸ§ͺ Test update -- [ ] ⚑ Performance improvement - -### Clinical Context - -- **Workflow**: -- **Standards**: -- **User Impact**: - ---- - -## Code Quality Checklist - -### General Requirements -- [ ] **Type Hints**: All functions/methods have complete type hints (Python 3.9+) -- [ ] **Docstrings**: Functions include docstrings with clinical/business context -- [ ] **Error Handling**: Uses `StandardErrorResponse` patterns -- [ ] **Code Style**: Follows PEP 8, passes `black` and `flake8` -- [ ] **No Hardcoded Values**: Configuration in environment variables - -### Multi-Tenancy -- [ ] **Tenant Isolation**: `tenant_id` validated in all operations -- [ ] **Database Queries**: All queries filtered by tenant schema -- [ ] **Cache Keys**: All cache keys prefixed with `tenant:{tenant_id}:` -- [ ] **No Cross-Tenant Access**: Integration test verifies isolation -- [ ] **Tenant Context**: Propagated through all service calls - -### Security & Compliance -- [ ] **No Secrets**: No API keys, passwords, or secrets in code -- [ ] **Input Validation**: All user inputs validated with Pydantic -- [ ] **SQL Injection**: Only parameterized queries used -- [ ] **XSS Prevention**: All output properly escaped -- [ ] **Audit Logging**: PHI access logged with cryptographic verification -- [ ] **HIPAA Compliant**: No PHI in application logs -- [ ] **Authorization**: RBAC/ABAC enforced on all endpoints - -### Performance -- [ ] **SLA Target**: Documented and tested (<200ms p95 for API endpoints) -- [ ] **Database Queries**: No N+1 patterns, uses eager loading -- [ ] **Caching**: Implements appropriate caching tier (1-4) -- [ ] **Async Operations**: Long-running tasks use background workers -- [ ] **Resource Limits**: No unbounded queries or memory allocations - -### Observability -- [ ] **Structured Logging**: Uses `structlog` with required fields -- [ ] **Distributed Tracing**: OpenTelemetry spans with clinical context -- [ ] **Metrics**: Prometheus metrics for key operations -- [ ] **Trace Context**: `trace_id` included in all logs -- [ ] **Healthcare Metrics**: App-specific metrics (bed occupancy, wait times, etc.) - -### Testing -- [ ] **Unit Tests**: Added/updated with β‰₯85% coverage -- [ ] **Integration Tests**: Critical workflows tested -- [ ] **Test Isolation**: Tests don't depend on each other -- [ ] **Performance Tests**: Validates SLA compliance -- [ ] **Multi-Tenancy Tests**: Verifies tenant isolation -- [ ] **All Tests Pass**: βœ… `pytest` runs successfully - -### Standards Compliance -- [ ] **Clinical Standards**: CLSI/ACGME/ASA/WHO compliance verified (if applicable) -- [ ] **Medical Coding**: ICD-10/CPT codes validated -- [ ] **Laboratory**: CLSI standards followed (if applicable) -- [ ] **Surgical**: WHO checklist implemented (if applicable) -- [ ] **Education**: ACGME requirements met (if applicable) - -### Documentation -- [ ] **API Documentation**: OpenAPI/Swagger updated -- [ ] **Architecture Docs**: Updated if architecture changes -- [ ] **README**: Updated if setup process changes -- [ ] **CHANGELOG**: Entry added for this change -- [ ] **Migration Guide**: Included if breaking change - ---- - -## Testing Evidence - -### Test Results -```bash -# Paste output of pytest run -pytest tests/ -v -``` - -### Coverage Report -```bash -# Paste coverage summary -pytest --cov=src --cov-report=term-missing -``` - -### Performance Benchmarks - -- **Before**: p95 = ___ ms -- **After**: p95 = ___ ms -- **Improvement**: ___% - ---- - -## Deployment Considerations - -### Database Migrations -- [ ] **Migration Required**: Yes / No -- [ ] **Migration Tested**: Forward and backward migrations tested -- [ ] **Data Migration**: Data migration script included (if needed) -- [ ] **Rollback Plan**: Documented rollback procedure - -### Configuration Changes -- [ ] **Environment Variables**: New variables documented -- [ ] **Feature Flags**: Feature flag added (if needed) -- [ ] **Cache Invalidation**: Cache keys invalidated if needed - -### Dependencies -- [ ] **New Dependencies**: Added to `requirements.txt` with version pinning -- [ ] **Security Scan**: Dependencies scanned for vulnerabilities -- [ ] **License Check**: New dependencies have compatible licenses - -### Monitoring & Alerts -- [ ] **Metrics Added**: New Prometheus metrics defined -- [ ] **Dashboards Updated**: Grafana dashboards include new metrics -- [ ] **Alerts Configured**: Alerts set for SLA violations -- [ ] **Logging Verified**: Logs searchable in Kibana - ---- - -## Reviewer Checklist - -### Code Review -- [ ] Code is clear and maintainable -- [ ] Architecture patterns followed -- [ ] No code duplication -- [ ] Error handling is comprehensive -- [ ] Security best practices followed - -### Testing Review -- [ ] Tests cover edge cases -- [ ] Test data is realistic -- [ ] Tests are deterministic -- [ ] Performance benchmarks met - -### Documentation Review -- [ ] Documentation is accurate -- [ ] Examples are clear -- [ ] Clinical context explained -- [ ] Breaking changes highlighted - ---- - -## Additional Notes - -### Breaking Changes - - -### Known Limitations - - -### Follow-up Tasks - -- [ ] -- [ ] - ---- - -## Screenshots / Demo - - ---- - -## Pre-Merge Checklist - -**Before merging, ensure:** -- [ ] All CI/CD checks passing -- [ ] At least 2 approvals from reviewers -- [ ] No unresolved comments -- [ ] Merge conflicts resolved -- [ ] CHANGELOG.md updated -- [ ] Documentation deployed -- [ ] Deployment plan reviewed - ---- - -**By submitting this PR, I confirm that:** -- βœ… My code follows YAZ Care Platform coding standards -- βœ… I have performed a self-review of my own code -- βœ… I have commented my code, particularly in hard-to-understand areas -- βœ… I have made corresponding changes to the documentation -- βœ… My changes generate no new warnings -- βœ… I have added tests that prove my fix is effective or that my feature works -- βœ… New and existing unit tests pass locally with my changes -- βœ… Any dependent changes have been merged and published - ---- - -**Reviewer:** @reviewer-username -**Estimated Review Time:** diff --git a/.github/README.md b/.github/README.md deleted file mode 100644 index e45dd21443b98399c21a2bf27722a8d315e1a653..0000000000000000000000000000000000000000 --- a/.github/README.md +++ /dev/null @@ -1,296 +0,0 @@ -# .github Folder Organization - -This folder contains GitHub-specific configuration and documentation for the YAZ Care platform. - -## πŸ“ Folder Structure - -``` -.github/ -β”œβ”€β”€ AI_CODER_INSTRUCTIONS.md # πŸ€– Master guide for AI coding assistants -β”œβ”€β”€ CODEOWNERS # Code ownership assignments -β”œβ”€β”€ PULL_REQUEST_TEMPLATE.md # PR template -β”œβ”€β”€ README.md # This file -β”‚ -β”œβ”€β”€ config/ # Configuration files -β”‚ β”œβ”€β”€ .flake8 # Python linting rules -β”‚ └── .pre-commit-config.yaml # Pre-commit hooks -β”‚ -β”œβ”€β”€ docs/ # GitHub documentation -β”‚ β”œβ”€β”€ COPILOT_GUIDE.md # GitHub Copilot quick reference -β”‚ └── DOCUMENTATION_INDEX.md # Legacy doc index (moved to docs/00-INDEX.md) -β”‚ -β”œβ”€β”€ prompts/ # Reusable AI prompts library -β”‚ β”œβ”€β”€ advanced-patterns.md -β”‚ β”œβ”€β”€ clinical-decision-support.md -β”‚ β”œβ”€β”€ database-patterns.md -β”‚ β”œβ”€β”€ multi-tenancy-patterns.md -β”‚ β”œβ”€β”€ observability-patterns.md -β”‚ β”œβ”€β”€ security-compliance.md -β”‚ β”œβ”€β”€ testing-protocol.md -β”‚ └── testing-strategies.md -β”‚ -└── workflows/ # GitHub Actions CI/CD - β”œβ”€β”€ quality-gates.yml # πŸ”₯ Main CI/CD pipeline (8 stages) - β”œβ”€β”€ deploy-enhanced.yml # Production deployment (blue-green) - β”œβ”€β”€ security-scanning.yml # Security vulnerability scanning - β”œβ”€β”€ ci-tests.yml # Test automation - └── [other workflows] -``` - -## πŸ€– AI Coder Instructions - -**Primary File**: [`AI_CODER_INSTRUCTIONS.md`](./AI_CODER_INSTRUCTIONS.md) - -This is the **authoritative guide** for any AI coding assistant (GitHub Copilot, Claude, ChatGPT, etc.) working on the YAZ Care platform. - -**Contents**: -- Platform overview (17 healthcare modules, 50K+ LOC) -- Core mandate & principles (patient safety, multi-tenancy, HIPAA, performance, quality) -- Architecture patterns (DDD, event-driven, CQRS, multi-tenant) -- Code generation standards (type hints, docstrings, error handling, logging) -- Clinical standards compliance (CLSI, ASA, WHO, ACGME) -- Security & HIPAA requirements (encryption, audit logging, access control) -- Performance engineering (4-tier caching, database optimization) -- Testing requirements (85%+ coverage, multi-tenancy tests) -- File organization & naming conventions -- Development workflow (5-phase cycle) -- Common patterns & templates -- Troubleshooting guide -- Future iterations roadmap -- References & resources - -**Usage**: -```bash -# For AI assistants -"Read .github/AI_CODER_INSTRUCTIONS.md before starting any implementation" - -# For new developers -"Review .github/AI_CODER_INSTRUCTIONS.md during onboarding" - -# For code reviews -"Verify implementation follows .github/AI_CODER_INSTRUCTIONS.md standards" -``` - -## πŸ“š Documentation Locations - -### Primary Documentation -- **Main Docs**: `/docs/` - Comprehensive platform documentation -- **Quick Navigation**: `/docs/00-INDEX.md` - Fast access to all docs -- **Module Docs**: `/docs/06-modules/{module_name}/README.md` - Per-module guides -- **Development**: `/docs/03-development/` - Developer guides and templates - -### GitHub-Specific Docs -- **AI Instructions**: `.github/AI_CODER_INSTRUCTIONS.md` - This folder -- **Copilot Guide**: `.github/docs/COPILOT_GUIDE.md` - Quick reference -- **Prompts Library**: `.github/prompts/` - Reusable prompts - -## πŸ”§ Configuration Files - -### Linting & Formatting -```bash -# Flake8 (Python linting) -flake8 src/ tests/ --config=.github/config/.flake8 - -# Black (Python formatting) -black src/ tests/ - -# isort (Import sorting) -isort src/ tests/ -``` - -### Pre-commit Hooks -```bash -# Install hooks -pre-commit install --config .github/config/.pre-commit-config.yaml - -# Run manually -pre-commit run --all-files --config .github/config/.pre-commit-config.yaml -``` - -## πŸš€ CI/CD Workflows - -### Main Pipeline: `quality-gates.yml` - -**8-Stage Quality Gates**: -1. **Checkout & Setup** - Python 3.11, dependencies -2. **Linting** - flake8, black, isort -3. **Type Checking** - mypy strict mode -4. **Unit Tests** - pytest with coverage (85%+ target) -5. **Integration Tests** - API endpoint validation -6. **Security Scan** - Bandit, Safety -7. **Performance Tests** - Locust load testing -8. **Documentation** - MkDocs build - -**Triggers**: -- Push to `master` or `develop` -- Pull requests -- Manual workflow dispatch - -### Deployment: `deploy-enhanced.yml` - -**Blue-Green Deployment**: -1. Deploy to staging (blue environment) -2. Run smoke tests -3. Switch traffic to blue -4. Monitor metrics (5 minutes) -5. Rollback if errors >1% -6. Mark green environment as standby - -**Manual approval required for production** - -### Security: `security-scanning.yml` - -**Scans**: -- Dependency vulnerabilities (Safety) -- Code security issues (Bandit) -- Secrets detection (Gitleaks) -- Container image scanning (Trivy) - -## πŸ“‹ Prompts Library - -Located in `.github/prompts/`, these are reusable AI prompts for common tasks: - -| Prompt File | Purpose | -|-------------|---------| -| `clinical-decision-support.md` | Healthcare algorithm patterns | -| `multi-tenancy-patterns.md` | Tenant isolation best practices | -| `observability-patterns.md` | Tracing, metrics, logging | -| `security-compliance.md` | HIPAA/audit logging checklist | -| `testing-protocol.md` | Test patterns and coverage | -| `database-patterns.md` | Query optimization, indexing | -| `advanced-patterns.md` | CQRS, event sourcing, DDD | - -**Usage**: -```bash -# Reference in AI prompts -"Follow patterns in .github/prompts/multi-tenancy-patterns.md" - -# Copy template -cp .github/prompts/testing-protocol.md src/apps/new_module/tests/ -``` - -## πŸ› οΈ Common Tasks - -### For AI Assistants - -**Before starting any task**: -```bash -# 1. Read AI instructions -cat .github/AI_CODER_INSTRUCTIONS.md - -# 2. Check module documentation -cat docs/06-modules/{module_name}/README.md - -# 3. Review relevant prompt -cat .github/prompts/{relevant_pattern}.md -``` - -### For Developers - -**Setting up development environment**: -```bash -# 1. Install pre-commit hooks -pre-commit install --config .github/config/.pre-commit-config.yaml - -# 2. Run quality checks -make lint # Uses .github/config/.flake8 -make typecheck # mypy strict -make test # pytest with coverage - -# 3. Review documentation -open docs/00-INDEX.md -``` - -### For Code Reviewers - -**PR review checklist**: -- [ ] Follows `.github/AI_CODER_INSTRUCTIONS.md` standards -- [ ] All quality gates passing (`.github/workflows/quality-gates.yml`) -- [ ] Multi-tenancy tests included -- [ ] HIPAA audit logging implemented -- [ ] Performance targets documented and met -- [ ] Documentation updated - -## πŸ“ Contributing Guidelines - -### File Organization Rules - -**Configuration files** β†’ `.github/config/` -- Linting configs (`.flake8`, `.pylintrc`) -- Pre-commit hooks (`.pre-commit-config.yaml`) -- Editor configs (`.editorconfig`) - -**Documentation** β†’ `.github/docs/` -- GitHub-specific guides -- Quick references -- Legacy documentation - -**Reusable Prompts** β†’ `.github/prompts/` -- AI coding patterns -- Best practices -- Template prompts - -**CI/CD Workflows** β†’ `.github/workflows/` -- GitHub Actions YAML files -- Deployment pipelines -- Automation scripts - -### Naming Conventions - -**Workflows**: `kebab-case.yml` -``` -quality-gates.yml -deploy-enhanced.yml -security-scanning.yml -``` - -**Documentation**: `SCREAMING_SNAKE_CASE.md` (top-level), `kebab-case.md` (subdirs) -``` -AI_CODER_INSTRUCTIONS.md -CODEOWNERS -docs/copilot-guide.md -``` - -**Prompts**: `kebab-case.md` -``` -multi-tenancy-patterns.md -clinical-decision-support.md -``` - -## πŸ”— Quick Links - -### Documentation -- [Main Documentation](../docs/README.md) -- [Quick Navigation](../docs/00-INDEX.md) -- [Development Guide](../docs/03-development/README.md) - -### AI Resources -- [AI Coder Instructions](./AI_CODER_INSTRUCTIONS.md) ⭐ -- [Copilot Guide](./docs/COPILOT_GUIDE.md) -- [Prompts Library](./prompts/) - -### Configuration -- [Linting Config](./config/.flake8) -- [Pre-commit Hooks](./config/.pre-commit-config.yaml) - -### CI/CD -- [Quality Gates Workflow](./workflows/quality-gates.yml) -- [Deployment Workflow](./workflows/deploy-enhanced.yml) -- [All Workflows](./workflows/) - -## πŸ“Š Status - -| Component | Status | Notes | -|-----------|--------|-------| -| **AI Instructions** | βœ… Complete | v5.0.0 (Dec 26, 2025) | -| **Folder Organization** | βœ… Complete | Organized into 4 subdirectories | -| **Quality Gates** | βœ… Active | 8-stage pipeline | -| **Deployment** | βœ… Active | Blue-green strategy | -| **Security Scanning** | βœ… Active | Daily scans | -| **Documentation** | βœ… Up-to-date | Synchronized with main docs | - ---- - -**Last Updated**: December 26, 2025 -**Maintained By**: YAZ Care Platform Team -**Status**: 🟒 Organized and Production-Ready diff --git a/.github/config/.flake8 b/.github/config/.flake8 deleted file mode 100644 index bfcead4159cc695a71940822912fce0ba0ef0816..0000000000000000000000000000000000000000 --- a/.github/config/.flake8 +++ /dev/null @@ -1,20 +0,0 @@ -[flake8] -max-line-length = 88 -extend-ignore = E203, W503, E501 -exclude = - .git, - __pycache__, - .pytest_cache, - htmlcov, - build, - dist, - *.egg-info, - .tox, - .coverage, - migrations, - venv, - virtualenv -per-file-ignores = - __init__.py:F401 - tests/*:S101,S106 -max-complexity = 10 \ No newline at end of file diff --git a/.github/config/.pre-commit-config.yaml b/.github/config/.pre-commit-config.yaml deleted file mode 100755 index 3cd860ace46be98f853e9fd8c2a4e1150a9d6739..0000000000000000000000000000000000000000 --- a/.github/config/.pre-commit-config.yaml +++ /dev/null @@ -1,16 +0,0 @@ -repos: - - repo: https://github.com/astral-sh/ruff-pre-commit - rev: v0.4.8 - hooks: - - id: ruff - args: [--fix] - - id: ruff-format - - - repo: local - hooks: - - id: no-star-imports - name: Prevent star imports - entry: bash -c 'if grep -r "from .* import \*" src/ --include="*.py" | grep -v "# noqa"; then echo "❌ Star imports found!"; exit 1; fi' - language: system - pass_filenames: false - stages: [pre-commit] diff --git a/.github/copilot-prompts/advanced-patterns.md b/.github/copilot-prompts/advanced-patterns.md deleted file mode 100644 index de4bd7ed7dfafe9a56a74b4ae9f800c06bea4b50..0000000000000000000000000000000000000000 --- a/.github/copilot-prompts/advanced-patterns.md +++ /dev/null @@ -1,847 +0,0 @@ -# Advanced Development Patterns for YAZ Care Platform - -## Overview -This document covers advanced patterns for building sophisticated healthcare features, including TOPSIS decision-making, event-driven architecture, background processing, and integration patterns. - -## 1. TOPSIS Multi-Criteria Decision Making - -### Clinical Context -TOPSIS (Technique for Order Preference by Similarity to Ideal Solution) is used for complex clinical decisions involving multiple weighted criteria, such as surgical case prioritization, treatment plan selection, and resource allocation. - -### Implementation Pattern - -```python -from typing import List, Dict, Any, Optional -import numpy as np -from pydantic import BaseModel, Field -import structlog - -logger = structlog.get_logger() - -class CriterionWeight(BaseModel): - """Weight configuration for TOPSIS criterion.""" - name: str - weight: float = Field(..., gt=0, le=1) - benefit: bool = True # True if higher is better, False if lower is better - min_threshold: Optional[float] = None - max_threshold: Optional[float] = None - -class TOPSISDecision(BaseModel): - """TOPSIS analysis result.""" - alternative_id: str - score: float = Field(..., ge=0, le=1) - rank: int - distance_to_ideal: float - distance_to_negative: float - criteria_scores: Dict[str, float] - metadata: Dict[str, Any] = {} - -class TOPSISAnalyzer: - """ - Multi-criteria decision analysis using TOPSIS. - - Clinical Context: Supports evidence-based clinical decision-making - with multiple weighted factors (efficacy, safety, cost, accessibility). - - Standards: Follows AHRQ (Agency for Healthcare Research and Quality) - comparative effectiveness research guidelines. - - Performance: <100ms for up to 100 alternatives, <500ms for 1000+ - """ - - def __init__( - self, - criteria: List[CriterionWeight], - tenant_id: str - ): - self.criteria = criteria - self.tenant_id = tenant_id - self._validate_weights() - - def _validate_weights(self) -> None: - """Ensure weights sum to 1.0.""" - total_weight = sum(c.weight for c in self.criteria) - if not (0.99 <= total_weight <= 1.01): - raise ValueError(f"Weights must sum to 1.0, got {total_weight}") - - async def analyze( - self, - alternatives: List[Dict[str, Any]], - user_id: str, - trace_context: Optional[Dict[str, Any]] = None - ) -> List[TOPSISDecision]: - """ - Perform TOPSIS analysis on alternatives. - - Args: - alternatives: List of options with criterion values - user_id: For audit logging - trace_context: OpenTelemetry context - - Returns: - Ranked list of alternatives with scores - - Raises: - ValueError: Invalid input data - - Performance: O(n*m) where n=alternatives, m=criteria - """ - if not alternatives: - raise ValueError("At least one alternative required") - - logger.info( - "topsis_analysis_started", - tenant_id=self.tenant_id, - user_id=user_id, - alternative_count=len(alternatives), - criteria_count=len(self.criteria) - ) - - # Step 1: Build decision matrix - matrix = self._build_matrix(alternatives) - - # Step 2: Normalize matrix - normalized = self._normalize_matrix(matrix) - - # Step 3: Apply weights - weighted = self._apply_weights(normalized) - - # Step 4: Calculate ideal and negative-ideal solutions - ideal = self._calculate_ideal_solution(weighted) - negative_ideal = self._calculate_negative_ideal(weighted) - - # Step 5: Calculate distances and scores - decisions = [] - for idx, alt in enumerate(alternatives): - d_positive = np.linalg.norm(weighted[idx] - ideal) - d_negative = np.linalg.norm(weighted[idx] - negative_ideal) - - score = d_negative / (d_positive + d_negative) if (d_positive + d_negative) > 0 else 0 - - decisions.append(TOPSISDecision( - alternative_id=alt["id"], - score=float(score), - rank=0, # Will be assigned after sorting - distance_to_ideal=float(d_positive), - distance_to_negative=float(d_negative), - criteria_scores={ - c.name: float(weighted[idx][i]) - for i, c in enumerate(self.criteria) - }, - metadata=alt.get("metadata", {}) - )) - - # Step 6: Rank alternatives - decisions.sort(key=lambda x: x.score, reverse=True) - for rank, decision in enumerate(decisions, start=1): - decision.rank = rank - - logger.info( - "topsis_analysis_completed", - tenant_id=self.tenant_id, - top_alternative=decisions[0].alternative_id if decisions else None, - top_score=decisions[0].score if decisions else None - ) - - return decisions - - def _build_matrix(self, alternatives: List[Dict[str, Any]]) -> np.ndarray: - """Build decision matrix from alternatives.""" - matrix = [] - for alt in alternatives: - row = [alt.get(c.name, 0.0) for c in self.criteria] - matrix.append(row) - return np.array(matrix) - - def _normalize_matrix(self, matrix: np.ndarray) -> np.ndarray: - """Normalize using vector normalization.""" - norms = np.linalg.norm(matrix, axis=0) - return matrix / norms - - def _apply_weights(self, normalized: np.ndarray) -> np.ndarray: - """Apply criterion weights to normalized matrix.""" - weights = np.array([c.weight for c in self.criteria]) - return normalized * weights - - def _calculate_ideal_solution(self, weighted: np.ndarray) -> np.ndarray: - """Calculate ideal solution (best values for each criterion).""" - ideal = [] - for i, criterion in enumerate(self.criteria): - if criterion.benefit: - ideal.append(np.max(weighted[:, i])) - else: - ideal.append(np.min(weighted[:, i])) - return np.array(ideal) - - def _calculate_negative_ideal(self, weighted: np.ndarray) -> np.ndarray: - """Calculate negative-ideal solution (worst values).""" - negative_ideal = [] - for i, criterion in enumerate(self.criteria): - if criterion.benefit: - negative_ideal.append(np.min(weighted[:, i])) - else: - negative_ideal.append(np.max(weighted[:, i])) - return np.array(negative_ideal) - -# Example Usage in Surgio Module -async def prioritize_surgical_cases( - tenant_id: str, - user_id: str, - cases: List[Dict[str, Any]] -) -> List[TOPSISDecision]: - """ - Prioritize surgical cases using TOPSIS. - - Clinical Context: Operating room scheduling with multiple factors - Standards: ASA guidelines, hospital capacity planning - Performance: <200ms for typical case load (50 cases) - """ - criteria = [ - CriterionWeight(name="urgency_score", weight=0.35, benefit=True), - CriterionWeight(name="patient_asa_class", weight=0.25, benefit=False), # Lower is better - CriterionWeight(name="procedure_duration_hours", weight=0.15, benefit=False), - CriterionWeight(name="resource_availability", weight=0.15, benefit=True), - CriterionWeight(name="days_waiting", weight=0.10, benefit=True) - ] - - analyzer = TOPSISAnalyzer(criteria=criteria, tenant_id=tenant_id) - return await analyzer.analyze(alternatives=cases, user_id=user_id) -``` - -### Testing TOPSIS Implementation - -```python -import pytest -import numpy as np - -def test_topsis_surgical_prioritization_high_urgency(): - """Test TOPSIS correctly prioritizes high-urgency cases.""" - criteria = [ - CriterionWeight(name="urgency_score", weight=0.5, benefit=True), - CriterionWeight(name="asa_class", weight=0.5, benefit=False) - ] - - cases = [ - {"id": "case-1", "urgency_score": 9, "asa_class": 2}, # High urgency, low risk - {"id": "case-2", "urgency_score": 5, "asa_class": 1}, # Medium urgency, very low risk - {"id": "case-3", "urgency_score": 8, "asa_class": 4}, # High urgency, high risk - ] - - analyzer = TOPSISAnalyzer(criteria=criteria, tenant_id="test-tenant") - results = await analyzer.analyze(alternatives=cases, user_id="test-user") - - # Case-1 should rank highest (high urgency + low risk) - assert results[0].alternative_id == "case-1" - assert results[0].rank == 1 - assert results[0].score > 0.6 - -@pytest.mark.performance -async def test_topsis_performance_large_dataset(): - """Verify TOPSIS meets performance target with large dataset.""" - import time - - criteria = [ - CriterionWeight(name="factor1", weight=0.5, benefit=True), - CriterionWeight(name="factor2", weight=0.5, benefit=False) - ] - - # Generate 500 alternatives - cases = [ - {"id": f"case-{i}", "factor1": np.random.rand(), "factor2": np.random.rand()} - for i in range(500) - ] - - analyzer = TOPSISAnalyzer(criteria=criteria, tenant_id="test-tenant") - - start = time.time() - results = await analyzer.analyze(alternatives=cases, user_id="test-user") - duration_ms = (time.time() - start) * 1000 - - assert duration_ms < 500 # Must complete in <500ms - assert len(results) == 500 - assert all(r.rank > 0 for r in results) -``` - ---- - -## 2. Event-Driven Architecture Patterns - -### Domain Events for Cross-App Communication - -```python -from typing import Dict, Any, Optional -from datetime import datetime -from pydantic import BaseModel, Field -from enum import Enum -import structlog - -logger = structlog.get_logger() - -class EventType(str, Enum): - """Domain event types.""" - PATIENT_ADMITTED = "patient.admitted" - SURGERY_SCHEDULED = "surgery.scheduled" - LAB_RESULT_CRITICAL = "lab.result.critical" - MEDICATION_PRESCRIBED = "medication.prescribed" - MEDICATION_INTERACTION_DETECTED = "medication.interaction.detected" - -class DomainEvent(BaseModel): - """Base class for all domain events.""" - event_id: str = Field(default_factory=lambda: str(uuid.uuid4())) - event_type: EventType - tenant_id: str - timestamp: datetime = Field(default_factory=datetime.utcnow) - source_app: str - user_id: str - payload: Dict[str, Any] - metadata: Dict[str, Any] = {} - trace_id: Optional[str] = None - -class EventPublisher: - """ - Publish domain events to message queue (Redis Streams). - - Performance: <10ms per event publish - Reliability: At-least-once delivery guarantee - """ - - def __init__(self, redis_client, tenant_id: str): - self.redis = redis_client - self.tenant_id = tenant_id - self.stream_prefix = f"events:{tenant_id}" - - async def publish( - self, - event: DomainEvent, - user_id: str - ) -> str: - """ - Publish event to Redis Stream. - - Returns: - Event ID for tracking - """ - stream_key = f"{self.stream_prefix}:{event.event_type.value}" - - event_data = { - "event_id": event.event_id, - "payload": json.dumps(event.payload), - "metadata": json.dumps(event.metadata), - "timestamp": event.timestamp.isoformat(), - "user_id": user_id, - "trace_id": event.trace_id or "unknown" - } - - # Publish to Redis Stream - stream_id = await self.redis.xadd(stream_key, event_data) - - logger.info( - "event_published", - event_type=event.event_type.value, - event_id=event.event_id, - stream_id=stream_id, - tenant_id=self.tenant_id - ) - - return event.event_id - -class EventSubscriber: - """ - Subscribe to domain events from message queue. - - Pattern: Consumer group for load balancing and reliability - """ - - def __init__( - self, - redis_client, - tenant_id: str, - consumer_group: str, - consumer_name: str - ): - self.redis = redis_client - self.tenant_id = tenant_id - self.consumer_group = consumer_group - self.consumer_name = consumer_name - self.handlers: Dict[EventType, callable] = {} - - def register_handler( - self, - event_type: EventType, - handler: callable - ) -> None: - """Register handler function for event type.""" - self.handlers[event_type] = handler - - async def start_consuming(self) -> None: - """Start consuming events from subscribed streams.""" - streams = { - f"events:{self.tenant_id}:{et.value}": ">" - for et in self.handlers.keys() - } - - while True: - try: - # Read from multiple streams - events = await self.redis.xreadgroup( - groupname=self.consumer_group, - consumername=self.consumer_name, - streams=streams, - count=10, - block=5000 # 5 second timeout - ) - - for stream, messages in events: - for message_id, data in messages: - await self._process_event(stream, message_id, data) - - except Exception as e: - logger.error( - "event_consumption_error", - error=str(e), - tenant_id=self.tenant_id - ) - await asyncio.sleep(1) - - async def _process_event( - self, - stream: str, - message_id: str, - data: Dict[str, Any] - ) -> None: - """Process individual event.""" - try: - event_type_str = stream.split(":")[-1] - event_type = EventType(event_type_str) - - handler = self.handlers.get(event_type) - if handler: - await handler(data) - - # Acknowledge message - await self.redis.xack(stream, self.consumer_group, message_id) - - logger.info( - "event_processed", - event_type=event_type_str, - message_id=message_id - ) - except Exception as e: - logger.error( - "event_processing_error", - error=str(e), - message_id=message_id - ) - -# Example: Cross-app event handling -# Pharma app listens for surgery scheduled events to prepare medications - -async def handle_surgery_scheduled(event_data: Dict[str, Any]) -> None: - """ - Handle surgery scheduled event in Pharma app. - - Clinical Context: Preoperative medication preparation - """ - payload = json.loads(event_data["payload"]) - patient_id = payload["patient_id"] - surgery_datetime = payload["scheduled_datetime"] - procedure_type = payload["procedure_type"] - - # Retrieve patient medications - medications = await get_patient_medications( - tenant_id=event_data["tenant_id"], - patient_id=patient_id - ) - - # Check for medications that need adjustment before surgery - preop_adjustments = await check_preoperative_medication_adjustments( - medications=medications, - procedure_type=procedure_type - ) - - if preop_adjustments: - # Publish event for clinical team - await publish_event( - event_type=EventType.MEDICATION_ADJUSTMENT_REQUIRED, - payload={ - "patient_id": patient_id, - "surgery_id": payload["surgery_id"], - "adjustments": preop_adjustments - } - ) -``` - ---- - -## 3. Background Job Processing - -### Celery Task Patterns - -```python -from celery import Celery, Task -from typing import Dict, Any -import structlog - -logger = structlog.get_logger() - -# Celery app configuration -celery_app = Celery( - "yaz_care", - broker="redis://localhost:6379/0", - backend="redis://localhost:6379/1" -) - -celery_app.conf.update( - task_serializer="json", - accept_content=["json"], - result_serializer="json", - timezone="UTC", - enable_utc=True, - task_track_started=True, - task_time_limit=3600, # 1 hour max - task_soft_time_limit=3300, # 55 minutes soft limit -) - -class TenantTask(Task): - """Base task with tenant context.""" - - def __call__(self, *args, **kwargs): - """Inject tenant context into task execution.""" - tenant_id = kwargs.get("tenant_id") - if not tenant_id: - raise ValueError("tenant_id required for all tasks") - - logger.info( - "task_started", - task_name=self.name, - tenant_id=tenant_id, - task_id=self.request.id - ) - - try: - result = super().__call__(*args, **kwargs) - logger.info( - "task_completed", - task_name=self.name, - tenant_id=tenant_id, - task_id=self.request.id - ) - return result - except Exception as e: - logger.error( - "task_failed", - task_name=self.name, - tenant_id=tenant_id, - task_id=self.request.id, - error=str(e) - ) - raise - -@celery_app.task(base=TenantTask, bind=True, max_retries=3) -def generate_clinical_report( - self, - tenant_id: str, - report_type: str, - patient_id: str, - date_range: Dict[str, str], - user_id: str -) -> Dict[str, Any]: - """ - Generate comprehensive clinical report (long-running task). - - Clinical Context: Regulatory compliance reporting, quality metrics - Performance: May take 5-30 minutes depending on data volume - """ - try: - # Step 1: Gather data from multiple sources - encounters = fetch_encounters(tenant_id, patient_id, date_range) - lab_results = fetch_lab_results(tenant_id, patient_id, date_range) - medications = fetch_medications(tenant_id, patient_id, date_range) - - # Step 2: Analyze and aggregate - report_data = { - "encounter_summary": analyze_encounters(encounters), - "lab_trends": analyze_lab_trends(lab_results), - "medication_adherence": calculate_adherence(medications), - } - - # Step 3: Generate PDF - pdf_path = generate_pdf_report(report_data, report_type) - - # Step 4: Store and notify - report_id = store_report(tenant_id, patient_id, pdf_path) - - notify_user(user_id, f"Report {report_id} ready for review") - - return { - "success": True, - "report_id": report_id, - "file_path": pdf_path - } - - except Exception as exc: - # Retry with exponential backoff - raise self.retry(exc=exc, countdown=60 * (2 ** self.request.retries)) - -@celery_app.task(base=TenantTask) -def process_lab_results_batch( - tenant_id: str, - lab_results: List[Dict[str, Any]], - user_id: str -) -> Dict[str, Any]: - """ - Process batch of lab results (CLSI validation, delta checks). - - Clinical Context: Quality control, panic value detection - Standards: CLSI EP17-A2, CLSI GP27 - Performance: ~1000 results per minute - """ - validated = [] - rejected = [] - alerts = [] - - for result in lab_results: - try: - # Validate against QC rules - qc_status = validate_qc_rules(result) - - if not qc_status.passed: - rejected.append({ - "result_id": result["id"], - "reason": qc_status.reason - }) - continue - - # Perform delta check - delta_check = perform_delta_check(tenant_id, result) - - if delta_check.significant_change: - alerts.append({ - "result_id": result["id"], - "type": "delta_check_failed", - "details": delta_check.details - }) - - # Check panic values - if is_panic_value(result): - alerts.append({ - "result_id": result["id"], - "type": "panic_value", - "value": result["value"], - "reference_range": result["reference_range"] - }) - - # Send immediate notification - notify_critical_result(tenant_id, result, user_id) - - validated.append(result) - - except Exception as e: - logger.error( - "lab_result_processing_error", - result_id=result.get("id"), - error=str(e) - ) - rejected.append({ - "result_id": result.get("id"), - "reason": f"Processing error: {str(e)}" - }) - - return { - "processed": len(lab_results), - "validated": len(validated), - "rejected": len(rejected), - "alerts": len(alerts), - "alert_details": alerts - } - -# Task scheduling with Celery Beat -celery_app.conf.beat_schedule = { - "daily-quality-metrics": { - "task": "calculate_daily_quality_metrics", - "schedule": crontab(hour=2, minute=0), # 2 AM daily - }, - "hourly-cache-cleanup": { - "task": "cleanup_expired_cache", - "schedule": crontab(minute=0), # Every hour - }, -} -``` - ---- - -## 4. Integration Patterns - -### External API Integration with Retry Logic - -```python -from typing import Optional, Dict, Any -import httpx -from tenacity import ( - retry, - stop_after_attempt, - wait_exponential, - retry_if_exception_type -) -import structlog - -logger = structlog.get_logger() - -class ExternalAPIClient: - """ - Base client for external healthcare API integrations. - - Features: - - Automatic retry with exponential backoff - - Circuit breaker pattern - - Request/response logging - - Performance monitoring - """ - - def __init__( - self, - base_url: str, - api_key: str, - tenant_id: str, - timeout: int = 30 - ): - self.base_url = base_url - self.api_key = api_key - self.tenant_id = tenant_id - self.timeout = timeout - self.client = httpx.AsyncClient( - base_url=base_url, - timeout=timeout, - headers={ - "Authorization": f"Bearer {api_key}", - "X-Tenant-ID": tenant_id, - "User-Agent": "YAZCare/3.8.0" - } - ) - - @retry( - retry=retry_if_exception_type((httpx.TimeoutException, httpx.NetworkError)), - stop=stop_after_attempt(3), - wait=wait_exponential(multiplier=1, min=2, max=10) - ) - async def get( - self, - endpoint: str, - params: Optional[Dict[str, Any]] = None, - user_id: Optional[str] = None - ) -> Dict[str, Any]: - """ - GET request with retry logic. - - Performance: Includes timeout and retry budget in SLA - """ - logger.info( - "external_api_request", - method="GET", - endpoint=endpoint, - tenant_id=self.tenant_id, - user_id=user_id - ) - - try: - response = await self.client.get(endpoint, params=params) - response.raise_for_status() - - logger.info( - "external_api_response", - method="GET", - endpoint=endpoint, - status_code=response.status_code, - duration_ms=response.elapsed.total_seconds() * 1000 - ) - - return response.json() - - except httpx.HTTPStatusError as e: - logger.error( - "external_api_error", - method="GET", - endpoint=endpoint, - status_code=e.response.status_code, - error=str(e) - ) - raise - - async def post( - self, - endpoint: str, - data: Dict[str, Any], - user_id: Optional[str] = None - ) -> Dict[str, Any]: - """POST request with retry logic.""" - # Similar implementation to GET - pass - -# Example: FDA Drug Interaction API Integration -class FDADrugInteractionClient(ExternalAPIClient): - """ - Client for FDA Drug Interaction API. - - Clinical Context: Real-time drug-drug interaction checking - Standards: FDA Orange Book, RxNorm - """ - - def __init__(self, tenant_id: str): - super().__init__( - base_url="https://api.fda.gov/drug", - api_key=os.getenv("FDA_API_KEY"), - tenant_id=tenant_id - ) - - async def check_interactions( - self, - drug_names: List[str], - user_id: str - ) -> Dict[str, Any]: - """ - Check drug-drug interactions. - - Performance: <500ms target (includes external API call) - Caching: Results cached for 24h (Tier 4) - """ - # Check cache first - cache_key = f"fda:interactions:{':'.join(sorted(drug_names))}" - cached = await redis.get(cache_key) - if cached: - logger.info("fda_interaction_cache_hit", drugs=drug_names) - return json.loads(cached) - - # Call FDA API - interactions = await self.get( - endpoint="/interaction.json", - params={"drug_name": drug_names}, - user_id=user_id - ) - - # Cache result - await redis.setex( - cache_key, - 86400, # 24 hours - json.dumps(interactions) - ) - - return interactions -``` - ---- - -## Summary - -These advanced patterns enable: -- βœ… Sophisticated multi-criteria clinical decision-making (TOPSIS) -- βœ… Decoupled cross-app communication (Event-Driven Architecture) -- βœ… Long-running background processing (Celery) -- βœ… Reliable external API integrations with retry logic -- βœ… Performance monitoring and caching at all layers - -**Always include**: -- Clinical context in docstrings -- Performance targets and monitoring -- Comprehensive error handling -- Audit logging for compliance -- Unit and integration tests diff --git a/.github/copilot-prompts/clinical-decision-support.md b/.github/copilot-prompts/clinical-decision-support.md deleted file mode 100644 index d112cd4c928c20f0e31e13f3795473e837e79416..0000000000000000000000000000000000000000 --- a/.github/copilot-prompts/clinical-decision-support.md +++ /dev/null @@ -1,525 +0,0 @@ -# Clinical Decision Support Prompts - -## Template: New Clinical Algorithm - -### Prompt Structure -``` -Create a clinical decision support service for [CLINICAL_TASK] - -Requirements: -- Clinical Context: [Describe medical workflow] -- Input: [Patient data, clinical measurements] -- Algorithm: [TOPSIS/Rule-based/ML model] -- Standards: [CLSI/ACGME/ASA/WHO compliance] -- Output: [Risk score/Recommendation/Alert] -- Performance: <200ms p95 -- Multi-tenancy: Isolated by tenant_id -- Observability: Trace clinical decisions - -Example Pattern (from Surgio): -- Input validation with Pydantic -- Business logic in service layer -- Database queries with tenant isolation -- Structured response with metadata -- Comprehensive test coverage -- Audit logging for clinical decisions - -Include: -1. Service class with type hints -2. Pydantic models for validation -3. Unit tests (happy path + edge cases) -4. Integration test with database -5. Performance benchmark test -6. Documentation with clinical rationale -``` - -## Example: Sepsis Screening Algorithm - -### Prompt -``` -Create a sepsis screening clinical decision support service for Clinica app. - -Clinical Context: -Implement early sepsis detection using SIRS (Systemic Inflammatory Response Syndrome) -criteria and qSOFA (quick Sequential Organ Failure Assessment) scoring. This supports -emergency department triage and ICU monitoring workflows. - -Input Data: -- Vital signs: temperature, heart rate, respiratory rate, blood pressure -- Laboratory: WBC count, lactate level -- Clinical observations: altered mental status, oxygen saturation -- Patient demographics: age, comorbidities - -Algorithm: -Rule-based scoring system combining: -1. SIRS criteria (β‰₯2 of 4 criteria) -2. qSOFA score (β‰₯2 of 3 criteria) -3. Lactate level risk stratification -4. TOPSIS for overall risk prioritization - -Standards: WHO Sepsis-3 definitions, Surviving Sepsis Campaign guidelines - -Output: -- Risk score (0.0-1.0) -- Severity classification (low/moderate/high/critical) -- Recommended interventions -- Time-sensitive alerts (if critical) -- Supporting evidence (which criteria met) - -Performance: Target <100ms (pure calculation), <150ms (with DB lookup) - -Multi-tenancy: All queries filtered by tenant_id, cache keys prefixed - -Observability: -- Log: sepsis_screening_started/completed with patient_id (hashed) -- Trace: span for each scoring component -- Metrics: screening_duration_ms, high_risk_alert_count -``` - -### Expected Implementation Pattern - -```python -from __future__ import annotations -from typing import Dict, Any, Optional, List -from pydantic import BaseModel, Field, validator -from datetime import datetime -import structlog -from opentelemetry import trace - -logger = structlog.get_logger() -tracer = trace.get_tracer(__name__) - - -class VitalSigns(BaseModel): - """Patient vital signs for sepsis screening.""" - temperature: float = Field(..., ge=35.0, le=42.0, description="Temperature in Celsius") - heart_rate: int = Field(..., ge=40, le=200, description="Heart rate in bpm") - respiratory_rate: int = Field(..., ge=8, le=40, description="Respiratory rate per minute") - systolic_bp: int = Field(..., ge=60, le=250, description="Systolic blood pressure") - oxygen_saturation: Optional[float] = Field(None, ge=50.0, le=100.0) - - @validator('temperature') - def validate_temperature_range(cls, v): - if v < 36.0 or v > 38.3: - logger.warning("abnormal_temperature_detected", temp=v) - return v - - -class LabResults(BaseModel): - """Laboratory results for sepsis assessment.""" - wbc_count: Optional[float] = Field(None, ge=0, le=50, description="WBC count in thousands/ΞΌL") - lactate_level: Optional[float] = Field(None, ge=0, le=20, description="Lactate in mmol/L") - - -class SepsisScreeningRequest(BaseModel): - """Complete sepsis screening input.""" - patient_id: str - vital_signs: VitalSigns - lab_results: LabResults - altered_mental_status: bool = False - timestamp: datetime = Field(default_factory=datetime.utcnow) - - -class SepsisRiskResponse(BaseModel): - """Sepsis risk assessment result.""" - risk_score: float = Field(..., ge=0.0, le=1.0) - severity: str = Field(..., regex="^(low|moderate|high|critical)$") - sirs_score: int = Field(..., ge=0, le=4) - qsofa_score: int = Field(..., ge=0, le=3) - recommendations: List[str] - alerts: List[str] - criteria_met: Dict[str, bool] - screening_timestamp: datetime - - -class SepsisScreeningService: - """ - Clinical decision support service for sepsis screening. - - Implements SIRS and qSOFA scoring with risk stratification per - Surviving Sepsis Campaign guidelines and WHO Sepsis-3 definitions. - - Standards Compliance: - - WHO Sepsis-3 definitions - - Surviving Sepsis Campaign guidelines - - SIRS criteria (β‰₯2 indicates systemic inflammation) - - qSOFA score (β‰₯2 indicates organ dysfunction) - - Performance: <150ms p95 (including database queries) - """ - - async def screen_patient( - self, - tenant_id: str, - user_id: str, - screening_data: SepsisScreeningRequest, - trace_context: Optional[Dict[str, Any]] = None - ) -> SepsisRiskResponse: - """ - Perform sepsis risk screening for a patient. - - Clinical Context: - Early sepsis detection is critical for mortality reduction. This service - identifies patients at risk using validated clinical criteria and triggers - time-sensitive interventions when indicated. - - Args: - tenant_id: Multi-tenant isolation key - user_id: Clinician performing screening (audit trail) - screening_data: Vital signs and lab results - trace_context: OpenTelemetry span context - - Returns: - SepsisRiskResponse with risk score, severity, and recommendations - - Raises: - ValidationError: Invalid clinical data - TenantIsolationError: Cross-tenant access attempt - - Performance: Target <100ms calculation, <150ms with DB - """ - with tracer.start_as_current_span("sepsis_screening") as span: - span.set_attribute("tenant.id", tenant_id) - span.set_attribute("user.id", user_id) - span.set_attribute("patient.id", screening_data.patient_id) - - logger.info( - "sepsis_screening_started", - tenant_id=tenant_id, - user_id=user_id, - patient_id=screening_data.patient_id, - trace_id=format(span.get_span_context().trace_id, '032x') - ) - - # Calculate SIRS score - sirs_score = self._calculate_sirs_score(screening_data) - span.set_attribute("sirs.score", sirs_score) - - # Calculate qSOFA score - qsofa_score = self._calculate_qsofa_score(screening_data) - span.set_attribute("qsofa.score", qsofa_score) - - # Overall risk using TOPSIS - risk_score = self._calculate_risk_score(sirs_score, qsofa_score, screening_data) - - # Determine severity - severity = self._determine_severity(risk_score, sirs_score, qsofa_score) - - # Generate recommendations - recommendations = self._generate_recommendations(severity, screening_data) - - # Generate alerts - alerts = self._generate_alerts(severity, screening_data) - - # Track criteria met - criteria_met = self._track_criteria(screening_data, sirs_score, qsofa_score) - - response = SepsisRiskResponse( - risk_score=risk_score, - severity=severity, - sirs_score=sirs_score, - qsofa_score=qsofa_score, - recommendations=recommendations, - alerts=alerts, - criteria_met=criteria_met, - screening_timestamp=datetime.utcnow() - ) - - logger.info( - "sepsis_screening_completed", - tenant_id=tenant_id, - risk_score=risk_score, - severity=severity, - trace_id=format(span.get_span_context().trace_id, '032x') - ) - - return response - - def _calculate_sirs_score(self, data: SepsisScreeningRequest) -> int: - """Calculate SIRS score (0-4).""" - score = 0 - vitals = data.vital_signs - - # Temperature: <36Β°C or >38.3Β°C - if vitals.temperature < 36.0 or vitals.temperature > 38.3: - score += 1 - - # Heart rate: >90 bpm - if vitals.heart_rate > 90: - score += 1 - - # Respiratory rate: >20/min - if vitals.respiratory_rate > 20: - score += 1 - - # WBC: <4k or >12k - if data.lab_results.wbc_count: - if data.lab_results.wbc_count < 4.0 or data.lab_results.wbc_count > 12.0: - score += 1 - - return score - - def _calculate_qsofa_score(self, data: SepsisScreeningRequest) -> int: - """Calculate qSOFA score (0-3).""" - score = 0 - - # Altered mental status - if data.altered_mental_status: - score += 1 - - # Respiratory rate β‰₯22/min - if data.vital_signs.respiratory_rate >= 22: - score += 1 - - # Systolic BP ≀100 mmHg - if data.vital_signs.systolic_bp <= 100: - score += 1 - - return score - - def _calculate_risk_score( - self, - sirs_score: int, - qsofa_score: int, - data: SepsisScreeningRequest - ) -> float: - """Calculate overall risk score using TOPSIS.""" - # Normalize scores - sirs_normalized = sirs_score / 4.0 - qsofa_normalized = qsofa_score / 3.0 - - # Lactate risk - lactate_risk = 0.0 - if data.lab_results.lactate_level: - if data.lab_results.lactate_level > 4.0: - lactate_risk = 1.0 - elif data.lab_results.lactate_level > 2.0: - lactate_risk = 0.5 - - # Weighted combination (TOPSIS-style) - weights = [0.4, 0.4, 0.2] # SIRS, qSOFA, lactate - risk_score = ( - weights[0] * sirs_normalized + - weights[1] * qsofa_normalized + - weights[2] * lactate_risk - ) - - return min(risk_score, 1.0) - - def _determine_severity( - self, - risk_score: float, - sirs_score: int, - qsofa_score: int - ) -> str: - """Determine severity classification.""" - if qsofa_score >= 2 or risk_score >= 0.7: - return "critical" - elif sirs_score >= 3 or risk_score >= 0.5: - return "high" - elif sirs_score >= 2 or risk_score >= 0.3: - return "moderate" - else: - return "low" - - def _generate_recommendations( - self, - severity: str, - data: SepsisScreeningRequest - ) -> List[str]: - """Generate clinical recommendations.""" - recommendations = [] - - if severity == "critical": - recommendations.extend([ - "IMMEDIATE: Initiate sepsis bundle within 1 hour", - "Obtain blood cultures before antibiotics", - "Administer broad-spectrum antibiotics", - "Begin fluid resuscitation (30 mL/kg crystalloid)", - "Consider ICU admission", - "Measure lactate level if not done", - "Continuous hemodynamic monitoring" - ]) - elif severity == "high": - recommendations.extend([ - "Urgent sepsis workup required", - "Obtain blood cultures", - "Consider early antibiotics", - "IV fluid resuscitation", - "Repeat vital signs q30min", - "Senior clinician review" - ]) - elif severity == "moderate": - recommendations.extend([ - "Close monitoring recommended", - "Repeat screening in 2-4 hours", - "Consider source of infection", - "Ensure adequate hydration" - ]) - else: - recommendations.append("Continue routine monitoring") - - return recommendations - - def _generate_alerts( - self, - severity: str, - data: SepsisScreeningRequest - ) -> List[str]: - """Generate time-sensitive alerts.""" - alerts = [] - - if severity == "critical": - alerts.append("CRITICAL: High sepsis risk - Immediate intervention required") - - if data.lab_results.lactate_level and data.lab_results.lactate_level > 4.0: - alerts.append("ALERT: Lactate >4 mmol/L - Severe sepsis likely") - - if data.vital_signs.systolic_bp < 90: - alerts.append("ALERT: Hypotension - Possible septic shock") - - return alerts - - def _track_criteria( - self, - data: SepsisScreeningRequest, - sirs_score: int, - qsofa_score: int - ) -> Dict[str, bool]: - """Track which clinical criteria were met.""" - vitals = data.vital_signs - - return { - "sirs_temperature": vitals.temperature < 36.0 or vitals.temperature > 38.3, - "sirs_heart_rate": vitals.heart_rate > 90, - "sirs_respiratory_rate": vitals.respiratory_rate > 20, - "sirs_wbc": bool( - data.lab_results.wbc_count and - (data.lab_results.wbc_count < 4.0 or data.lab_results.wbc_count > 12.0) - ), - "qsofa_altered_mental": data.altered_mental_status, - "qsofa_respiratory": vitals.respiratory_rate >= 22, - "qsofa_hypotension": vitals.systolic_bp <= 100, - "sirs_positive": sirs_score >= 2, - "qsofa_positive": qsofa_score >= 2, - "elevated_lactate": bool( - data.lab_results.lactate_level and - data.lab_results.lactate_level > 2.0 - ) - } - - -# Unit Tests -import pytest - -def test_sepsis_high_risk(): - """Test sepsis screening with high-risk indicators.""" - screening_data = SepsisScreeningRequest( - patient_id="patient-001", - vital_signs=VitalSigns( - temperature=39.5, - heart_rate=120, - respiratory_rate=25, - systolic_bp=95, - oxygen_saturation=92.0 - ), - lab_results=LabResults( - wbc_count=15.0, - lactate_level=3.5 - ), - altered_mental_status=True - ) - - service = SepsisScreeningService() - - # Test SIRS score calculation - sirs_score = service._calculate_sirs_score(screening_data) - assert sirs_score >= 3, "High-risk patient should have SIRS β‰₯3" - - # Test qSOFA score calculation - qsofa_score = service._calculate_qsofa_score(screening_data) - assert qsofa_score >= 2, "High-risk patient should have qSOFA β‰₯2" - - # Test risk score - risk_score = service._calculate_risk_score(sirs_score, qsofa_score, screening_data) - assert risk_score > 0.6, "High-risk patient should have risk score >0.6" - - # Test severity - severity = service._determine_severity(risk_score, sirs_score, qsofa_score) - assert severity in ["high", "critical"], "Should be classified as high/critical" - - -def test_sepsis_low_risk(): - """Test sepsis screening with low-risk indicators.""" - screening_data = SepsisScreeningRequest( - patient_id="patient-002", - vital_signs=VitalSigns( - temperature=37.0, - heart_rate=75, - respiratory_rate=16, - systolic_bp=120, - oxygen_saturation=98.0 - ), - lab_results=LabResults( - wbc_count=7.5, - lactate_level=1.2 - ), - altered_mental_status=False - ) - - service = SepsisScreeningService() - - sirs_score = service._calculate_sirs_score(screening_data) - assert sirs_score == 0, "Low-risk patient should have SIRS = 0" - - qsofa_score = service._calculate_qsofa_score(screening_data) - assert qsofa_score == 0, "Low-risk patient should have qSOFA = 0" - - risk_score = service._calculate_risk_score(sirs_score, qsofa_score, screening_data) - assert risk_score < 0.3, "Low-risk patient should have risk score <0.3" - - severity = service._determine_severity(risk_score, sirs_score, qsofa_score) - assert severity == "low", "Should be classified as low risk" - - -@pytest.mark.asyncio -async def test_sepsis_screening_integration(async_client, tenant_context): - """Integration test for sepsis screening endpoint.""" - response = await async_client.post( - "/api/v1/clinica/sepsis/screen", - json={ - "patient_id": "patient-001", - "vital_signs": { - "temperature": 39.5, - "heart_rate": 120, - "respiratory_rate": 25, - "systolic_bp": 95, - "oxygen_saturation": 92.0 - }, - "lab_results": { - "wbc_count": 15.0, - "lactate_level": 3.5 - }, - "altered_mental_status": True - }, - headers={"X-Tenant-ID": tenant_context["tenant_id"]} - ) - - assert response.status_code == 200 - data = response.json() - - assert "risk_score" in data - assert "severity" in data - assert data["severity"] in ["low", "moderate", "high", "critical"] - assert len(data["recommendations"]) > 0 -``` - -## Additional Use Cases - -### 1. Stroke Risk Assessment (FAST Score) -### 2. Cardiac Risk Stratification (HEART Score) -### 3. Pneumonia Severity Index (PSI/PORT Score) -### 4. Venous Thromboembolism Risk (Wells Score) -### 5. Delirium Screening (CAM-ICU) - -See individual templates for each clinical algorithm. diff --git a/.github/copilot-prompts/database-patterns.md b/.github/copilot-prompts/database-patterns.md deleted file mode 100644 index b7d033f2fb9dde6195a2d1c2776c398f19374d96..0000000000000000000000000000000000000000 --- a/.github/copilot-prompts/database-patterns.md +++ /dev/null @@ -1,772 +0,0 @@ -# Database Design and Migration Patterns for YAZ Care Platform - -## Overview -This guide covers PostgreSQL database design patterns for multi-tenant healthcare applications, including schema design, indexing strategies, migrations with Alembic, and query optimization. - -## Architecture: Schema-Per-Tenant Multi-Tenancy - -### Database Structure -``` -PostgreSQL Database: yaz_care -β”œβ”€β”€ public schema (system tables, shared metadata) -β”‚ β”œβ”€β”€ tenants -β”‚ β”œβ”€β”€ users -β”‚ β”œβ”€β”€ audit_logs -β”‚ └── system_config -β”œβ”€β”€ tenant_{tenant_id} schema (isolated per tenant) -β”‚ β”œβ”€β”€ patients -β”‚ β”œβ”€β”€ encounters -β”‚ β”œβ”€β”€ clinical_notes -β”‚ β”œβ”€β”€ lab_results -β”‚ β”œβ”€β”€ medications -β”‚ └── ... (all clinical data) -└── shared schema (reference data) - β”œβ”€β”€ icd10_codes - β”œβ”€β”€ drug_database - β”œβ”€β”€ clinical_protocols - └── reference_ranges -``` - -## 1. Model Design Patterns - -### Base Model with Tenant Isolation - -```python -from sqlmodel import SQLModel, Field -from datetime import datetime -from typing import Optional -from uuid import uuid4 - -class TenantBaseModel(SQLModel): - """ - Base model for all tenant-specific tables. - - Required Fields: - - id: Primary key (UUID) - - tenant_id: Foreign key to tenants table (indexed) - - created_at: Audit timestamp - - updated_at: Audit timestamp - - created_by: User who created record - - updated_by: User who last updated record - """ - - id: str = Field( - default_factory=lambda: str(uuid4()), - primary_key=True, - description="Unique identifier (UUID)" - ) - - tenant_id: str = Field( - index=True, - nullable=False, - foreign_key="public.tenants.id", - description="Multi-tenant isolation key" - ) - - created_at: datetime = Field( - default_factory=datetime.utcnow, - nullable=False, - description="Record creation timestamp (UTC)" - ) - - updated_at: datetime = Field( - default_factory=datetime.utcnow, - nullable=False, - description="Record last update timestamp (UTC)" - ) - - created_by: str = Field( - nullable=False, - foreign_key="public.users.id", - description="User ID who created this record" - ) - - updated_by: Optional[str] = Field( - default=None, - foreign_key="public.users.id", - description="User ID who last updated this record" - ) - - is_deleted: bool = Field( - default=False, - nullable=False, - description="Soft delete flag (HIPAA retention)" - ) - - deleted_at: Optional[datetime] = Field( - default=None, - description="Soft delete timestamp" - ) - - deleted_by: Optional[str] = Field( - default=None, - foreign_key="public.users.id", - description="User who soft-deleted this record" - ) - -### Example: Patient Model - -```python -from sqlmodel import SQLModel, Field, Relationship -from typing import Optional, List -from datetime import date -from enum import Enum - -class Gender(str, Enum): - """Gender options (HL7 FHIR R4 standard).""" - MALE = "male" - FEMALE = "female" - OTHER = "other" - UNKNOWN = "unknown" - -class Patient(TenantBaseModel, table=True): - """ - Patient demographic and identification information. - - Clinical Context: Central patient registry for all clinical applications - Standards: HL7 FHIR R4 Patient Resource, HIPAA PHI - Security: Contains PHI - all access must be audited - """ - - __tablename__ = "patients" - __table_args__ = ( - {"schema": "clinica"}, # Tenant-specific schema - ) - - # Identifiers - mrn: str = Field( - unique=True, - index=True, - nullable=False, - max_length=50, - description="Medical Record Number (facility-specific)" - ) - - national_id: Optional[str] = Field( - default=None, - max_length=50, - description="National ID number (SSN, passport, etc.) - encrypted" - ) - - # Demographics (PHI) - first_name: str = Field( - nullable=False, - max_length=100, - description="Patient first name" - ) - - middle_name: Optional[str] = Field( - default=None, - max_length=100, - description="Patient middle name" - ) - - last_name: str = Field( - nullable=False, - max_length=100, - description="Patient last name" - ) - - date_of_birth: date = Field( - nullable=False, - description="Date of birth (for age calculation)" - ) - - gender: Gender = Field( - nullable=False, - description="Administrative gender (HL7 FHIR)" - ) - - # Contact Information (PHI) - primary_phone: Optional[str] = Field( - default=None, - max_length=20, - description="Primary contact phone number" - ) - - email: Optional[str] = Field( - default=None, - max_length=255, - description="Email address" - ) - - address_line1: Optional[str] = Field( - default=None, - max_length=255, - description="Street address line 1" - ) - - address_line2: Optional[str] = Field( - default=None, - max_length=255, - description="Street address line 2" - ) - - city: Optional[str] = Field( - default=None, - max_length=100, - description="City" - ) - - state: Optional[str] = Field( - default=None, - max_length=50, - description="State/Province" - ) - - postal_code: Optional[str] = Field( - default=None, - max_length=20, - description="ZIP/Postal code" - ) - - country: str = Field( - default="US", - max_length=2, - description="ISO 3166-1 alpha-2 country code" - ) - - # Clinical Metadata - blood_type: Optional[str] = Field( - default=None, - max_length=10, - description="Blood type (A+, B-, O+, etc.)" - ) - - allergies: Optional[List[str]] = Field( - default=None, - sa_column=Column(JSON), - description="Known allergies (JSON array)" - ) - - # Relationships - encounters: List["Encounter"] = Relationship(back_populates="patient") - lab_results: List["LabResult"] = Relationship(back_populates="patient") - medications: List["Medication"] = Relationship(back_populates="patient") - - # Computed Properties - @property - def age_years(self) -> int: - """Calculate current age in years.""" - today = date.today() - age = today.year - self.date_of_birth.year - if (today.month, today.day) < (self.date_of_birth.month, self.date_of_birth.day): - age -= 1 - return age - - @property - def full_name(self) -> str: - """Return formatted full name.""" - parts = [self.first_name] - if self.middle_name: - parts.append(self.middle_name) - parts.append(self.last_name) - return " ".join(parts) - - class Config: - """Pydantic configuration.""" - json_schema_extra = { - "example": { - "mrn": "MRN-2024-001234", - "first_name": "John", - "last_name": "Doe", - "date_of_birth": "1980-05-15", - "gender": "male", - "primary_phone": "+1-555-0123", - "email": "john.doe@example.com" - } - } - -## 2. Indexing Strategy - -### Required Indexes for Multi-Tenant Tables - -```sql --- Primary key index (automatic) -CREATE UNIQUE INDEX idx_patients_pkey ON clinica.patients(id); - --- Tenant isolation index (CRITICAL - must be on ALL tenant tables) -CREATE INDEX idx_patients_tenant_id ON clinica.patients(tenant_id); - --- Unique business key within tenant -CREATE UNIQUE INDEX idx_patients_tenant_mrn ON clinica.patients(tenant_id, mrn); - --- Foreign key indexes -CREATE INDEX idx_patients_created_by ON clinica.patients(created_by); -CREATE INDEX idx_patients_updated_by ON clinica.patients(updated_by); - --- Search indexes -CREATE INDEX idx_patients_last_name ON clinica.patients(tenant_id, last_name); -CREATE INDEX idx_patients_dob ON clinica.patients(tenant_id, date_of_birth); - --- Soft delete filter -CREATE INDEX idx_patients_active ON clinica.patients(tenant_id, is_deleted) - WHERE is_deleted = false; - --- Composite indexes for common queries -CREATE INDEX idx_patients_search ON clinica.patients(tenant_id, last_name, first_name) - WHERE is_deleted = false; - --- Full-text search (for patient search) -CREATE INDEX idx_patients_fulltext ON clinica.patients - USING gin(to_tsvector('english', first_name || ' ' || last_name)); -``` - -### Index Performance Guidelines - -```python -""" -Index Design Principles: - -1. **Always Index tenant_id**: First column in multi-column indexes -2. **Index Foreign Keys**: For JOIN performance -3. **Composite Indexes**: Order matters - most selective first -4. **Partial Indexes**: Use WHERE clause for filtered queries -5. **Index Cardinality**: High-cardinality columns first -6. **Avoid Over-Indexing**: Each index costs write performance - -Performance Targets: -- Simple queries (indexed): <10ms -- Complex queries (multiple JOINs): <50ms -- Full-table scans: Avoid entirely in production - -Use EXPLAIN ANALYZE to verify: -```sql -EXPLAIN ANALYZE -SELECT * FROM clinica.patients -WHERE tenant_id = 'acme-hospital' - AND last_name = 'Smith' - AND is_deleted = false; -``` -``` - -## 3. Alembic Migration Patterns - -### Migration File Template - -```python -"""Add patients table for Clinica module - -Revision ID: 001_add_patients_table -Revises: -Create Date: 2025-12-24 10:00:00.000000 - -Clinical Context: Central patient registry for demographic and identification data -Standards: HL7 FHIR R4 Patient Resource -""" -from alembic import op -import sqlalchemy as sa -from sqlalchemy.dialects import postgresql -from datetime import datetime - -# revision identifiers -revision = '001_add_patients_table' -down_revision = None -branch_labels = None -depends_on = None - -def upgrade() -> None: - """ - Create patients table with multi-tenant support. - - Checklist: - - [ ] tenant_id column (nullable=False, indexed) - - [ ] Audit timestamps (created_at, updated_at) - - [ ] Audit users (created_by, updated_by) - - [ ] Soft delete (is_deleted, deleted_at, deleted_by) - - [ ] Foreign keys with ON DELETE CASCADE - - [ ] Unique constraints within tenant - - [ ] Indexes for common queries - """ - - # Create clinica schema if not exists - op.execute("CREATE SCHEMA IF NOT EXISTS clinica") - - # Create patients table - op.create_table( - 'patients', - sa.Column('id', sa.String(36), primary_key=True), - sa.Column('tenant_id', sa.String(36), nullable=False), - sa.Column('mrn', sa.String(50), nullable=False), - sa.Column('national_id', sa.String(50), nullable=True), - sa.Column('first_name', sa.String(100), nullable=False), - sa.Column('middle_name', sa.String(100), nullable=True), - sa.Column('last_name', sa.String(100), nullable=False), - sa.Column('date_of_birth', sa.Date(), nullable=False), - sa.Column('gender', sa.String(20), nullable=False), - sa.Column('primary_phone', sa.String(20), nullable=True), - sa.Column('email', sa.String(255), nullable=True), - sa.Column('address_line1', sa.String(255), nullable=True), - sa.Column('address_line2', sa.String(255), nullable=True), - sa.Column('city', sa.String(100), nullable=True), - sa.Column('state', sa.String(50), nullable=True), - sa.Column('postal_code', sa.String(20), nullable=True), - sa.Column('country', sa.String(2), nullable=False, server_default='US'), - sa.Column('blood_type', sa.String(10), nullable=True), - sa.Column('allergies', postgresql.JSON, nullable=True), - sa.Column('created_at', sa.DateTime(), nullable=False, server_default=sa.func.now()), - sa.Column('updated_at', sa.DateTime(), nullable=False, server_default=sa.func.now()), - sa.Column('created_by', sa.String(36), nullable=False), - sa.Column('updated_by', sa.String(36), nullable=True), - sa.Column('is_deleted', sa.Boolean(), nullable=False, server_default='false'), - sa.Column('deleted_at', sa.DateTime(), nullable=True), - sa.Column('deleted_by', sa.String(36), nullable=True), - schema='clinica' - ) - - # Foreign keys - op.create_foreign_key( - 'fk_patients_tenant_id', - 'patients', 'tenants', - ['tenant_id'], ['id'], - source_schema='clinica', - referent_schema='public', - ondelete='CASCADE' - ) - - op.create_foreign_key( - 'fk_patients_created_by', - 'patients', 'users', - ['created_by'], ['id'], - source_schema='clinica', - referent_schema='public' - ) - - # Indexes - op.create_index( - 'idx_patients_tenant_id', - 'patients', - ['tenant_id'], - schema='clinica' - ) - - op.create_index( - 'idx_patients_tenant_mrn', - 'patients', - ['tenant_id', 'mrn'], - unique=True, - schema='clinica' - ) - - op.create_index( - 'idx_patients_last_name', - 'patients', - ['tenant_id', 'last_name'], - schema='clinica' - ) - - op.create_index( - 'idx_patients_active', - 'patients', - ['tenant_id', 'is_deleted'], - schema='clinica', - postgresql_where=sa.text('is_deleted = false') - ) - - # Updated_at trigger - op.execute(""" - CREATE OR REPLACE FUNCTION update_updated_at_column() - RETURNS TRIGGER AS $$ - BEGIN - NEW.updated_at = NOW(); - RETURN NEW; - END; - $$ language 'plpgsql'; - """) - - op.execute(""" - CREATE TRIGGER update_patients_updated_at - BEFORE UPDATE ON clinica.patients - FOR EACH ROW - EXECUTE FUNCTION update_updated_at_column(); - """) - -def downgrade() -> None: - """Rollback patients table creation.""" - op.drop_table('patients', schema='clinica') - op.execute("DROP FUNCTION IF EXISTS update_updated_at_column() CASCADE") -``` - -### Migration Best Practices - -```python -""" -Migration Safety Checklist: - -1. **Backward Compatibility**: - - New columns should be nullable OR have defaults - - Don't drop columns in production (use soft delete) - - Use ALTER TABLE ADD COLUMN instead of DROP/CREATE - -2. **Data Migration**: - - Include data transformation logic - - Test with production-sized datasets - - Use batch processing for large tables - -3. **Rollback Strategy**: - - Always implement downgrade() - - Test rollback before deploying - - Keep migrations atomic - -4. **Performance**: - - Create indexes CONCURRENTLY in production - - Avoid long-running transactions - - Test migration time on production-sized data - -5. **Multi-Tenancy**: - - Apply schema changes to ALL tenant schemas - - Verify tenant isolation after migration - - Test with multiple tenants - -Example: Safe Column Addition -""" - -def upgrade(): - # Add column with default (fast, no table rewrite) - op.add_column( - 'patients', - sa.Column('preferred_language', sa.String(10), nullable=True), - schema='clinica' - ) - - # Backfill data in batches (for large tables) - connection = op.get_bind() - connection.execute(""" - UPDATE clinica.patients - SET preferred_language = 'en' - WHERE preferred_language IS NULL - """) - - # Make NOT NULL after backfill - op.alter_column( - 'patients', - 'preferred_language', - nullable=False, - schema='clinica' - ) -``` - -## 4. Query Optimization Patterns - -### Repository Pattern with Optimized Queries - -```python -from typing import List, Optional -from sqlalchemy.ext.asyncio import AsyncSession -from sqlalchemy import select, and_, func -from sqlalchemy.orm import selectinload -import structlog - -logger = structlog.get_logger() - -class PatientRepository: - """ - Repository for patient data access with optimized queries. - - Performance: All queries <50ms for typical loads - Multi-Tenancy: All queries auto-filter by tenant_id - """ - - def __init__(self, session: AsyncSession, tenant_id: str): - self.session = session - self.tenant_id = tenant_id - - async def get_by_id(self, patient_id: str) -> Optional[Patient]: - """ - Get patient by ID (tenant-scoped). - - Performance: <10ms (indexed lookup) - """ - stmt = select(Patient).where( - and_( - Patient.tenant_id == self.tenant_id, - Patient.id == patient_id, - Patient.is_deleted == False - ) - ) - - result = await self.session.execute(stmt) - return result.scalar_one_or_none() - - async def get_by_mrn(self, mrn: str) -> Optional[Patient]: - """ - Get patient by MRN (Medical Record Number). - - Performance: <10ms (unique index lookup) - """ - stmt = select(Patient).where( - and_( - Patient.tenant_id == self.tenant_id, - Patient.mrn == mrn, - Patient.is_deleted == False - ) - ) - - result = await self.session.execute(stmt) - return result.scalar_one_or_none() - - async def search_by_name( - self, - last_name: str, - first_name: Optional[str] = None, - limit: int = 50 - ) -> List[Patient]: - """ - Search patients by name. - - Performance: <50ms (composite index on tenant_id + last_name + first_name) - """ - conditions = [ - Patient.tenant_id == self.tenant_id, - Patient.last_name.ilike(f"{last_name}%"), - Patient.is_deleted == False - ] - - if first_name: - conditions.append(Patient.first_name.ilike(f"{first_name}%")) - - stmt = ( - select(Patient) - .where(and_(*conditions)) - .order_by(Patient.last_name, Patient.first_name) - .limit(limit) - ) - - result = await self.session.execute(stmt) - return result.scalars().all() - - async def get_with_encounters( - self, - patient_id: str - ) -> Optional[Patient]: - """ - Get patient with encounters (eager loading to avoid N+1). - - Performance: <100ms (single query with JOIN) - """ - stmt = ( - select(Patient) - .options(selectinload(Patient.encounters)) # Eager load - .where( - and_( - Patient.tenant_id == self.tenant_id, - Patient.id == patient_id, - Patient.is_deleted == False - ) - ) - ) - - result = await self.session.execute(stmt) - return result.scalar_one_or_none() - - async def count_active_patients(self) -> int: - """ - Count active patients for tenant. - - Performance: <20ms (index-only scan) - """ - stmt = select(func.count(Patient.id)).where( - and_( - Patient.tenant_id == self.tenant_id, - Patient.is_deleted == False - ) - ) - - result = await self.session.execute(stmt) - return result.scalar_one() - - async def batch_create( - self, - patients: List[Patient], - user_id: str - ) -> List[Patient]: - """ - Batch create patients (optimized for ETL/import). - - Performance: ~1000 records per second - """ - # Set audit fields - for patient in patients: - patient.tenant_id = self.tenant_id - patient.created_by = user_id - - # Bulk insert - self.session.add_all(patients) - await self.session.flush() - - logger.info( - "patients_batch_created", - tenant_id=self.tenant_id, - count=len(patients), - user_id=user_id - ) - - return patients -``` - -### Query Performance Monitoring - -```python -import time -from functools import wraps - -def monitor_query_performance(func): - """ - Decorator to monitor database query performance. - - Logs slow queries (>50ms) for optimization review. - """ - @wraps(func) - async def wrapper(*args, **kwargs): - start = time.time() - - try: - result = await func(*args, **kwargs) - duration_ms = (time.time() - start) * 1000 - - if duration_ms > 50: - logger.warning( - "slow_query_detected", - function=func.__name__, - duration_ms=duration_ms, - args=str(args)[:100], # Truncate for logging - ) - - return result - finally: - duration_ms = (time.time() - start) * 1000 - logger.info( - "query_completed", - function=func.__name__, - duration_ms=duration_ms - ) - - return wrapper - -# Usage -class OptimizedRepository: - @monitor_query_performance - async def get_patient(self, patient_id: str): - # Query implementation - pass -``` - -## Summary - -Key database design principles: -- βœ… Always include tenant_id in multi-tenant tables (indexed, non-nullable) -- βœ… Use schema-per-tenant for strong isolation -- βœ… Index foreign keys and common query columns -- βœ… Implement soft delete for HIPAA retention -- βœ… Use audit columns (created_at, updated_at, created_by, updated_by) -- βœ… Test migrations with production-sized data -- βœ… Monitor query performance and optimize slow queries -- βœ… Use repository pattern for query encapsulation -- βœ… Implement proper cascade deletes -- βœ… Document clinical context in table/column comments - -**Performance Targets**: -- Indexed lookups: <10ms -- Simple queries: <50ms -- Complex queries with JOINs: <200ms -- Batch operations: 1000+ records/second diff --git a/.github/copilot-prompts/multi-tenancy-patterns.md b/.github/copilot-prompts/multi-tenancy-patterns.md deleted file mode 100644 index ae2fccacae9d45aa94d8d72ff80841a49e9412d9..0000000000000000000000000000000000000000 --- a/.github/copilot-prompts/multi-tenancy-patterns.md +++ /dev/null @@ -1,725 +0,0 @@ -# Multi-Tenancy Implementation Patterns - -## Overview -YAZ Care Platform uses **schema-per-tenant** isolation in PostgreSQL for strong data separation with shared infrastructure efficiency. - -## Architecture Pattern - -### Tenant Isolation Strategy -``` -Database: PostgreSQL -β”œβ”€β”€ public schema (shared metadata, system tables) -β”œβ”€β”€ tenant_acme_hospital schema -β”‚ β”œβ”€β”€ patients -β”‚ β”œβ”€β”€ encounters -β”‚ β”œβ”€β”€ clinical_notes -β”‚ └── ... -β”œβ”€β”€ tenant_city_clinic schema -β”‚ β”œβ”€β”€ patients -β”‚ β”œβ”€β”€ encounters -β”‚ └── ... -└── ... -``` - -## Template: Add Multi-Tenant Support to Existing Endpoint - -### Prompt Structure -``` -Add multi-tenant support to [ENDPOINT_NAME] in [APP_NAME] application. - -Current Implementation: -[Paste current code without tenant isolation] - -Required Changes: -1. Extract tenant_id from request context (X-Tenant-ID header or JWT) -2. Validate tenant access rights (user belongs to tenant) -3. Apply tenant schema filter to all database queries -4. Add tenant_id prefix to all cache keys -5. Verify no cross-tenant data leakage in responses -6. Add audit logging with tenant_id -7. Add integration test for tenant isolation - -Security Checklist: -- [ ] tenant_id extracted from authenticated JWT token -- [ ] Database queries use SET search_path to tenant schema -- [ ] Cache keys prefixed: f"tenant:{tenant_id}:..." -- [ ] Error messages don't leak other tenant info -- [ ] Audit log includes tenant_id for all operations -- [ ] Test verifies tenant A cannot access tenant B data -- [ ] No raw SQL queries without tenant filter - -Performance Impact: -- Schema switching adds ~5ms overhead per request -- Cache hit rate should remain >80% -- No N+1 query patterns introduced -- Connection pool shared across tenants - -Reference: Sprint 29 multi-tenancy tests (6/6 passing) -``` - -## Implementation Pattern: Database Layer - -### 1. Tenant Context Middleware -```python -from __future__ import annotations -from typing import Optional -from fastapi import Request, HTTPException, status -from sqlalchemy import text -from sqlalchemy.ext.asyncio import AsyncSession -import structlog - -logger = structlog.get_logger() - - -class TenantContext: - """ - Multi-tenant context for request isolation. - - Manages tenant identification, validation, and database schema switching. - Ensures no cross-tenant data access. - """ - - def __init__(self, tenant_id: str, user_id: str): - self.tenant_id = tenant_id - self.user_id = user_id - self.schema_name = f"tenant_{tenant_id.replace('-', '_')}" - - @classmethod - async def from_request(cls, request: Request) -> TenantContext: - """ - Extract and validate tenant context from request. - - Args: - request: FastAPI request object - - Returns: - TenantContext with validated tenant_id - - Raises: - HTTPException: If tenant validation fails - """ - # Extract from header (API calls) - tenant_id = request.headers.get("X-Tenant-ID") - - # If not in header, extract from JWT token - if not tenant_id: - user = getattr(request.state, "user", None) - if user and hasattr(user, "tenant_id"): - tenant_id = user.tenant_id - - if not tenant_id: - logger.error("missing_tenant_id", path=request.url.path) - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="Tenant ID is required (X-Tenant-ID header or JWT)" - ) - - # Extract user_id for audit - user_id = getattr(request.state, "user_id", "unknown") - - # Validate tenant exists and user has access - await cls._validate_tenant_access(tenant_id, user_id) - - logger.info( - "tenant_context_created", - tenant_id=tenant_id, - user_id=user_id - ) - - return cls(tenant_id=tenant_id, user_id=user_id) - - @staticmethod - async def _validate_tenant_access(tenant_id: str, user_id: str) -> None: - """ - Validate user has access to tenant. - - Args: - tenant_id: Tenant identifier - user_id: User identifier - - Raises: - HTTPException: If validation fails - """ - # TODO: Check user_tenants table - # For now, assume valid if tenant_id provided - pass - - async def set_search_path(self, db: AsyncSession) -> None: - """ - Set PostgreSQL search_path to tenant schema. - - CRITICAL: Must be called before any database queries - to ensure tenant isolation. - - Args: - db: Database session - """ - await db.execute( - text(f"SET search_path TO {self.schema_name}, public") - ) - logger.debug( - "search_path_set", - tenant_id=self.tenant_id, - schema=self.schema_name - ) - - -# FastAPI Dependency -async def get_tenant_context(request: Request) -> TenantContext: - """FastAPI dependency for tenant context injection.""" - return await TenantContext.from_request(request) -``` - -### 2. Multi-Tenant Repository Pattern - -```python -from __future__ import annotations -from typing import List, Optional, Generic, TypeVar -from sqlalchemy import select -from sqlalchemy.ext.asyncio import AsyncSession -from sqlalchemy.orm import DeclarativeMeta -import structlog - -logger = structlog.get_logger() - -T = TypeVar('T', bound=DeclarativeMeta) - - -class TenantRepository(Generic[T]): - """ - Base repository with multi-tenant isolation. - - All database operations automatically filtered by tenant schema. - """ - - def __init__( - self, - db: AsyncSession, - tenant_context: TenantContext, - model: type[T] - ): - self.db = db - self.tenant_context = tenant_context - self.model = model - - async def _ensure_tenant_schema(self) -> None: - """Ensure database search_path is set to tenant schema.""" - await self.tenant_context.set_search_path(self.db) - - async def get_by_id(self, id: str) -> Optional[T]: - """ - Get entity by ID within tenant scope. - - Args: - id: Entity identifier - - Returns: - Entity if found in tenant schema, None otherwise - """ - await self._ensure_tenant_schema() - - result = await self.db.execute( - select(self.model).where(self.model.id == id) - ) - entity = result.scalar_one_or_none() - - logger.debug( - "entity_retrieved", - tenant_id=self.tenant_context.tenant_id, - model=self.model.__name__, - id=id, - found=entity is not None - ) - - return entity - - async def list( - self, - skip: int = 0, - limit: int = 100, - filters: Optional[dict] = None - ) -> List[T]: - """ - List entities within tenant scope. - - Args: - skip: Pagination offset - limit: Max results - filters: Additional filters - - Returns: - List of entities in tenant schema - """ - await self._ensure_tenant_schema() - - query = select(self.model) - - # Apply filters - if filters: - for key, value in filters.items(): - if hasattr(self.model, key): - query = query.where(getattr(self.model, key) == value) - - query = query.offset(skip).limit(limit) - - result = await self.db.execute(query) - entities = result.scalars().all() - - logger.info( - "entities_listed", - tenant_id=self.tenant_context.tenant_id, - model=self.model.__name__, - count=len(entities), - skip=skip, - limit=limit - ) - - return list(entities) - - async def create(self, entity: T) -> T: - """ - Create entity in tenant schema. - - Args: - entity: Entity to create - - Returns: - Created entity with ID - """ - await self._ensure_tenant_schema() - - self.db.add(entity) - await self.db.flush() - await self.db.refresh(entity) - - logger.info( - "entity_created", - tenant_id=self.tenant_context.tenant_id, - model=self.model.__name__, - entity_id=getattr(entity, 'id', None) - ) - - return entity - - async def update(self, entity: T) -> T: - """ - Update entity in tenant schema. - - Args: - entity: Entity with updated fields - - Returns: - Updated entity - """ - await self._ensure_tenant_schema() - - await self.db.flush() - await self.db.refresh(entity) - - logger.info( - "entity_updated", - tenant_id=self.tenant_context.tenant_id, - model=self.model.__name__, - entity_id=getattr(entity, 'id', None) - ) - - return entity - - async def delete(self, id: str) -> bool: - """ - Delete entity from tenant schema. - - Args: - id: Entity identifier - - Returns: - True if deleted, False if not found - """ - await self._ensure_tenant_schema() - - entity = await self.get_by_id(id) - if not entity: - return False - - await self.db.delete(entity) - await self.db.flush() - - logger.info( - "entity_deleted", - tenant_id=self.tenant_context.tenant_id, - model=self.model.__name__, - entity_id=id - ) - - return True -``` - -### 3. Multi-Tenant Cache Pattern - -```python -from __future__ import annotations -from typing import Optional, Any -from redis.asyncio import Redis -import json -import structlog - -logger = structlog.get_logger() - - -class TenantCache: - """ - Multi-tenant Redis cache with automatic key prefixing. - - Ensures cache isolation between tenants. - """ - - def __init__(self, redis: Redis, tenant_context: TenantContext): - self.redis = redis - self.tenant_context = tenant_context - - def _make_key(self, key: str) -> str: - """ - Create tenant-prefixed cache key. - - Args: - key: Base cache key - - Returns: - Prefixed key: "tenant:{tenant_id}:{key}" - """ - return f"tenant:{self.tenant_context.tenant_id}:{key}" - - async def get(self, key: str) -> Optional[Any]: - """ - Get value from tenant cache. - - Args: - key: Cache key (will be prefixed) - - Returns: - Cached value or None - """ - prefixed_key = self._make_key(key) - value = await self.redis.get(prefixed_key) - - if value: - logger.debug( - "cache_hit", - tenant_id=self.tenant_context.tenant_id, - key=key - ) - return json.loads(value) - - logger.debug( - "cache_miss", - tenant_id=self.tenant_context.tenant_id, - key=key - ) - return None - - async def set( - self, - key: str, - value: Any, - ttl: int = 3600 - ) -> None: - """ - Set value in tenant cache. - - Args: - key: Cache key (will be prefixed) - value: Value to cache (JSON-serializable) - ttl: Time to live in seconds - """ - prefixed_key = self._make_key(key) - await self.redis.setex( - prefixed_key, - ttl, - json.dumps(value) - ) - - logger.debug( - "cache_set", - tenant_id=self.tenant_context.tenant_id, - key=key, - ttl=ttl - ) - - async def delete(self, key: str) -> None: - """Delete value from tenant cache.""" - prefixed_key = self._make_key(key) - await self.redis.delete(prefixed_key) - - logger.debug( - "cache_deleted", - tenant_id=self.tenant_context.tenant_id, - key=key - ) - - async def clear_tenant_cache(self) -> int: - """ - Clear all cache entries for current tenant. - - Returns: - Number of keys deleted - """ - pattern = self._make_key("*") - keys = [] - async for key in self.redis.scan_iter(match=pattern): - keys.append(key) - - if keys: - deleted = await self.redis.delete(*keys) - else: - deleted = 0 - - logger.info( - "tenant_cache_cleared", - tenant_id=self.tenant_context.tenant_id, - keys_deleted=deleted - ) - - return deleted -``` - -### 4. Multi-Tenant API Endpoint Pattern - -```python -from __future__ import annotations -from fastapi import APIRouter, Depends, HTTPException, status -from sqlalchemy.ext.asyncio import AsyncSession -from typing import List -import structlog - -from src.infrastructure.database import get_db -from src.core.models.patient import Patient -from src.core.schemas.patient import PatientCreate, PatientResponse - -logger = structlog.get_logger() -router = APIRouter(prefix="/api/v1/patients", tags=["patients"]) - - -@router.post("/", response_model=PatientResponse, status_code=status.HTTP_201_CREATED) -async def create_patient( - patient_data: PatientCreate, - tenant_context: TenantContext = Depends(get_tenant_context), - db: AsyncSession = Depends(get_db) -): - """ - Create new patient in tenant scope. - - Multi-Tenancy: Patient created in tenant-specific schema. - Security: Requires valid JWT with tenant_id. - Audit: All operations logged with tenant_id and user_id. - """ - logger.info( - "patient_create_started", - tenant_id=tenant_context.tenant_id, - user_id=tenant_context.user_id - ) - - # Create repository with tenant context - repo = TenantRepository(db, tenant_context, Patient) - - # Create patient entity - patient = Patient(**patient_data.dict()) - patient = await repo.create(patient) - - await db.commit() - - logger.info( - "patient_created", - tenant_id=tenant_context.tenant_id, - patient_id=patient.id - ) - - return PatientResponse.from_orm(patient) - - -@router.get("/{patient_id}", response_model=PatientResponse) -async def get_patient( - patient_id: str, - tenant_context: TenantContext = Depends(get_tenant_context), - db: AsyncSession = Depends(get_db) -): - """ - Get patient by ID within tenant scope. - - Multi-Tenancy: Only returns patient if in same tenant schema. - Returns 404 if patient not found OR in different tenant. - """ - repo = TenantRepository(db, tenant_context, Patient) - patient = await repo.get_by_id(patient_id) - - if not patient: - logger.warning( - "patient_not_found", - tenant_id=tenant_context.tenant_id, - patient_id=patient_id - ) - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail="Patient not found" - ) - - return PatientResponse.from_orm(patient) - - -@router.get("/", response_model=List[PatientResponse]) -async def list_patients( - skip: int = 0, - limit: int = 100, - tenant_context: TenantContext = Depends(get_tenant_context), - db: AsyncSession = Depends(get_db) -): - """ - List all patients in tenant scope. - - Multi-Tenancy: Only returns patients from current tenant schema. - """ - repo = TenantRepository(db, tenant_context, Patient) - patients = await repo.list(skip=skip, limit=limit) - - return [PatientResponse.from_orm(p) for p in patients] -``` - -## Integration Tests - -```python -import pytest -from httpx import AsyncClient - - -@pytest.mark.integration -async def test_multi_tenant_isolation(async_client: AsyncClient): - """ - Critical test: Verify tenant A cannot access tenant B data. - - This is the most important multi-tenancy test - ensures - strong data isolation between tenants. - """ - # Create patient in tenant A - response_a = await async_client.post( - "/api/v1/patients", - json={ - "mrn": "MRN-A-001", - "first_name": "Alice", - "last_name": "Smith", - "date_of_birth": "1980-01-01" - }, - headers={"X-Tenant-ID": "tenant-a"} - ) - assert response_a.status_code == 201 - patient_id = response_a.json()["id"] - - # Attempt to access from tenant B (should fail) - response_b = await async_client.get( - f"/api/v1/patients/{patient_id}", - headers={"X-Tenant-ID": "tenant-b"} - ) - - # Should return 404, not 403 (don't leak existence) - assert response_b.status_code == 404 - assert "not found" in response_b.json()["detail"].lower() - - -@pytest.mark.integration -async def test_tenant_list_isolation(async_client: AsyncClient): - """Verify list operations only return tenant-specific data.""" - # Create patients in both tenants - await async_client.post( - "/api/v1/patients", - json={"mrn": "MRN-A-001", "first_name": "Alice", "last_name": "A", "date_of_birth": "1980-01-01"}, - headers={"X-Tenant-ID": "tenant-a"} - ) - await async_client.post( - "/api/v1/patients", - json={"mrn": "MRN-B-001", "first_name": "Bob", "last_name": "B", "date_of_birth": "1985-01-01"}, - headers={"X-Tenant-ID": "tenant-b"} - ) - - # List for tenant A - response_a = await async_client.get( - "/api/v1/patients", - headers={"X-Tenant-ID": "tenant-a"} - ) - patients_a = response_a.json() - - # List for tenant B - response_b = await async_client.get( - "/api/v1/patients", - headers={"X-Tenant-ID": "tenant-b"} - ) - patients_b = response_b.json() - - # Verify separation - assert len(patients_a) == 1 - assert len(patients_b) == 1 - assert patients_a[0]["mrn"] == "MRN-A-001" - assert patients_b[0]["mrn"] == "MRN-B-001" - - -@pytest.mark.integration -async def test_cache_isolation(async_client: AsyncClient, redis_client): - """Verify cache keys are properly tenant-prefixed.""" - # Create patient in tenant A - response = await async_client.post( - "/api/v1/patients", - json={"mrn": "MRN-001", "first_name": "Test", "last_name": "User", "date_of_birth": "1990-01-01"}, - headers={"X-Tenant-ID": "tenant-a"} - ) - patient_id = response.json()["id"] - - # Check cache keys - keys = [] - async for key in redis_client.scan_iter(match="tenant:tenant-a:*"): - keys.append(key.decode()) - - # Should have tenant-prefixed keys - assert any("tenant:tenant-a:" in key for key in keys) - - # Should NOT have keys for other tenants - async for key in redis_client.scan_iter(match="tenant:tenant-b:*"): - pytest.fail("Found tenant B cache keys when only tenant A was used") -``` - -## Performance Considerations - -### Schema Switching Overhead -- **Cost**: ~5ms per request for `SET search_path` -- **Mitigation**: Connection pooling per tenant (if needed) -- **Monitoring**: Track p95 latency by tenant - -### Cache Hit Rates -- **Target**: >80% cache hit rate per tenant -- **Key Strategy**: Prefix all keys with `tenant:{tenant_id}:` -- **Monitoring**: Track hit/miss rates per tenant - -### Database Connections -- **Current**: Shared connection pool (100 connections) -- **Scaling**: Consider per-tenant pools at 1000+ tenants -- **Monitoring**: Track connection usage by tenant - -## Migration to Multi-Tenancy - -### Checklist for Adding Tenant Support -- [ ] Add `TenantContext` dependency to endpoint -- [ ] Use `TenantRepository` for all database operations -- [ ] Prefix cache keys with tenant_id -- [ ] Add integration test for tenant isolation -- [ ] Verify no raw SQL without tenant filter -- [ ] Update API documentation -- [ ] Add audit logging with tenant_id -- [ ] Performance test with multiple tenants - -### Common Pitfalls -1. **Forgetting search_path**: Always call `set_search_path()` before queries -2. **Cache key collisions**: Always prefix with tenant_id -3. **Leaking existence**: Return 404, not 403 for missing cross-tenant resources -4. **Background jobs**: Ensure async tasks include tenant_id -5. **Aggregations**: Verify tenant filter applied to all joins - -## Reference -- Sprint 29: Multi-tenancy implementation (6/6 tests passing) -- Database schema per tenant pattern -- PostgreSQL search_path documentation diff --git a/.github/copilot-prompts/observability-patterns.md b/.github/copilot-prompts/observability-patterns.md deleted file mode 100644 index 5eb4574afdcbb43180d0dbdcce874cb5eeea3bfb..0000000000000000000000000000000000000000 --- a/.github/copilot-prompts/observability-patterns.md +++ /dev/null @@ -1,738 +0,0 @@ -# Observability Patterns - Tracing, Metrics, and Logging - -## Overview -YAZ Care Platform uses OpenTelemetry for distributed tracing, Prometheus for metrics, and structured logging with ELK stack. - -**Sprint 32 Implementation**: 12,300 LOC added for comprehensive observability - -## Architecture - -``` -Request Flow: -Client β†’ API Gateway β†’ FastAPI App β†’ Service Layer β†’ Database - ↓ ↓ ↓ ↓ - Traces Traces Traces Traces - Logs Logs Logs Logs - Metrics Metrics Metrics Metrics - ↓ ↓ ↓ ↓ - Jaeger Prometheus Elasticsearch - ↓ ↓ ↓ - Grafana (unified dashboards) -``` - -## Template: Add Full Observability to Service - -### Prompt Structure -``` -Add comprehensive observability to [SERVICE_NAME] in [APP_NAME]. - -Requirements: -1. Distributed Tracing (OpenTelemetry) - - Create span for each operation - - Add clinical/business context attributes - - Propagate trace_id to all downstream calls - - Handle async operations properly - -2. Structured Logging - Required fields: - - timestamp (ISO 8601) - - log_level (DEBUG/INFO/WARNING/ERROR) - - trace_id (from OpenTelemetry) - - tenant_id (multi-tenant context) - - user_id (audit trail) - - component (app name) - - message (human-readable) - - context (structured data) - -3. Metrics (Prometheus) - - Request counter by endpoint and status - - Latency histogram (p50/p95/p99) - - Error rate counter - - Healthcare-specific metrics - -4. Performance Target: <200ms p95 - -Reference: Sprint 32 observability implementation -``` - -## Implementation Pattern - -### 1. Distributed Tracing with OpenTelemetry - -```python -from __future__ import annotations -from typing import Optional, Dict, Any -from opentelemetry import trace -from opentelemetry.trace import Status, StatusCode -from opentelemetry.sdk.trace import TracerProvider -from opentelemetry.sdk.trace.export import BatchSpanProcessor -from opentelemetry.exporter.jaeger.thrift import JaegerExporter -from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor -from opentelemetry.instrumentation.sqlalchemy import SQLAlchemyInstrumentor -from opentelemetry.instrumentation.redis import RedisInstrumentor -import structlog - -logger = structlog.get_logger() - - -def setup_tracing(service_name: str = "yaz-care-platform"): - """ - Initialize OpenTelemetry distributed tracing. - - Exports spans to Jaeger for visualization and analysis. - """ - # Configure Jaeger exporter - jaeger_exporter = JaegerExporter( - agent_host_name="localhost", - agent_port=6831, - ) - - # Set up tracer provider - provider = TracerProvider() - processor = BatchSpanProcessor(jaeger_exporter) - provider.add_span_processor(processor) - - trace.set_tracer_provider(provider) - - logger.info("tracing_initialized", service_name=service_name) - - -def instrument_app(app): - """ - Instrument FastAPI application for automatic tracing. - - Args: - app: FastAPI application instance - """ - # Instrument FastAPI - FastAPIInstrumentor.instrument_app(app) - - # Instrument SQLAlchemy - SQLAlchemyInstrumentor().instrument() - - # Instrument Redis - RedisInstrumentor().instrument() - - logger.info("app_instrumented") - - -# Service-level tracing pattern -tracer = trace.get_tracer(__name__) - - -class ClinicalService: - """Example service with comprehensive tracing.""" - - async def perform_clinical_assessment( - self, - tenant_id: str, - user_id: str, - patient_id: str, - assessment_data: Dict[str, Any] - ) -> Dict[str, Any]: - """ - Clinical assessment with distributed tracing. - - Creates spans for each major operation: - - Overall assessment - - Data validation - - Risk calculation - - Database operations - - Cache operations - """ - with tracer.start_as_current_span("clinical_assessment") as span: - # Add clinical context to span - span.set_attribute("tenant.id", tenant_id) - span.set_attribute("user.id", user_id) - span.set_attribute("patient.id", patient_id) - span.set_attribute("assessment.type", assessment_data.get("type")) - span.set_attribute("service.name", "clinica") - - try: - # Validation span - with tracer.start_as_current_span("validate_input") as validation_span: - validation_span.set_attribute("fields_count", len(assessment_data)) - validated_data = await self._validate_assessment(assessment_data) - validation_span.set_status(Status(StatusCode.OK)) - - # Risk calculation span - with tracer.start_as_current_span("calculate_risk") as risk_span: - risk_span.set_attribute("algorithm", "topsis") - risk_score = await self._calculate_risk(validated_data) - risk_span.set_attribute("risk.score", risk_score) - risk_span.set_attribute("risk.severity", self._classify_risk(risk_score)) - risk_span.set_status(Status(StatusCode.OK)) - - # Database operation span - with tracer.start_as_current_span("save_assessment") as db_span: - db_span.set_attribute("db.system", "postgresql") - db_span.set_attribute("db.operation", "insert") - db_span.set_attribute("db.table", "clinical_assessments") - assessment_id = await self._save_assessment( - tenant_id, - patient_id, - validated_data, - risk_score - ) - db_span.set_attribute("assessment.id", assessment_id) - db_span.set_status(Status(StatusCode.OK)) - - # Cache operation span - with tracer.start_as_current_span("cache_result") as cache_span: - cache_span.set_attribute("cache.system", "redis") - cache_span.set_attribute("cache.operation", "set") - await self._cache_result(tenant_id, patient_id, risk_score) - cache_span.set_status(Status(StatusCode.OK)) - - # Success - span.set_attribute("result.status", "success") - span.set_status(Status(StatusCode.OK)) - - return { - "assessment_id": assessment_id, - "risk_score": risk_score, - "severity": self._classify_risk(risk_score) - } - - except Exception as e: - # Record error in span - span.set_status(Status(StatusCode.ERROR, str(e))) - span.record_exception(e) - logger.error( - "clinical_assessment_failed", - tenant_id=tenant_id, - patient_id=patient_id, - error=str(e), - trace_id=format(span.get_span_context().trace_id, '032x') - ) - raise - - async def _validate_assessment(self, data: Dict[str, Any]) -> Dict[str, Any]: - """Validation logic.""" - # Implementation - return data - - async def _calculate_risk(self, data: Dict[str, Any]) -> float: - """Risk calculation logic.""" - # Implementation - return 0.75 - - def _classify_risk(self, score: float) -> str: - """Risk classification.""" - if score >= 0.8: - return "critical" - elif score >= 0.6: - return "high" - elif score >= 0.4: - return "moderate" - else: - return "low" - - async def _save_assessment( - self, - tenant_id: str, - patient_id: str, - data: Dict[str, Any], - risk_score: float - ) -> str: - """Save to database.""" - # Implementation - return "assessment-123" - - async def _cache_result( - self, - tenant_id: str, - patient_id: str, - risk_score: float - ) -> None: - """Cache result.""" - # Implementation - pass -``` - -### 2. Structured Logging - -```python -import structlog -import logging -import sys -from datetime import datetime -from opentelemetry import trace - - -def setup_structured_logging(): - """ - Configure structured logging with required fields. - - Outputs JSON logs for ELK stack ingestion. - """ - structlog.configure( - processors=[ - structlog.contextvars.merge_contextvars, - structlog.stdlib.filter_by_level, - structlog.stdlib.add_logger_name, - structlog.stdlib.add_log_level, - structlog.processors.TimeStamper(fmt="iso"), - structlog.processors.StackInfoRenderer(), - structlog.processors.format_exc_info, - structlog.processors.UnicodeDecoder(), - structlog.processors.JSONRenderer() - ], - wrapper_class=structlog.stdlib.BoundLogger, - context_class=dict, - logger_factory=structlog.stdlib.LoggerFactory(), - cache_logger_on_first_use=True, - ) - - # Configure standard logging - logging.basicConfig( - format="%(message)s", - stream=sys.stdout, - level=logging.INFO, - ) - - -# Usage pattern -logger = structlog.get_logger() - - -class ClinicalWorkflowLogger: - """ - Logger wrapper for clinical workflows. - - Automatically includes required context fields. - """ - - def __init__( - self, - tenant_id: str, - user_id: str, - component: str - ): - self.logger = logger.bind( - tenant_id=tenant_id, - user_id=user_id, - component=component - ) - - def _add_trace_context(self) -> Dict[str, str]: - """Add OpenTelemetry trace context to log.""" - span = trace.get_current_span() - if span.is_recording(): - ctx = span.get_span_context() - return { - "trace_id": format(ctx.trace_id, '032x'), - "span_id": format(ctx.span_id, '016x') - } - return {} - - def info(self, event: str, **kwargs): - """Log info event with trace context.""" - self.logger.info(event, **{**kwargs, **self._add_trace_context()}) - - def warning(self, event: str, **kwargs): - """Log warning event with trace context.""" - self.logger.warning(event, **{**kwargs, **self._add_trace_context()}) - - def error(self, event: str, **kwargs): - """Log error event with trace context.""" - self.logger.error(event, **{**kwargs, **self._add_trace_context()}) - - def debug(self, event: str, **kwargs): - """Log debug event with trace context.""" - self.logger.debug(event, **{**kwargs, **self._add_trace_context()}) - - -# Usage example -async def clinical_decision_workflow(tenant_id: str, user_id: str): - """Example workflow with structured logging.""" - log = ClinicalWorkflowLogger( - tenant_id=tenant_id, - user_id=user_id, - component="clinica" - ) - - log.info( - "clinical_decision_started", - patient_id="patient-123", - decision_type="sepsis_screening" - ) - - try: - # Workflow logic - result = await perform_screening() - - log.info( - "clinical_decision_completed", - patient_id="patient-123", - risk_score=result["risk_score"], - severity=result["severity"], - duration_ms=123 - ) - - except Exception as e: - log.error( - "clinical_decision_failed", - patient_id="patient-123", - error=str(e), - error_type=type(e).__name__ - ) - raise - - -# Sample log output (JSON): -# { -# "event": "clinical_decision_started", -# "timestamp": "2025-12-21T10:30:00.123456Z", -# "level": "info", -# "tenant_id": "acme-hospital", -# "user_id": "dr.smith@acme.com", -# "component": "clinica", -# "patient_id": "patient-123", -# "decision_type": "sepsis_screening", -# "trace_id": "a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6", -# "span_id": "a1b2c3d4e5f6g7h8" -# } -``` - -### 3. Metrics with Prometheus - -```python -from __future__ import annotations -from prometheus_client import Counter, Histogram, Gauge, Info -from typing import Callable -from functools import wraps -import time - - -# Define metrics -api_requests_total = Counter( - 'api_requests_total', - 'Total API requests', - ['endpoint', 'method', 'status', 'tenant_id'] -) - -api_request_duration_seconds = Histogram( - 'api_request_duration_seconds', - 'API request latency', - ['endpoint', 'method', 'tenant_id'], - buckets=(0.01, 0.025, 0.05, 0.075, 0.1, 0.15, 0.2, 0.3, 0.5, 0.75, 1.0, 2.5, 5.0) -) - -api_errors_total = Counter( - 'api_errors_total', - 'Total API errors', - ['endpoint', 'method', 'error_type', 'tenant_id'] -) - -# Healthcare-specific metrics -bed_occupancy_rate = Gauge( - 'bed_occupancy_rate', - 'Current bed occupancy percentage', - ['tenant_id', 'facility_id', 'unit_type'] -) - -or_utilization_rate = Gauge( - 'or_utilization_rate', - 'Operating room utilization percentage', - ['tenant_id', 'facility_id', 'or_number'] -) - -lab_turnaround_time_seconds = Histogram( - 'lab_turnaround_time_seconds', - 'Lab test turnaround time', - ['tenant_id', 'test_type', 'priority'], - buckets=(300, 600, 900, 1800, 3600, 7200, 14400, 28800) # 5min to 8hr -) - -clinical_decisions_total = Counter( - 'clinical_decisions_total', - 'Clinical decision support invocations', - ['tenant_id', 'decision_type', 'severity'] -) - -sepsis_screenings_total = Counter( - 'sepsis_screenings_total', - 'Sepsis screening counts', - ['tenant_id', 'severity', 'positive'] -) - - -# Decorator for automatic metrics -def track_api_metrics(endpoint: str): - """ - Decorator to automatically track API metrics. - - Usage: - @track_api_metrics("/api/v1/patients") - async def create_patient(...): - ... - """ - def decorator(func: Callable): - @wraps(func) - async def wrapper(*args, **kwargs): - tenant_id = kwargs.get('tenant_context', TenantContext('unknown', 'unknown')).tenant_id - method = kwargs.get('method', 'unknown') - - start_time = time.time() - status = "success" - - try: - result = await func(*args, **kwargs) - return result - - except Exception as e: - status = "error" - api_errors_total.labels( - endpoint=endpoint, - method=method, - error_type=type(e).__name__, - tenant_id=tenant_id - ).inc() - raise - - finally: - duration = time.time() - start_time - - api_requests_total.labels( - endpoint=endpoint, - method=method, - status=status, - tenant_id=tenant_id - ).inc() - - api_request_duration_seconds.labels( - endpoint=endpoint, - method=method, - tenant_id=tenant_id - ).observe(duration) - - return wrapper - return decorator - - -# Healthcare metrics tracking -class HealthcareMetrics: - """Track healthcare-specific metrics.""" - - @staticmethod - def update_bed_occupancy( - tenant_id: str, - facility_id: str, - unit_type: str, - occupancy_rate: float - ): - """Update bed occupancy gauge.""" - bed_occupancy_rate.labels( - tenant_id=tenant_id, - facility_id=facility_id, - unit_type=unit_type - ).set(occupancy_rate) - - @staticmethod - def update_or_utilization( - tenant_id: str, - facility_id: str, - or_number: str, - utilization_rate: float - ): - """Update OR utilization gauge.""" - or_utilization_rate.labels( - tenant_id=tenant_id, - facility_id=facility_id, - or_number=or_number - ).set(utilization_rate) - - @staticmethod - def record_lab_turnaround( - tenant_id: str, - test_type: str, - priority: str, - duration_seconds: float - ): - """Record lab turnaround time.""" - lab_turnaround_time_seconds.labels( - tenant_id=tenant_id, - test_type=test_type, - priority=priority - ).observe(duration_seconds) - - @staticmethod - def record_clinical_decision( - tenant_id: str, - decision_type: str, - severity: str - ): - """Record clinical decision invocation.""" - clinical_decisions_total.labels( - tenant_id=tenant_id, - decision_type=decision_type, - severity=severity - ).inc() - - @staticmethod - def record_sepsis_screening( - tenant_id: str, - severity: str, - positive: bool - ): - """Record sepsis screening result.""" - sepsis_screenings_total.labels( - tenant_id=tenant_id, - severity=severity, - positive=str(positive).lower() - ).inc() - - -# Usage example -@track_api_metrics("/api/v1/clinica/sepsis/screen") -async def sepsis_screening_endpoint( - request: SepsisScreeningRequest, - tenant_context: TenantContext -): - """API endpoint with automatic metrics tracking.""" - # Screening logic - result = await perform_sepsis_screening(tenant_context.tenant_id, request) - - # Track healthcare-specific metrics - HealthcareMetrics.record_clinical_decision( - tenant_id=tenant_context.tenant_id, - decision_type="sepsis_screening", - severity=result.severity - ) - - HealthcareMetrics.record_sepsis_screening( - tenant_id=tenant_context.tenant_id, - severity=result.severity, - positive=result.severity in ["high", "critical"] - ) - - return result -``` - -### 4. FastAPI Integration - -```python -from fastapi import FastAPI, Request -from prometheus_client import make_asgi_app -import time - - -def setup_observability(app: FastAPI): - """ - Configure complete observability for FastAPI app. - - - Distributed tracing - - Structured logging - - Prometheus metrics - """ - # Setup tracing - setup_tracing("yaz-care-platform") - instrument_app(app) - - # Setup logging - setup_structured_logging() - - # Expose metrics endpoint - metrics_app = make_asgi_app() - app.mount("/metrics", metrics_app) - - # Request timing middleware - @app.middleware("http") - async def track_request_metrics(request: Request, call_next): - start_time = time.time() - - response = await call_next(request) - - duration = time.time() - start_time - - # Extract tenant from request - tenant_id = request.headers.get("X-Tenant-ID", "unknown") - - # Track metrics - api_request_duration_seconds.labels( - endpoint=request.url.path, - method=request.method, - tenant_id=tenant_id - ).observe(duration) - - api_requests_total.labels( - endpoint=request.url.path, - method=request.method, - status="success" if response.status_code < 400 else "error", - tenant_id=tenant_id - ).inc() - - return response - - logger.info("observability_configured") -``` - -## Grafana Dashboard Configuration - -```yaml -# Example dashboard for healthcare metrics -apiVersion: 1 -dashboards: - - name: YAZ Care - Clinical Operations - panels: - - title: API Latency (p95) - targets: - - expr: histogram_quantile(0.95, rate(api_request_duration_seconds_bucket[5m])) - thresholds: - - value: 0.2 # 200ms SLA - color: green - - value: 0.5 - color: yellow - - value: 1.0 - color: red - - - title: Sepsis Screenings by Severity - targets: - - expr: rate(sepsis_screenings_total[5m]) - legend: "{{severity}}" - - - title: Bed Occupancy Rate - targets: - - expr: bed_occupancy_rate - legend: "{{unit_type}}" - - - title: OR Utilization - targets: - - expr: or_utilization_rate - legend: "OR {{or_number}}" - - - title: Error Rate - targets: - - expr: rate(api_errors_total[5m]) - thresholds: - - value: 0.01 # 1% error rate SLA -``` - -## Best Practices - -### 1. Always Include Trace Context -- Pass trace_id through all service calls -- Include in logs for correlation -- Add to error responses for debugging - -### 2. Sensitive Data Handling -- NEVER log PHI (patient identifiers, clinical details) -- Log patient_id as hashed value only -- Use separate audit log for PHI access - -### 3. Performance -- Use sampling for high-volume traces (1-10%) -- Batch span exports -- Async metric updates - -### 4. Alerting -- Alert on SLA violations (p95 > 200ms) -- Alert on error rate > 1% -- Alert on PHI access anomalies - -## Reference -- Sprint 32: Observability implementation (12,300 LOC) -- OpenTelemetry Python documentation -- Prometheus best practices -- ELK stack integration diff --git a/.github/copilot-prompts/security-compliance.md b/.github/copilot-prompts/security-compliance.md deleted file mode 100644 index 6e34a4dfa33e96f5dc3a860f3facc40925593e27..0000000000000000000000000000000000000000 --- a/.github/copilot-prompts/security-compliance.md +++ /dev/null @@ -1,417 +0,0 @@ -# Security & Compliance Patterns - -## HIPAA Audit Logging Checklist - -### Every PHI Access Must Be Logged - -```python -from __future__ import annotations -from typing import Optional, Dict, Any -from datetime import datetime -import hashlib -import hmac -import structlog - -logger = structlog.get_logger() - - -class AuditLogger: - """ - HIPAA-compliant audit logging for PHI access. - - Requirements: - - Cryptographic verification of logs - - Immutable audit trail - - No PHI content in logs (metadata only) - - Complete access tracking - """ - - def __init__(self, secret_key: str): - self.secret_key = secret_key.encode() - - def _generate_signature(self, audit_data: Dict[str, Any]) -> str: - """Generate HMAC-SHA256 signature for audit log entry.""" - message = f"{audit_data['timestamp']}:{audit_data['tenant_id']}:{audit_data['user_id']}:{audit_data['action']}:{audit_data['resource_id']}" - signature = hmac.new( - self.secret_key, - message.encode(), - hashlib.sha256 - ).hexdigest() - return signature - - async def log_phi_access( - self, - tenant_id: str, - user_id: str, - action: str, - resource_type: str, - resource_id: str, - ip_address: str, - user_agent: str, - access_granted: bool, - reason: Optional[str] = None, - additional_context: Optional[Dict[str, Any]] = None - ) -> str: - """ - Log PHI access with cryptographic verification. - - Args: - tenant_id: Tenant identifier - user_id: User accessing PHI - action: Action performed (view, edit, delete, export) - resource_type: Type of resource (patient, encounter, note) - resource_id: Resource identifier (NEVER include PHI) - ip_address: Source IP address - user_agent: Client user agent - access_granted: Whether access was granted - reason: Justification for access - additional_context: Additional non-PHI metadata - - Returns: - Audit log ID - """ - audit_log = { - "timestamp": datetime.utcnow().isoformat(), - "tenant_id": tenant_id, - "user_id": user_id, - "action": action, - "resource_type": resource_type, - "resource_id": resource_id, # Use ID, never PHI - "ip_address": ip_address, - "user_agent": user_agent, - "access_granted": access_granted, - "reason": reason, - "additional_context": additional_context or {} - } - - # Generate cryptographic signature - audit_log["signature"] = self._generate_signature(audit_log) - - # Log to audit system (separate from application logs) - logger.info( - "phi_access_audit", - **audit_log, - component="audit" - ) - - # Store in immutable audit database - audit_id = await self._store_audit_log(audit_log) - - return audit_id - - async def _store_audit_log(self, audit_log: Dict[str, Any]) -> str: - """Store audit log in immutable database.""" - # Implementation: Write to append-only audit table - return "audit-12345" - - -# Usage pattern -audit_logger = AuditLogger(secret_key="your-secret-key") - -@router.get("/api/v1/patients/{patient_id}") -async def get_patient( - patient_id: str, - request: Request, - tenant_context: TenantContext = Depends(get_tenant_context) -): - """Get patient with HIPAA audit logging.""" - - # Log PHI access attempt - await audit_logger.log_phi_access( - tenant_id=tenant_context.tenant_id, - user_id=tenant_context.user_id, - action="patient_record_viewed", - resource_type="patient", - resource_id=patient_id, # ID only, no PHI - ip_address=request.client.host, - user_agent=request.headers.get("user-agent", "unknown"), - access_granted=True, - reason="clinical_care" - ) - - # Fetch patient data - patient = await get_patient_from_db(patient_id, tenant_context) - - return patient -``` - -## Input Validation & Sanitization - -```python -from pydantic import BaseModel, validator, Field -from typing import Optional -import re - - -class SecurePatientInput(BaseModel): - """Secure patient input with comprehensive validation.""" - - mrn: str = Field(..., min_length=1, max_length=50) - first_name: str = Field(..., min_length=1, max_length=100) - last_name: str = Field(..., min_length=1, max_length=100) - email: Optional[str] = Field(None, max_length=255) - phone: Optional[str] = Field(None, max_length=20) - - @validator('mrn') - def validate_mrn(cls, v): - """Validate MRN format - alphanumeric only.""" - if not re.match(r'^[A-Za-z0-9\-]+$', v): - raise ValueError("MRN must be alphanumeric") - return v - - @validator('first_name', 'last_name') - def validate_name(cls, v): - """Sanitize names - letters, spaces, hyphens only.""" - if not re.match(r"^[A-Za-z\s\-']+$", v): - raise ValueError("Name contains invalid characters") - return v.strip() - - @validator('email') - def validate_email(cls, v): - """Validate email format.""" - if v and not re.match(r'^[\w\.\-]+@[\w\.\-]+\.\w+$', v): - raise ValueError("Invalid email format") - return v.lower() if v else None - - @validator('phone') - def validate_phone(cls, v): - """Sanitize phone number.""" - if v: - # Remove non-numeric characters - cleaned = re.sub(r'[^\d+]', '', v) - if len(cleaned) < 10: - raise ValueError("Phone number too short") - return cleaned - return None - - -# SQL Injection Prevention -# ALWAYS use parameterized queries -async def get_patient_secure(patient_id: str, tenant_id: str): - """Secure database query - parameterized.""" - # βœ“ CORRECT - Parameterized query - query = text(""" - SELECT * FROM patients - WHERE id = :patient_id - """) - result = await db.execute(query, {"patient_id": patient_id}) - - # βœ— WRONG - String concatenation (SQL injection risk) - # query = f"SELECT * FROM patients WHERE id = '{patient_id}'" # NEVER DO THIS! - - -# XSS Prevention -from markupsafe import escape - -def render_patient_note(note_content: str) -> str: - """Render clinical note with XSS prevention.""" - # Escape HTML to prevent XSS - safe_content = escape(note_content) - return safe_content -``` - -## Authentication & Authorization - -```python -from fastapi import Depends, HTTPException, status -from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials -import jwt -from datetime import datetime, timedelta - - -security = HTTPBearer() - - -class AuthService: - """JWT-based authentication service.""" - - SECRET_KEY = "your-secret-key" # Store in environment variable - ALGORITHM = "RS256" # Use RS256 for production - ACCESS_TOKEN_EXPIRE_MINUTES = 15 - - @classmethod - def create_access_token(cls, user_id: str, tenant_id: str, roles: list[str]) -> str: - """Create JWT access token.""" - expires = datetime.utcnow() + timedelta(minutes=cls.ACCESS_TOKEN_EXPIRE_MINUTES) - - payload = { - "sub": user_id, - "tenant_id": tenant_id, - "roles": roles, - "exp": expires, - "iat": datetime.utcnow(), - "type": "access" - } - - token = jwt.encode(payload, cls.SECRET_KEY, algorithm=cls.ALGORITHM) - return token - - @classmethod - def verify_token(cls, token: str) -> dict: - """Verify and decode JWT token.""" - try: - payload = jwt.decode( - token, - cls.SECRET_KEY, - algorithms=[cls.ALGORITHM] - ) - return payload - except jwt.ExpiredSignatureError: - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="Token has expired" - ) - except jwt.JWTError: - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="Invalid token" - ) - - -async def get_current_user( - credentials: HTTPAuthorizationCredentials = Depends(security) -) -> dict: - """Dependency for extracting current user from JWT.""" - token = credentials.credentials - payload = AuthService.verify_token(token) - return payload - - -# Role-based access control -class RBACPermissions: - """Define role-based permissions.""" - - ROLES = { - "physician": ["read:patients", "write:patients", "read:clinical_notes", "write:clinical_notes"], - "nurse": ["read:patients", "write:vital_signs", "read:clinical_notes"], - "admin": ["read:*", "write:*", "delete:*"], - "billing": ["read:patients", "read:encounters", "write:claims"] - } - - @classmethod - def has_permission(cls, user_roles: list[str], required_permission: str) -> bool: - """Check if user has required permission.""" - for role in user_roles: - permissions = cls.ROLES.get(role, []) - if required_permission in permissions or "write:*" in permissions or "read:*" in permissions: - return True - return False - - -def require_permission(permission: str): - """Decorator to require specific permission.""" - def decorator(func): - async def wrapper(*args, current_user: dict = Depends(get_current_user), **kwargs): - user_roles = current_user.get("roles", []) - - if not RBACPermissions.has_permission(user_roles, permission): - raise HTTPException( - status_code=status.HTTP_403_FORBIDDEN, - detail=f"Permission denied: {permission} required" - ) - - return await func(*args, current_user=current_user, **kwargs) - return wrapper - return decorator - - -# Usage -@router.post("/api/v1/patients") -@require_permission("write:patients") -async def create_patient( - patient_data: PatientCreate, - current_user: dict = Depends(get_current_user) -): - """Create patient - requires write:patients permission.""" - # Implementation - pass -``` - -## Secrets Management - -```python -import os -from typing import Optional - - -class SecureConfig: - """Secure configuration management - NEVER hardcode secrets.""" - - @staticmethod - def get_secret(key: str, default: Optional[str] = None) -> str: - """Get secret from environment variable.""" - value = os.getenv(key, default) - - if value is None: - raise ValueError(f"Required secret '{key}' not found in environment") - - return value - - # Database credentials - DATABASE_URL = get_secret.__func__("DATABASE_URL") - DATABASE_PASSWORD = get_secret.__func__("DATABASE_PASSWORD") - - # JWT secrets - JWT_SECRET_KEY = get_secret.__func__("JWT_SECRET_KEY") - JWT_ALGORITHM = get_secret.__func__("JWT_ALGORITHM", "RS256") - - # Encryption keys - ENCRYPTION_KEY = get_secret.__func__("ENCRYPTION_KEY") - - # API keys - THIRD_PARTY_API_KEY = get_secret.__func__("THIRD_PARTY_API_KEY") - - -# .env file (never commit to git!) -""" -DATABASE_URL=postgresql://user:password@localhost:5432/yaz_care -DATABASE_PASSWORD=secure_password_here -JWT_SECRET_KEY=your_jwt_secret_key_here -ENCRYPTION_KEY=your_encryption_key_here -""" - -# .gitignore (always include) -""" -.env -.env.local -.env.production -*.pem -*.key -secrets/ -""" -``` - -## Security Checklist - -Before deploying any feature: - -- [ ] **Input Validation**: All user inputs validated with Pydantic -- [ ] **SQL Injection**: Only parameterized queries used -- [ ] **XSS Prevention**: All output escaped -- [ ] **CSRF Protection**: CSRF tokens on state-changing operations -- [ ] **Authentication**: JWT tokens with short expiry -- [ ] **Authorization**: RBAC/ABAC enforced on all endpoints -- [ ] **Secrets Management**: No hardcoded secrets -- [ ] **Audit Logging**: All PHI access logged with signature -- [ ] **Encryption**: AES-256 at rest, TLS 1.3 in transit -- [ ] **Multi-Tenancy**: Tenant isolation verified -- [ ] **Rate Limiting**: Applied to all public endpoints -- [ ] **Security Headers**: CSP, HSTS, X-Frame-Options set -- [ ] **Dependency Scanning**: No known vulnerabilities -- [ ] **Penetration Testing**: Security review completed - -## Compliance Requirements - -### HIPAA -- [ ] PHI encrypted at rest and in transit -- [ ] Audit logs for all PHI access -- [ ] Access controls enforced -- [ ] Data breach notification process -- [ ] Business associate agreements - -### GDPR -- [ ] Right to access (data export) -- [ ] Right to erasure (data deletion) -- [ ] Data portability -- [ ] Consent management -- [ ] Data processing agreements diff --git a/.github/copilot-prompts/testing-protocol.md b/.github/copilot-prompts/testing-protocol.md deleted file mode 100644 index d9c7a481383c81f217868814c52fd1d0ec4f857e..0000000000000000000000000000000000000000 --- a/.github/copilot-prompts/testing-protocol.md +++ /dev/null @@ -1,925 +0,0 @@ -# Testing Protocol - YAZ Care Platform - -> **Purpose**: Comprehensive testing guidelines for all code changes in the YAZ Care healthcare platform -> **Target**: 85%+ test coverage, <200ms p95 latency, 100% multi-tenant isolation -> **Updated**: December 26, 2025 - ---- - -## Table of Contents - -1. [Test Types & When to Use](#test-types--when-to-use) -2. [Unit Test Patterns](#unit-test-patterns) -3. [Integration Test Patterns](#integration-test-patterns) -4. [E2E Test Patterns](#e2e-test-patterns) -5. [Performance Test Patterns](#performance-test-patterns) -6. [Security Test Patterns](#security-test-patterns) -7. [Multi-Tenancy Test Patterns](#multi-tenancy-test-patterns) -8. [Clinical Standards Test Patterns](#clinical-standards-test-patterns) -9. [Test Data Management](#test-data-management) -10. [CI/CD Integration](#cicd-integration) - ---- - -## Test Types & When to Use - -### Decision Tree - -``` -Is it testing a single function/method in isolation? -β”œβ”€ YES β†’ Unit Test -└─ NO β†’ Is it testing interaction between multiple components? - β”œβ”€ YES β†’ Integration Test - └─ NO β†’ Is it testing complete user workflow? - β”œβ”€ YES β†’ E2E Test - └─ NO β†’ Is it testing performance/load? - β”œβ”€ YES β†’ Performance Test - └─ NO β†’ Security/Compliance Test -``` - -### Test Coverage Requirements - -| Test Type | Coverage Target | Execution Time | Frequency | -|-----------|----------------|----------------|-----------| -| Unit Tests | 85%+ per module | <5s per module | Every commit | -| Integration Tests | All critical workflows | <30s per test | Every PR | -| E2E Tests | Happy path + error scenarios | <2min per test | Pre-merge | -| Performance Tests | SLA validation | <5min | Daily + pre-release | -| Security Tests | OWASP Top 10 | <10min | Daily | -| Multi-Tenancy Tests | Isolation verification | <1min | Every commit | - ---- - -## Unit Test Patterns - -### Pattern 1: Service Layer Business Logic - -**When to Use**: Testing business logic in service classes (e.g., risk calculations, validation rules) - -**Template**: -```python -import pytest -from uuid import UUID -from datetime import datetime -from src.apps.{module}.services.{entity}_service import {Entity}Service -from src.apps.{module}.domain.models import {Entity} - -class Test{Entity}Service: - """Test suite for {Entity}Service business logic""" - - @pytest.fixture - def service(self): - """Create service instance with mocked dependencies""" - return {Entity}Service() - - @pytest.fixture - def valid_{entity}_data(self): - """Valid {entity} data for testing""" - return { - "name": "Test Entity", - "tenant_id": "tenant-test-001", - # Add required fields - } - - def test_create_{entity}_success(self, service, valid_{entity}_data): - """Test successful {entity} creation with valid data""" - # Arrange - data = valid_{entity}_data - - # Act - result = await service.create_{entity}(**data) - - # Assert - assert result.id is not None - assert result.name == data["name"] - assert result.tenant_id == data["tenant_id"] - assert result.created_at is not None - - def test_create_{entity}_missing_required_field(self, service): - """Test {entity} creation fails with missing required field""" - # Arrange - invalid_data = {"tenant_id": "tenant-test-001"} # Missing 'name' - - # Act & Assert - with pytest.raises(ValidationError) as exc_info: - await service.create_{entity}(**invalid_data) - - assert "name" in str(exc_info.value) - - def test_create_{entity}_invalid_tenant_id(self, service, valid_{entity}_data): - """Test {entity} creation fails with invalid tenant_id format""" - # Arrange - valid_{entity}_data["tenant_id"] = "invalid-format" - - # Act & Assert - with pytest.raises(ValidationError) as exc_info: - await service.create_{entity}(**valid_{entity}_data) - - assert "tenant_id" in str(exc_info.value) -``` - -**Real Example**: `tests/apps/surgio/test_surgical_case_service.py` - ---- - -### Pattern 2: Clinical Algorithm Testing - -**When to Use**: Testing clinical decision support algorithms (e.g., risk scores, screening tools) - -**Template**: -```python -import pytest -from src.apps.clinica.services.clinical_algorithms import ( - calculate_sepsis_risk, - SepsisRiskResult -) - -class TestSepsisRiskCalculation: - """Test sepsis risk calculation algorithm (qSOFA + SIRS + Sepsis-3)""" - - def test_high_risk_sepsis_detection(self): - """ - Test high-risk sepsis detection with critical indicators - - Clinical Context: Patient with fever, tachycardia, hypotension - Expected: High risk score (>0.8), immediate intervention recommended - Standards: Surviving Sepsis Campaign 2021 - """ - # Arrange - High-risk patient data - patient_data = { - "temperature": 39.5, # Celsius - fever - "heart_rate": 125, # bpm - tachycardia - "respiratory_rate": 28, # breaths/min - tachypnea - "systolic_bp": 85, # mmHg - hypotension - "wbc_count": 18000, # cells/ΞΌL - elevated - "lactate": 3.5, # mmol/L - elevated - "glasgow_coma": 13 # Altered mental status - } - - # Act - result = calculate_sepsis_risk(patient_data) - - # Assert - assert isinstance(result, SepsisRiskResult) - assert result.score > 0.8, "High-risk patient should have score >0.8" - assert result.severity == "high" - assert result.qsofa_score >= 2, "qSOFA β‰₯2 indicates sepsis" - assert "immediate_intervention" in result.recommendations - assert "blood_cultures" in result.recommendations - assert "broad_spectrum_antibiotics" in result.recommendations - - def test_moderate_risk_sepsis_detection(self): - """Test moderate-risk sepsis with some indicators""" - patient_data = { - "temperature": 38.2, - "heart_rate": 105, - "respiratory_rate": 22, - "systolic_bp": 105, - "wbc_count": 13000, - "lactate": 2.0, - "glasgow_coma": 15 - } - - result = calculate_sepsis_risk(patient_data) - - assert 0.4 < result.score < 0.8 - assert result.severity == "moderate" - assert "monitoring" in result.recommendations - - def test_low_risk_normal_patient(self): - """Test low-risk with normal vital signs""" - patient_data = { - "temperature": 37.0, - "heart_rate": 75, - "respiratory_rate": 16, - "systolic_bp": 120, - "wbc_count": 8000, - "lactate": 1.0, - "glasgow_coma": 15 - } - - result = calculate_sepsis_risk(patient_data) - - assert result.score < 0.4 - assert result.severity == "low" - assert result.qsofa_score < 2 - - def test_missing_vital_signs_handling(self): - """Test graceful handling of missing data""" - patient_data = { - "temperature": 38.5, - "heart_rate": 110 - # Missing other vitals - } - - result = calculate_sepsis_risk(patient_data) - - assert result.data_completeness < 1.0 - assert "incomplete_data" in result.warnings - - def test_edge_case_borderline_values(self): - """Test behavior with borderline clinical values""" - patient_data = { - "temperature": 38.0, # Just at fever threshold - "heart_rate": 90, # Upper normal - "respiratory_rate": 20, # Upper normal - "systolic_bp": 100, # Lower normal - "wbc_count": 12000, # Borderline elevated - "lactate": 2.0, # Upper normal - "glasgow_coma": 15 - } - - result = calculate_sepsis_risk(patient_data) - - # Should not trigger high-risk alerts with borderline values - assert result.score < 0.7 -``` - -**Key Principles**: -- Test high/moderate/low risk scenarios -- Include edge cases and borderline values -- Test missing/incomplete data handling -- Document clinical context and standards -- Assert on specific clinical recommendations - ---- - -## Integration Test Patterns - -### Pattern 3: API Endpoint Testing - -**When to Use**: Testing complete API workflows from request to response - -**Template**: -```python -import pytest -from httpx import AsyncClient -from src.main import app - -@pytest.mark.asyncio -class TestPatientAPI: - """Integration tests for Patient API endpoints""" - - @pytest.fixture - async def async_client(self): - """Create async HTTP client for testing""" - async with AsyncClient(app=app, base_url="http://test") as client: - yield client - - @pytest.fixture - async def auth_headers(self, async_client): - """Get authentication headers with JWT token""" - # Login as test user - response = await async_client.post( - "/api/v1/auth/login", - json={ - "username": "test.clinician@hospital.com", - "password": "test_password_123" - } - ) - token = response.json()["data"]["access_token"] - - return { - "Authorization": f"Bearer {token}", - "X-Tenant-ID": "tenant-test-001" - } - - async def test_create_patient_success(self, async_client, auth_headers): - """Test successful patient creation via API""" - # Arrange - patient_data = { - "first_name": "John", - "last_name": "Doe", - "date_of_birth": "1980-01-15", - "gender": "male", - "mrn": "MRN-12345" - } - - # Act - response = await async_client.post( - "/api/v1/clinica/patients", - json=patient_data, - headers=auth_headers - ) - - # Assert - assert response.status_code == 201 - data = response.json()["data"] - assert data["first_name"] == "John" - assert data["last_name"] == "Doe" - assert "id" in data - assert "created_at" in data - - # Verify audit log created - audit_response = await async_client.get( - f"/api/v1/audit/logs?resource_id={data['id']}", - headers=auth_headers - ) - assert audit_response.status_code == 200 - assert len(audit_response.json()["data"]) > 0 - - async def test_create_patient_unauthorized(self, async_client): - """Test patient creation fails without authentication""" - patient_data = {"first_name": "John", "last_name": "Doe"} - - response = await async_client.post( - "/api/v1/clinica/patients", - json=patient_data - ) - - assert response.status_code == 401 - assert "authentication" in response.json()["error"].lower() - - async def test_create_patient_invalid_data(self, async_client, auth_headers): - """Test patient creation with invalid data returns 400""" - invalid_data = { - "first_name": "", # Empty name - "date_of_birth": "invalid-date" - } - - response = await async_client.post( - "/api/v1/clinica/patients", - json=invalid_data, - headers=auth_headers - ) - - assert response.status_code == 400 - error = response.json() - assert error["error"] == "validation_error" - assert "first_name" in error["details"] - - async def test_get_patient_by_id(self, async_client, auth_headers): - """Test retrieving patient by ID""" - # Create patient first - create_response = await async_client.post( - "/api/v1/clinica/patients", - json={"first_name": "Jane", "last_name": "Smith", "mrn": "MRN-67890"}, - headers=auth_headers - ) - patient_id = create_response.json()["data"]["id"] - - # Retrieve patient - response = await async_client.get( - f"/api/v1/clinica/patients/{patient_id}", - headers=auth_headers - ) - - assert response.status_code == 200 - data = response.json()["data"] - assert data["id"] == patient_id - assert data["first_name"] == "Jane" - - async def test_list_patients_pagination(self, async_client, auth_headers): - """Test patient list endpoint with pagination""" - # Create multiple patients - for i in range(25): - await async_client.post( - "/api/v1/clinica/patients", - json={"first_name": f"Patient{i}", "last_name": "Test", "mrn": f"MRN-{i}"}, - headers=auth_headers - ) - - # Test pagination - response = await async_client.get( - "/api/v1/clinica/patients?page=1&per_page=10", - headers=auth_headers - ) - - assert response.status_code == 200 - data = response.json() - assert data["page"] == 1 - assert data["per_page"] == 10 - assert len(data["data"]) == 10 - assert data["total"] >= 25 -``` - ---- - -## Multi-Tenancy Test Patterns - -### Pattern 4: Tenant Isolation Testing - -**When to Use**: Verifying data isolation between tenants (CRITICAL for every feature) - -**Template**: -```python -import pytest -from uuid import uuid4 - -@pytest.mark.asyncio -class TestMultiTenantIsolation: - """Test multi-tenant data isolation for {Entity}""" - - @pytest.fixture - async def tenant_a_data(self, async_client): - """Create test data for Tenant A""" - tenant_id = "tenant-a-001" - auth_headers = await get_auth_headers(async_client, tenant_id) - - # Create entity in Tenant A - response = await async_client.post( - "/api/v1/{module}/{entity}", - json={"name": "Tenant A Entity", "value": "confidential_a"}, - headers=auth_headers - ) - - return { - "tenant_id": tenant_id, - "entity_id": response.json()["data"]["id"], - "headers": auth_headers - } - - @pytest.fixture - async def tenant_b_data(self, async_client): - """Create test data for Tenant B""" - tenant_id = "tenant-b-002" - auth_headers = await get_auth_headers(async_client, tenant_id) - - # Create entity in Tenant B - response = await async_client.post( - "/api/v1/{module}/{entity}", - json={"name": "Tenant B Entity", "value": "confidential_b"}, - headers=auth_headers - ) - - return { - "tenant_id": tenant_id, - "entity_id": response.json()["data"]["id"], - "headers": auth_headers - } - - async def test_tenant_cannot_read_other_tenant_data( - self, - async_client, - tenant_a_data, - tenant_b_data - ): - """ - Verify Tenant B cannot read Tenant A's data - - Security Context: Multi-tenant data isolation (HIPAA requirement) - Expected: 404 Not Found (not 403 to avoid information disclosure) - """ - # Tenant B attempts to access Tenant A's entity - response = await async_client.get( - f"/api/v1/{module}/{entity}/{tenant_a_data['entity_id']}", - headers=tenant_b_data["headers"] - ) - - # Should return 404 (not 403) to avoid leaking entity existence - assert response.status_code == 404 - assert "not found" in response.json()["message"].lower() - - async def test_tenant_cannot_update_other_tenant_data( - self, - async_client, - tenant_a_data, - tenant_b_data - ): - """Verify Tenant B cannot update Tenant A's data""" - response = await async_client.put( - f"/api/v1/{module}/{entity}/{tenant_a_data['entity_id']}", - json={"name": "Malicious Update"}, - headers=tenant_b_data["headers"] - ) - - assert response.status_code == 404 - - async def test_tenant_cannot_delete_other_tenant_data( - self, - async_client, - tenant_a_data, - tenant_b_data - ): - """Verify Tenant B cannot delete Tenant A's data""" - response = await async_client.delete( - f"/api/v1/{module}/{entity}/{tenant_a_data['entity_id']}", - headers=tenant_b_data["headers"] - ) - - assert response.status_code == 404 - - # Verify Tenant A's data still exists - verify_response = await async_client.get( - f"/api/v1/{module}/{entity}/{tenant_a_data['entity_id']}", - headers=tenant_a_data["headers"] - ) - assert verify_response.status_code == 200 - - async def test_list_endpoint_filters_by_tenant( - self, - async_client, - tenant_a_data, - tenant_b_data - ): - """Verify list endpoint only returns tenant's own data""" - # Tenant A lists entities - response_a = await async_client.get( - f"/api/v1/{module}/{entity}", - headers=tenant_a_data["headers"] - ) - - data_a = response_a.json()["data"] - tenant_a_ids = [item["id"] for item in data_a] - - # Tenant B's entity ID should NOT appear in Tenant A's list - assert tenant_b_data["entity_id"] not in tenant_a_ids - - # Tenant A's entity ID SHOULD appear - assert tenant_a_data["entity_id"] in tenant_a_ids - - async def test_database_query_includes_tenant_filter(self, db_session): - """Verify raw database queries include tenant_id filter""" - from sqlalchemy import text - - # Attempt query without tenant_id (should fail or return empty) - query = text("SELECT * FROM {schema}.{table} WHERE id = :id") - result = await db_session.execute( - query, - {"id": tenant_a_data["entity_id"]} - ) - - # Without search_path or tenant_id filter, should not find data - assert result.rowcount == 0 or result is None -``` - -**Critical Rules**: -1. Every API endpoint MUST have tenant isolation test -2. Return 404 (not 403) to avoid information disclosure -3. Test create, read, update, delete, and list operations -4. Verify raw database queries include tenant filters -5. Test with at least 2 different tenants - ---- - -## Performance Test Patterns - -### Pattern 5: API Latency Testing - -**When to Use**: Validating SLA compliance (<200ms p95 latency) - -**Template**: -```python -import pytest -import time -from statistics import mean, median -from typing import List - -@pytest.mark.performance -class TestAPIPerformance: - """Performance tests for API endpoints (SLA: <200ms p95)""" - - async def measure_endpoint_latency( - self, - async_client, - method: str, - url: str, - headers: dict, - iterations: int = 100 - ) -> List[float]: - """Measure endpoint latency over multiple iterations""" - latencies = [] - - for _ in range(iterations): - start = time.time() - - if method == "GET": - response = await async_client.get(url, headers=headers) - elif method == "POST": - response = await async_client.post(url, json={}, headers=headers) - - latency_ms = (time.time() - start) * 1000 - latencies.append(latency_ms) - - assert response.status_code in [200, 201, 400] # Valid responses - - return latencies - - def calculate_percentiles(self, latencies: List[float]): - """Calculate latency percentiles""" - sorted_latencies = sorted(latencies) - n = len(sorted_latencies) - - return { - "p50": sorted_latencies[int(n * 0.50)], - "p95": sorted_latencies[int(n * 0.95)], - "p99": sorted_latencies[int(n * 0.99)], - "mean": mean(latencies), - "median": median(latencies), - "min": min(latencies), - "max": max(latencies) - } - - async def test_patient_list_latency(self, async_client, auth_headers): - """ - Test patient list endpoint latency - - Performance Target: <200ms p95 - Load: 100 sequential requests - """ - # Arrange - Pre-populate database - for i in range(50): - await async_client.post( - "/api/v1/clinica/patients", - json={"first_name": f"Patient{i}", "last_name": "Test"}, - headers=auth_headers - ) - - # Act - Measure latency - latencies = await self.measure_endpoint_latency( - async_client, - "GET", - "/api/v1/clinica/patients?page=1&per_page=20", - auth_headers, - iterations=100 - ) - - # Assert - percentiles = self.calculate_percentiles(latencies) - - print(f"\nPatient List Latency:") - print(f" P50: {percentiles['p50']:.2f}ms") - print(f" P95: {percentiles['p95']:.2f}ms") - print(f" P99: {percentiles['p99']:.2f}ms") - print(f" Mean: {percentiles['mean']:.2f}ms") - - # SLA assertion - assert percentiles['p95'] < 200, \ - f"P95 latency {percentiles['p95']:.2f}ms exceeds SLA of 200ms" - - async def test_concurrent_request_performance(self, async_client, auth_headers): - """Test API performance under concurrent load""" - import asyncio - - async def make_request(): - start = time.time() - response = await async_client.get( - "/api/v1/clinica/patients", - headers=auth_headers - ) - return (time.time() - start) * 1000 - - # Simulate 50 concurrent requests - tasks = [make_request() for _ in range(50)] - latencies = await asyncio.gather(*tasks) - - percentiles = self.calculate_percentiles(latencies) - - assert percentiles['p95'] < 200 - assert max(latencies) < 500, "No request should exceed 500ms" -``` - ---- - -## Security Test Patterns - -### Pattern 6: Authentication & Authorization Testing - -**Template**: -```python -@pytest.mark.security -class TestAuthenticationSecurity: - """Security tests for authentication and authorization""" - - async def test_endpoint_requires_authentication(self, async_client): - """Verify protected endpoint rejects unauthenticated requests""" - response = await async_client.get("/api/v1/clinica/patients") - - assert response.status_code == 401 - assert "authentication" in response.json()["error"].lower() - - async def test_expired_token_rejected(self, async_client): - """Verify expired JWT tokens are rejected""" - expired_token = generate_expired_token() - - response = await async_client.get( - "/api/v1/clinica/patients", - headers={"Authorization": f"Bearer {expired_token}"} - ) - - assert response.status_code == 401 - assert "expired" in response.json()["message"].lower() - - async def test_insufficient_permissions_denied(self, async_client): - """Verify users without required permissions cannot access endpoint""" - # Login as user with limited permissions - token = await get_auth_token(async_client, role="nurse") - - # Attempt admin-only action - response = await async_client.delete( - "/api/v1/clinica/patients/patient-123", - headers={"Authorization": f"Bearer {token}"} - ) - - assert response.status_code == 403 - assert "permission" in response.json()["message"].lower() - - async def test_sql_injection_protection(self, async_client, auth_headers): - """Verify SQL injection attempts are blocked""" - malicious_inputs = [ - "'; DROP TABLE patients; --", - "1' OR '1'='1", - "admin'--", - "1 UNION SELECT * FROM users--" - ] - - for malicious_input in malicious_inputs: - response = await async_client.get( - f"/api/v1/clinica/patients?search={malicious_input}", - headers=auth_headers - ) - - # Should either return 400 (validation error) or safe results - assert response.status_code in [200, 400] - # Database should still be intact (verify critical table exists) - - async def test_xss_protection(self, async_client, auth_headers): - """Verify XSS payloads are sanitized""" - xss_payload = "" - - response = await async_client.post( - "/api/v1/clinica/patients", - json={"first_name": xss_payload, "last_name": "Test"}, - headers=auth_headers - ) - - # Either rejected or sanitized - if response.status_code == 201: - data = response.json()["data"] - assert "" - - response = await async_client.post( - "/api/v1/clinica/patients", - json={"first_name": xss_payload, "last_name": "Test"}, - headers=auth_headers - ) - - # Either rejected or sanitized - if response.status_code == 201: - data = response.json()["data"] - assert "|javascript:|onerror=|onload=| backup.sql -``` - -## Redis Management - -```bash -# Connect to Redis -kubectl exec -it -n yaz-care redis-0 -- redis-cli - -# Check Redis cluster status -kubectl exec -it -n yaz-care redis-0 -- redis-cli cluster info - -# Monitor Redis -kubectl exec -it -n yaz-care redis-0 -- redis-cli monitor -``` - -## Resource Configuration - -### Current Settings - -| Resource | Requests | Limits | -|----------|----------|--------| -| API Pod | 512Mi / 500m | 2Gi / 2000m | -| PostgreSQL | 1Gi / 500m | 4Gi / 2000m | -| Redis | 512Mi / 250m | 2Gi / 1000m | - -### Auto-scaling - -- **Min Replicas**: 3 -- **Max Replicas**: 10 -- **CPU Target**: 70% -- **Memory Target**: 80% - -## Security Notes - -⚠️ **IMPORTANT**: Before production deployment: - -1. Update all passwords in `secrets.yaml` -2. Use proper TLS certificates (cert-manager with Let's Encrypt) -3. Enable network policies -4. Configure pod security policies -5. Use image pull secrets for private registries -6. Review and adjust resource limits -7. Enable audit logging -8. Configure backup strategy - -## Production Checklist - -- [ ] All secrets updated with strong passwords -- [ ] TLS certificates configured -- [ ] Monitoring stack deployed (Prometheus/Grafana) -- [ ] Backup CronJob configured -- [ ] Resource limits tuned based on load testing -- [ ] Network policies applied -- [ ] Pod disruption budgets configured -- [ ] Health checks validated -- [ ] Rollback procedure tested -- [ ] Disaster recovery plan documented - -## Architecture - -``` -β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” -β”‚ Load Balancer (Ingress) β”‚ -β”‚ api.yazcare.health β”‚ -β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ - β”‚ -β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” -β”‚ API Pods (3-10 replicas) β”‚ -β”‚ Auto-scaling (HPA) β”‚ -β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ - β”‚ β”‚ -β”Œβ”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β” -β”‚ PostgreSQL β”‚ β”‚ Redis β”‚ -β”‚StatefulSet β”‚ β”‚StatefulSet β”‚ -β”‚ (Primary) β”‚ β”‚ (3 nodes) β”‚ -β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ -``` - -## Support - -For issues or questions, refer to: -- Main documentation: `/docs/` -- Sprint 16 plan: `/docs/sprints/sprint-16-production-deployment.md` -- Operations runbooks: `/docs/operations/` diff --git a/infra/kubernetes/backup-cronjob.yaml b/infra/kubernetes/backup-cronjob.yaml deleted file mode 100644 index aaf8374b482adab94153059201454d62925872c4..0000000000000000000000000000000000000000 --- a/infra/kubernetes/backup-cronjob.yaml +++ /dev/null @@ -1,136 +0,0 @@ ---- -apiVersion: batch/v1 -kind: CronJob -metadata: - name: yaz-care-backup - namespace: yaz-care - labels: - app: backup - component: disaster-recovery -spec: - # Run every 6 hours - schedule: "0 */6 * * *" - concurrencyPolicy: Forbid - successfulJobsHistoryLimit: 3 - failedJobsHistoryLimit: 3 - - jobTemplate: - spec: - template: - metadata: - labels: - app: backup - spec: - restartPolicy: OnFailure - - serviceAccountName: backup-service-account - - containers: - - name: backup - image: ghcr.io/elanass/yaz:3.0.0 - command: - - python - - /app/scripts/backup/automated_backup.py - - backup - - env: - # S3 Configuration - - name: S3_BUCKET - value: "yaz-care-backups" - - name: AWS_ACCESS_KEY_ID - valueFrom: - secretKeyRef: - name: yaz-care-secrets - key: AWS_ACCESS_KEY_ID - - name: AWS_SECRET_ACCESS_KEY - valueFrom: - secretKeyRef: - name: yaz-care-secrets - key: AWS_SECRET_ACCESS_KEY - - name: AWS_REGION - value: "eu-central-1" - - # Database Configuration - - name: DB_HOST - value: "postgres" - - name: DB_PORT - value: "5432" - - name: DB_NAME - value: "yaz_care_prod" - - name: DB_USER - valueFrom: - secretKeyRef: - name: yaz-care-secrets - key: POSTGRES_USER - - name: DB_PASSWORD - valueFrom: - secretKeyRef: - name: yaz-care-secrets - key: POSTGRES_PASSWORD - - # Redis Configuration - - name: REDIS_HOST - value: "redis" - - name: REDIS_PORT - value: "6379" - - name: REDIS_PASSWORD - valueFrom: - secretKeyRef: - name: yaz-care-secrets - key: REDIS_PASSWORD - - volumeMounts: - - name: backup-storage - mountPath: /tmp/backups - - resources: - requests: - memory: "256Mi" - cpu: "250m" - limits: - memory: "1Gi" - cpu: "1000m" - - volumes: - - name: backup-storage - emptyDir: - sizeLimit: 10Gi - ---- -apiVersion: v1 -kind: ServiceAccount -metadata: - name: backup-service-account - namespace: yaz-care - ---- -apiVersion: rbac.authorization.k8s.io/v1 -kind: Role -metadata: - name: backup-role - namespace: yaz-care -rules: - - apiGroups: [""] - resources: ["pods", "pods/log"] - verbs: ["get", "list"] - - apiGroups: [""] - resources: ["pods/exec"] - verbs: ["create"] - - apiGroups: [""] - resources: ["configmaps", "secrets"] - verbs: ["get", "list"] - ---- -apiVersion: rbac.authorization.k8s.io/v1 -kind: RoleBinding -metadata: - name: backup-role-binding - namespace: yaz-care -subjects: - - kind: ServiceAccount - name: backup-service-account - namespace: yaz-care -roleRef: - kind: Role - name: backup-role - apiGroup: rbac.authorization.k8s.io diff --git a/infra/kubernetes/configmap.yaml b/infra/kubernetes/configmap.yaml deleted file mode 100644 index 514313b24c69987970fcaa97de0c5e57e47d9dfb..0000000000000000000000000000000000000000 --- a/infra/kubernetes/configmap.yaml +++ /dev/null @@ -1,38 +0,0 @@ ---- -apiVersion: v1 -kind: ConfigMap -metadata: - name: yaz-care-config - namespace: yaz-care -data: - # Environment - ENVIRONMENT: "production" - LOG_LEVEL: "INFO" - - # Database - DATABASE_POOL_SIZE: "20" - DATABASE_POOL_TIMEOUT: "30" - DATABASE_MAX_OVERFLOW: "10" - - # Redis - REDIS_CLUSTER_MODE: "true" - REDIS_MAX_CONNECTIONS: "50" - - # API Configuration - API_RATE_LIMIT: "100" - API_TIMEOUT: "30" - - # CORS - CORS_ORIGINS: "https://yazcare.health,https://app.yazcare.health" - - # Session - SESSION_TIMEOUT: "3600" - - # Monitoring - METRICS_ENABLED: "true" - METRICS_PORT: "8001" - - # Feature Flags - ENABLE_REALTIME: "true" - ENABLE_ANALYTICS: "true" - ENABLE_AI_FEATURES: "true" diff --git a/infra/kubernetes/deployment.yaml b/infra/kubernetes/deployment.yaml deleted file mode 100644 index 6abad82525d746636dea7b400b0bbc83977d8e86..0000000000000000000000000000000000000000 --- a/infra/kubernetes/deployment.yaml +++ /dev/null @@ -1,501 +0,0 @@ -# YAZ Healthcare Platform - Kubernetes Deployment -# Production-ready Kubernetes configuration with auto-scaling and monitoring - -apiVersion: v1 -kind: Namespace -metadata: - name: yaz-healthcare - labels: - name: yaz-healthcare - environment: production - ---- -# ConfigMap for application configuration -apiVersion: v1 -kind: ConfigMap -metadata: - name: yaz-config - namespace: yaz-care -data: - APP_ENV: "production" - PYTHONPATH: "/app/src" - LOG_LEVEL: "INFO" - ENABLE_METRICS: "true" - ENABLE_TRACING: "true" - DATABASE_HOST: "postgres-service" - REDIS_HOST: "redis-service" - JAEGER_ENDPOINT: "http://jaeger-service:14268/api/traces" - PROMETHEUS_GATEWAY: "http://prometheus-service:9090" - ---- -# Secret for sensitive data -apiVersion: v1 -kind: Secret -metadata: - name: yaz-secrets - namespace: yaz-care -type: Opaque -data: - DATABASE_PASSWORD: eWF6Y2FyZXBhc3N3b3Jk # base64 encoded - SECRET_KEY: c3VwZXJzZWNyZXRrZXlmb3J5YXo= # base64 encoded - JWT_SECRET_KEY: and0c2VjcmV0a2V5Zm9yeWF6 # base64 encoded - ---- -# Persistent Volume Claim for data -apiVersion: v1 -kind: PersistentVolumeClaim -metadata: - name: yaz-data-pvc - namespace: yaz-care -spec: - accessModes: - - ReadWriteOnce - storageClassName: fast-ssd - resources: - requests: - storage: 100Gi - ---- -# PostgreSQL StatefulSet -apiVersion: apps/v1 -kind: StatefulSet -metadata: - name: postgres - namespace: yaz-care -spec: - serviceName: postgres-service - replicas: 1 - selector: - matchLabels: - app: postgres - template: - metadata: - labels: - app: postgres - spec: - containers: - - name: postgres - image: postgres:15-alpine - ports: - - containerPort: 5432 - env: - - name: POSTGRES_DB - value: "yazcare" - - name: POSTGRES_USER - value: "yazcare" - - name: POSTGRES_PASSWORD - valueFrom: - secretKeyRef: - name: yaz-secrets - key: DATABASE_PASSWORD - - name: PGDATA - value: /var/lib/postgresql/data/pgdata - volumeMounts: - - name: postgres-storage - mountPath: /var/lib/postgresql/data - resources: - requests: - memory: "2Gi" - cpu: "1" - limits: - memory: "4Gi" - cpu: "2" - livenessProbe: - exec: - command: - - pg_isready - - -U - - yazcare - - -d - - yazcare - initialDelaySeconds: 30 - periodSeconds: 10 - readinessProbe: - exec: - command: - - pg_isready - - -U - - yazcare - - -d - - yazcare - initialDelaySeconds: 5 - periodSeconds: 5 - volumeClaimTemplates: - - metadata: - name: postgres-storage - spec: - accessModes: ["ReadWriteOnce"] - storageClassName: "fast-ssd" - resources: - requests: - storage: 50Gi - ---- -# PostgreSQL Service -apiVersion: v1 -kind: Service -metadata: - name: postgres-service - namespace: yaz-care -spec: - selector: - app: postgres - ports: - - port: 5432 - targetPort: 5432 - type: ClusterIP - ---- -# Redis Deployment -apiVersion: apps/v1 -kind: Deployment -metadata: - name: redis - namespace: yaz-care -spec: - replicas: 1 - selector: - matchLabels: - app: redis - template: - metadata: - labels: - app: redis - spec: - containers: - - name: redis - image: redis:7-alpine - ports: - - containerPort: 6379 - command: ["redis-server", "--appendonly", "yes"] - volumeMounts: - - name: redis-storage - mountPath: /data - resources: - requests: - memory: "1Gi" - cpu: "0.5" - limits: - memory: "2Gi" - cpu: "1" - livenessProbe: - exec: - command: - - redis-cli - - ping - initialDelaySeconds: 30 - periodSeconds: 10 - readinessProbe: - exec: - command: - - redis-cli - - ping - initialDelaySeconds: 5 - periodSeconds: 5 - volumes: - - name: redis-storage - persistentVolumeClaim: - claimName: redis-pvc - ---- -# Redis PVC -apiVersion: v1 -kind: PersistentVolumeClaim -metadata: - name: redis-pvc - namespace: yaz-care -spec: - accessModes: - - ReadWriteOnce - storageClassName: fast-ssd - resources: - requests: - storage: 20Gi - ---- -# Redis Service -apiVersion: v1 -kind: Service -metadata: - name: redis-service - namespace: yaz-care -spec: - selector: - app: redis - ports: - - port: 6379 - targetPort: 6379 - type: ClusterIP - ---- -# YAZ Healthcare Platform Deployment -apiVersion: apps/v1 -kind: Deployment -metadata: - name: yaz-platform - namespace: yaz-care - labels: - app: yaz-platform - version: v1 -spec: - replicas: 3 - selector: - matchLabels: - app: yaz-platform - template: - metadata: - labels: - app: yaz-platform - version: v1 - spec: - containers: - - name: yaz-platform - image: yaz-healthcare:latest - ports: - - containerPort: 8000 - env: - - name: DATABASE_URL - value: "postgresql://yazcare:$(DATABASE_PASSWORD)@postgres-service:5432/yazcare" - - name: REDIS_URL - value: "redis://redis-service:6379/0" - - name: DATABASE_PASSWORD - valueFrom: - secretKeyRef: - name: yaz-secrets - key: DATABASE_PASSWORD - - name: SECRET_KEY - valueFrom: - secretKeyRef: - name: yaz-secrets - key: SECRET_KEY - - name: JWT_SECRET_KEY - valueFrom: - secretKeyRef: - name: yaz-secrets - key: JWT_SECRET_KEY - envFrom: - - configMapRef: - name: yaz-config - volumeMounts: - - name: app-data - mountPath: /app/data - - name: app-logs - mountPath: /app/logs - - name: app-storage - mountPath: /app/storage - resources: - requests: - memory: "512Mi" - cpu: "500m" - limits: - memory: "1Gi" - cpu: "1000m" - lifecycle: - preStop: - exec: - command: ["sh", "-c", "sleep 10"] # drain in-flight requests - livenessProbe: - httpGet: - path: /health - port: 8000 - initialDelaySeconds: 45 - periodSeconds: 15 - timeoutSeconds: 5 - failureThreshold: 3 - readinessProbe: - httpGet: - path: /health - port: 8000 - initialDelaySeconds: 15 - periodSeconds: 5 - timeoutSeconds: 3 - failureThreshold: 3 - startupProbe: - httpGet: - path: /health - port: 8000 - initialDelaySeconds: 10 - periodSeconds: 5 - timeoutSeconds: 3 - failureThreshold: 20 - volumes: - - name: app-data - persistentVolumeClaim: - claimName: yaz-data-pvc - - name: app-logs - emptyDir: {} - - name: app-storage - persistentVolumeClaim: - claimName: yaz-storage-pvc - imagePullSecrets: - - name: docker-registry-secret - ---- -# Additional PVC for storage -apiVersion: v1 -kind: PersistentVolumeClaim -metadata: - name: yaz-storage-pvc - namespace: yaz-care -spec: - accessModes: - - ReadWriteOnce - storageClassName: fast-ssd - resources: - requests: - storage: 50Gi - ---- -# YAZ Platform Service -apiVersion: v1 -kind: Service -metadata: - name: yaz-platform-service - namespace: yaz-care -spec: - selector: - app: yaz-platform - ports: - - name: http - port: 8000 - targetPort: 8000 - type: ClusterIP - ---- -# Horizontal Pod Autoscaler -apiVersion: autoscaling/v2 -kind: HorizontalPodAutoscaler -metadata: - name: yaz-platform-hpa - namespace: yaz-care -spec: - scaleTargetRef: - apiVersion: apps/v1 - kind: Deployment - name: yaz-platform - minReplicas: 3 - maxReplicas: 20 - metrics: - - type: Resource - resource: - name: cpu - target: - type: Utilization - averageUtilization: 70 - - type: Resource - resource: - name: memory - target: - type: Utilization - averageUtilization: 80 - behavior: - scaleDown: - stabilizationWindowSeconds: 300 # Wait 5 min before scaling down - policies: - - type: Percent - value: 25 - periodSeconds: 120 - scaleUp: - stabilizationWindowSeconds: 30 - policies: - - type: Percent - value: 50 - periodSeconds: 60 - - type: Pods - value: 3 - periodSeconds: 60 - ---- -# Ingress for external access -apiVersion: networking.k8s.io/v1 -kind: Ingress -metadata: - name: yaz-platform-ingress - namespace: yaz-care - annotations: - kubernetes.io/ingress.class: "nginx" - nginx.ingress.kubernetes.io/ssl-redirect: "true" - nginx.ingress.kubernetes.io/force-ssl-redirect: "true" - nginx.ingress.kubernetes.io/rate-limit: "100" - nginx.ingress.kubernetes.io/rate-limit-window: "1m" - cert-manager.io/cluster-issuer: "letsencrypt-prod" -spec: - tls: - - hosts: - - yaz-healthcare.com - - api.yaz-healthcare.com - secretName: yaz-tls-secret - rules: - - host: yaz-healthcare.com - http: - paths: - - path: / - pathType: Prefix - backend: - service: - name: yaz-platform-service - port: - number: 8000 - - host: api.yaz-healthcare.com - http: - paths: - - path: / - pathType: Prefix - backend: - service: - name: yaz-platform-service - port: - number: 8000 - ---- -# Pod Disruption Budget -apiVersion: policy/v1 -kind: PodDisruptionBudget -metadata: - name: yaz-platform-pdb - namespace: yaz-care -spec: - minAvailable: 2 - selector: - matchLabels: - app: yaz-platform - ---- -# Network Policy for security -apiVersion: networking.k8s.io/v1 -kind: NetworkPolicy -metadata: - name: yaz-network-policy - namespace: yaz-care -spec: - podSelector: {} - policyTypes: - - Ingress - - Egress - ingress: - - from: - - namespaceSelector: - matchLabels: - name: nginx-ingress - - namespaceSelector: - matchLabels: - name: monitoring - egress: - - to: - - namespaceSelector: - matchLabels: - name: kube-system - - to: - - podSelector: - matchLabels: - app: postgres - ports: - - protocol: TCP - port: 5432 - - to: - - podSelector: - matchLabels: - app: redis - ports: - - protocol: TCP - port: 6379 diff --git a/infra/kubernetes/hpa.yaml b/infra/kubernetes/hpa.yaml deleted file mode 100644 index 21576a3b397585318bcc358ae3b1e47a70e15976..0000000000000000000000000000000000000000 --- a/infra/kubernetes/hpa.yaml +++ /dev/null @@ -1,63 +0,0 @@ ---- -apiVersion: autoscaling/v2 -kind: HorizontalPodAutoscaler -metadata: - name: yaz-care-api-hpa - namespace: yaz-care -spec: - scaleTargetRef: - apiVersion: apps/v1 - kind: Deployment - name: yaz-care-api - - minReplicas: 3 - maxReplicas: 20 - - metrics: - # CPU-based scaling - - type: Resource - resource: - name: cpu - target: - type: Utilization - averageUtilization: 70 - - # Memory-based scaling - - type: Resource - resource: - name: memory - target: - type: Utilization - averageUtilization: 80 - - # Custom metrics (if Prometheus adapter is installed) - # - type: Pods - # pods: - # metric: - # name: http_requests_per_second - # target: - # type: AverageValue - # averageValue: "1000" - - behavior: - scaleUp: - stabilizationWindowSeconds: 60 - policies: - - type: Percent - value: 50 - periodSeconds: 60 - - type: Pods - value: 2 - periodSeconds: 60 - selectPolicy: Max - - scaleDown: - stabilizationWindowSeconds: 300 - policies: - - type: Percent - value: 25 - periodSeconds: 120 - - type: Pods - value: 1 - periodSeconds: 60 - selectPolicy: Min diff --git a/infra/kubernetes/ingress.yaml b/infra/kubernetes/ingress.yaml deleted file mode 100644 index 013eaa230aca6d767d7a1e1bee9c29c4c7ef96bd..0000000000000000000000000000000000000000 --- a/infra/kubernetes/ingress.yaml +++ /dev/null @@ -1,63 +0,0 @@ ---- -apiVersion: networking.k8s.io/v1 -kind: Ingress -metadata: - name: yaz-care-ingress - namespace: yaz-care - annotations: - # Cert manager - cert-manager.io/cluster-issuer: "letsencrypt-prod" - - # NGINX ingress - nginx.ingress.kubernetes.io/ssl-redirect: "true" - nginx.ingress.kubernetes.io/force-ssl-redirect: "true" - nginx.ingress.kubernetes.io/rate-limit: "100" - nginx.ingress.kubernetes.io/proxy-body-size: "10m" - nginx.ingress.kubernetes.io/proxy-connect-timeout: "30" - nginx.ingress.kubernetes.io/proxy-send-timeout: "30" - nginx.ingress.kubernetes.io/proxy-read-timeout: "30" - - # Security headers - nginx.ingress.kubernetes.io/configuration-snippet: | - add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always; - add_header X-Content-Type-Options "nosniff" always; - add_header X-Frame-Options "DENY" always; - add_header X-XSS-Protection "1; mode=block" always; - add_header Referrer-Policy "strict-origin-when-cross-origin" always; - - # CORS - nginx.ingress.kubernetes.io/enable-cors: "true" - nginx.ingress.kubernetes.io/cors-allow-origin: "https://yazcare.health,https://app.yazcare.health" - nginx.ingress.kubernetes.io/cors-allow-methods: "GET, POST, PUT, DELETE, PATCH, OPTIONS" - nginx.ingress.kubernetes.io/cors-allow-credentials: "true" - -spec: - ingressClassName: nginx - tls: - - hosts: - - api.yazcare.health - - app.yazcare.health - secretName: yaz-care-tls - - rules: - - host: api.yazcare.health - http: - paths: - - path: / - pathType: Prefix - backend: - service: - name: yaz-care-api - port: - number: 8000 - - - host: app.yazcare.health - http: - paths: - - path: / - pathType: Prefix - backend: - service: - name: yaz-care-api - port: - number: 8000 diff --git a/infra/kubernetes/monitoring/grafana.yaml b/infra/kubernetes/monitoring/grafana.yaml deleted file mode 100644 index 1fa6e4656d07ae6649f7fde6bc6ff7e2dddb982e..0000000000000000000000000000000000000000 --- a/infra/kubernetes/monitoring/grafana.yaml +++ /dev/null @@ -1,82 +0,0 @@ -apiVersion: v1 -kind: ConfigMap -metadata: - name: grafana-datasources - namespace: monitoring -data: - datasources.yaml: | - apiVersion: 1 - datasources: - - name: Prometheus - type: prometheus - access: proxy - url: http://prometheus:9090 - isDefault: true - editable: false ---- -apiVersion: apps/v1 -kind: Deployment -metadata: - name: grafana - namespace: monitoring -spec: - replicas: 1 - selector: - matchLabels: - app: grafana - template: - metadata: - labels: - app: grafana - spec: - containers: - - name: grafana - image: grafana/grafana:latest - ports: - - containerPort: 3000 - name: web - env: - - name: GF_SECURITY_ADMIN_PASSWORD - valueFrom: - secretKeyRef: - name: grafana-secrets - key: admin-password - - name: GF_SERVER_ROOT_URL - value: https://monitoring.yazcare.com - volumeMounts: - - name: grafana-storage - mountPath: /var/lib/grafana - - name: datasources - mountPath: /etc/grafana/provisioning/datasources - volumes: - - name: grafana-storage - persistentVolumeClaim: - claimName: grafana-pvc - - name: datasources - configMap: - name: grafana-datasources ---- -apiVersion: v1 -kind: Service -metadata: - name: grafana - namespace: monitoring -spec: - type: ClusterIP - ports: - - port: 3000 - targetPort: 3000 - selector: - app: grafana ---- -apiVersion: v1 -kind: PersistentVolumeClaim -metadata: - name: grafana-pvc - namespace: monitoring -spec: - accessModes: - - ReadWriteOnce - resources: - requests: - storage: 10Gi diff --git a/infra/kubernetes/monitoring/prometheus.yaml b/infra/kubernetes/monitoring/prometheus.yaml deleted file mode 100644 index f86f9172fb7614b5b32f289a1bea8728acf6ace4..0000000000000000000000000000000000000000 --- a/infra/kubernetes/monitoring/prometheus.yaml +++ /dev/null @@ -1,137 +0,0 @@ -apiVersion: v1 -kind: ServiceAccount -metadata: - name: prometheus - namespace: monitoring ---- -apiVersion: rbac.authorization.k8s.io/v1 -kind: ClusterRole -metadata: - name: prometheus -rules: - - apiGroups: [""] - resources: - - nodes - - nodes/proxy - - services - - endpoints - - pods - verbs: ["get", "list", "watch"] - - apiGroups: - - extensions - resources: - - ingresses - verbs: ["get", "list", "watch"] ---- -apiVersion: rbac.authorization.k8s.io/v1 -kind: ClusterRoleBinding -metadata: - name: prometheus -roleRef: - apiGroup: rbac.authorization.k8s.io - kind: ClusterRole - name: prometheus -subjects: - - kind: ServiceAccount - name: prometheus - namespace: monitoring ---- -apiVersion: v1 -kind: ConfigMap -metadata: - name: prometheus-config - namespace: monitoring -data: - prometheus.yml: | - global: - scrape_interval: 15s - evaluation_interval: 15s - - scrape_configs: - - job_name: 'yaz-api' - kubernetes_sd_configs: - - role: pod - namespaces: - names: - - yaz-production - relabel_configs: - - source_labels: [__meta_kubernetes_pod_label_app] - action: keep - regex: yaz-api - - source_labels: [__address__] - action: replace - regex: ([^:]+)(?::\d+)? - replacement: ${1}:9090 - target_label: __address__ - - - job_name: 'postgres' - static_configs: - - targets: ['postgres-exporter:9187'] - - - job_name: 'redis' - static_configs: - - targets: ['redis-exporter:9121'] ---- -apiVersion: apps/v1 -kind: Deployment -metadata: - name: prometheus - namespace: monitoring -spec: - replicas: 1 - selector: - matchLabels: - app: prometheus - template: - metadata: - labels: - app: prometheus - spec: - serviceAccountName: prometheus - containers: - - name: prometheus - image: prom/prometheus:latest - args: - - "--config.file=/etc/prometheus/prometheus.yml" - - "--storage.tsdb.path=/prometheus" - - "--storage.tsdb.retention.time=30d" - ports: - - containerPort: 9090 - name: web - volumeMounts: - - name: config - mountPath: /etc/prometheus - - name: storage - mountPath: /prometheus - volumes: - - name: config - configMap: - name: prometheus-config - - name: storage - persistentVolumeClaim: - claimName: prometheus-pvc ---- -apiVersion: v1 -kind: Service -metadata: - name: prometheus - namespace: monitoring -spec: - type: ClusterIP - ports: - - port: 9090 - targetPort: 9090 - selector: - app: prometheus ---- -apiVersion: v1 -kind: PersistentVolumeClaim -metadata: - name: prometheus-pvc - namespace: monitoring -spec: - accessModes: - - ReadWriteOnce - resources: - requests: - storage: 50Gi diff --git a/infra/kubernetes/monitoring/tracing-stack.yaml b/infra/kubernetes/monitoring/tracing-stack.yaml deleted file mode 100644 index 72155161cb416dc55c9c1ae5384dfa7dad046fa1..0000000000000000000000000000000000000000 --- a/infra/kubernetes/monitoring/tracing-stack.yaml +++ /dev/null @@ -1,289 +0,0 @@ ---- -# Grafana Tempo Deployment -apiVersion: apps/v1 -kind: Deployment -metadata: - name: tempo - namespace: yaz-care-monitoring - labels: - app: tempo - component: tracing -spec: - replicas: 2 - selector: - matchLabels: - app: tempo - template: - metadata: - labels: - app: tempo - spec: - serviceAccountName: tempo - containers: - - name: tempo - image: grafana/tempo:latest - args: - - -config.file=/etc/tempo/tempo.yaml - ports: - - name: http - containerPort: 3200 - - name: otlp-grpc - containerPort: 4317 - - name: otlp-http - containerPort: 4318 - - name: jaeger-grpc - containerPort: 14250 - - name: jaeger-http - containerPort: 14268 - - name: zipkin - containerPort: 9411 - volumeMounts: - - name: config - mountPath: /etc/tempo - - name: storage - mountPath: /var/tempo - resources: - requests: - memory: "1Gi" - cpu: "500m" - limits: - memory: "4Gi" - cpu: "2000m" - livenessProbe: - httpGet: - path: /ready - port: 3200 - initialDelaySeconds: 45 - readinessProbe: - httpGet: - path: /ready - port: 3200 - initialDelaySeconds: 15 - volumes: - - name: config - configMap: - name: tempo-config - - name: storage - persistentVolumeClaim: - claimName: tempo-storage - ---- -# Tempo Service -apiVersion: v1 -kind: Service -metadata: - name: tempo - namespace: yaz-care-monitoring -spec: - selector: - app: tempo - ports: - - name: http - port: 3200 - targetPort: 3200 - - name: otlp-grpc - port: 4317 - targetPort: 4317 - - name: otlp-http - port: 4318 - targetPort: 4318 - - name: jaeger-grpc - port: 14250 - targetPort: 14250 - - name: jaeger-http - port: 14268 - targetPort: 14268 - - name: zipkin - port: 9411 - targetPort: 9411 - ---- -# OpenTelemetry Collector Deployment -apiVersion: apps/v1 -kind: Deployment -metadata: - name: otel-collector - namespace: yaz-care-monitoring - labels: - app: otel-collector - component: telemetry -spec: - replicas: 3 - selector: - matchLabels: - app: otel-collector - template: - metadata: - labels: - app: otel-collector - spec: - serviceAccountName: otel-collector - containers: - - name: otel-collector - image: otel/opentelemetry-collector-contrib:latest - command: - - /otelcol-contrib - - --config=/etc/otel/config.yaml - ports: - - name: otlp-grpc - containerPort: 4317 - - name: otlp-http - containerPort: 4318 - - name: jaeger-grpc - containerPort: 14250 - - name: jaeger-http - containerPort: 14268 - - name: zipkin - containerPort: 9411 - - name: prometheus - containerPort: 8889 - - name: health - containerPort: 13133 - volumeMounts: - - name: config - mountPath: /etc/otel - - name: logs - mountPath: /var/log/otel - env: - - name: ENVIRONMENT - value: "production" - - name: VERSION - value: "5.0.2" - resources: - requests: - memory: "512Mi" - cpu: "250m" - limits: - memory: "2Gi" - cpu: "1000m" - livenessProbe: - httpGet: - path: /health - port: 13133 - initialDelaySeconds: 30 - readinessProbe: - httpGet: - path: /health - port: 13133 - initialDelaySeconds: 10 - volumes: - - name: config - configMap: - name: otel-collector-config - - name: logs - emptyDir: - sizeLimit: "5Gi" - ---- -# OpenTelemetry Collector Service -apiVersion: v1 -kind: Service -metadata: - name: otel-collector - namespace: yaz-care-monitoring -spec: - selector: - app: otel-collector - ports: - - name: otlp-grpc - port: 4317 - targetPort: 4317 - - name: otlp-http - port: 4318 - targetPort: 4318 - - name: jaeger-grpc - port: 14250 - targetPort: 14250 - - name: jaeger-http - port: 14268 - targetPort: 14268 - - name: zipkin - port: 9411 - targetPort: 9411 - - name: prometheus - port: 8889 - targetPort: 8889 - - name: health - port: 13133 - targetPort: 13133 - ---- -# ConfigMaps -apiVersion: v1 -kind: ConfigMap -metadata: - name: tempo-config - namespace: yaz-care-monitoring -data: - tempo.yaml: | - # Tempo configuration loaded from external file - # See: infra/monitoring/tempo-config.yaml - ---- -apiVersion: v1 -kind: ConfigMap -metadata: - name: otel-collector-config - namespace: yaz-care-monitoring -data: - config.yaml: | - # OpenTelemetry Collector configuration - # See: infra/monitoring/otel-collector-config.yaml - ---- -# PersistentVolumeClaim for Tempo -apiVersion: v1 -kind: PersistentVolumeClaim -metadata: - name: tempo-storage - namespace: yaz-care-monitoring -spec: - accessModes: - - ReadWriteOnce - resources: - requests: - storage: 100Gi - storageClassName: fast-ssd - ---- -# ServiceAccounts -apiVersion: v1 -kind: ServiceAccount -metadata: - name: tempo - namespace: yaz-care-monitoring - ---- -apiVersion: v1 -kind: ServiceAccount -metadata: - name: otel-collector - namespace: yaz-care-monitoring - ---- -# HorizontalPodAutoscaler for OTel Collector -apiVersion: autoscaling/v2 -kind: HorizontalPodAutoscaler -metadata: - name: otel-collector-hpa - namespace: yaz-care-monitoring -spec: - scaleTargetRef: - apiVersion: apps/v1 - kind: Deployment - name: otel-collector - minReplicas: 3 - maxReplicas: 10 - metrics: - - type: Resource - resource: - name: cpu - target: - type: Utilization - averageUtilization: 70 - - type: Resource - resource: - name: memory - target: - type: Utilization - averageUtilization: 80 diff --git a/infra/kubernetes/namespace.yaml b/infra/kubernetes/namespace.yaml deleted file mode 100644 index 55b158542dd748451ac0ab6a3a83531cf1c50e54..0000000000000000000000000000000000000000 --- a/infra/kubernetes/namespace.yaml +++ /dev/null @@ -1,9 +0,0 @@ ---- -apiVersion: v1 -kind: Namespace -metadata: - name: yaz-care - labels: - app: yaz-care - environment: production - managed-by: kubernetes diff --git a/infra/kubernetes/postgres-statefulset.yaml b/infra/kubernetes/postgres-statefulset.yaml deleted file mode 100644 index b81ab5802e479e96c419a85989413cab9027d85f..0000000000000000000000000000000000000000 --- a/infra/kubernetes/postgres-statefulset.yaml +++ /dev/null @@ -1,166 +0,0 @@ ---- -apiVersion: apps/v1 -kind: StatefulSet -metadata: - name: postgres - namespace: yaz-care - labels: - app: postgres -spec: - serviceName: postgres - replicas: 1 - selector: - matchLabels: - app: postgres - - template: - metadata: - labels: - app: postgres - spec: - containers: - - name: postgres - image: postgres:15-alpine - - ports: - - name: postgres - containerPort: 5432 - protocol: TCP - - env: - - name: POSTGRES_DB - value: yaz_care_prod - - name: POSTGRES_USER - valueFrom: - secretKeyRef: - name: yaz-care-secrets - key: POSTGRES_USER - - name: POSTGRES_PASSWORD - valueFrom: - secretKeyRef: - name: yaz-care-secrets - key: POSTGRES_PASSWORD - - name: PGDATA - value: /var/lib/postgresql/data/pgdata - - # Performance tuning - - name: POSTGRES_SHARED_BUFFERS - value: "256MB" - - name: POSTGRES_EFFECTIVE_CACHE_SIZE - value: "1GB" - - name: POSTGRES_MAINTENANCE_WORK_MEM - value: "64MB" - - name: POSTGRES_WORK_MEM - value: "16MB" - - volumeMounts: - - name: postgres-storage - mountPath: /var/lib/postgresql/data - - name: postgres-config - mountPath: /etc/postgresql/postgresql.conf - subPath: postgresql.conf - - resources: - requests: - memory: "1Gi" - cpu: "500m" - limits: - memory: "4Gi" - cpu: "2000m" - - livenessProbe: - exec: - command: - - pg_isready - - -U - - yaz_care - initialDelaySeconds: 30 - periodSeconds: 10 - timeoutSeconds: 5 - failureThreshold: 3 - - readinessProbe: - exec: - command: - - pg_isready - - -U - - yaz_care - initialDelaySeconds: 10 - periodSeconds: 5 - timeoutSeconds: 3 - failureThreshold: 3 - - volumes: - - name: postgres-config - configMap: - name: postgres-config - - securityContext: - fsGroup: 999 - - volumeClaimTemplates: - - metadata: - name: postgres-storage - spec: - accessModes: ["ReadWriteOnce"] - resources: - requests: - storage: 50Gi - # storageClassName: fast-ssd # Uncomment for specific storage class - ---- -apiVersion: v1 -kind: Service -metadata: - name: postgres - namespace: yaz-care - labels: - app: postgres -spec: - type: ClusterIP - ports: - - name: postgres - port: 5432 - targetPort: 5432 - protocol: TCP - selector: - app: postgres - ---- -apiVersion: v1 -kind: ConfigMap -metadata: - name: postgres-config - namespace: yaz-care -data: - postgresql.conf: | - # Connection settings - max_connections = 200 - shared_buffers = 256MB - - # Memory settings - effective_cache_size = 1GB - maintenance_work_mem = 64MB - work_mem = 16MB - - # WAL settings - wal_level = replica - max_wal_size = 1GB - min_wal_size = 80MB - - # Query tuning - random_page_cost = 1.1 - effective_io_concurrency = 200 - - # Logging - log_destination = 'stderr' - logging_collector = on - log_directory = 'log' - log_filename = 'postgresql-%Y-%m-%d.log' - log_min_duration_statement = 1000 - log_line_prefix = '%t [%p]: [%l-1] user=%u,db=%d,app=%a,client=%h ' - - # Statistics - track_activities = on - track_counts = on - track_io_timing = on diff --git a/infra/kubernetes/production/api-deployment.yaml b/infra/kubernetes/production/api-deployment.yaml deleted file mode 100644 index 9c217dfd71f5d9dc7240372e193ed930e7550926..0000000000000000000000000000000000000000 --- a/infra/kubernetes/production/api-deployment.yaml +++ /dev/null @@ -1,155 +0,0 @@ -apiVersion: apps/v1 -kind: Deployment -metadata: - name: yaz-api - namespace: yaz-production - labels: - app: yaz-api - version: v2.9.0 -spec: - replicas: 3 - selector: - matchLabels: - app: yaz-api - strategy: - type: RollingUpdate - rollingUpdate: - maxSurge: 1 - maxUnavailable: 0 - template: - metadata: - labels: - app: yaz-api - version: v2.9.0 - spec: - containers: - - name: api - image: ghcr.io/elanass/yaz:latest - imagePullPolicy: Always - ports: - - containerPort: 8000 - name: http - protocol: TCP - env: - - name: ENVIRONMENT - value: "production" - - name: DATABASE_URL - valueFrom: - secretKeyRef: - name: yaz-secrets - key: database-url - - name: REDIS_URL - valueFrom: - secretKeyRef: - name: yaz-secrets - key: redis-url - - name: SECRET_KEY - valueFrom: - secretKeyRef: - name: yaz-secrets - key: secret-key - - name: PYTHONPATH - value: "/app/src" - resources: - requests: - memory: "512Mi" - cpu: "500m" - limits: - memory: "2Gi" - cpu: "2000m" - livenessProbe: - httpGet: - path: /health - port: 8000 - initialDelaySeconds: 30 - periodSeconds: 10 - timeoutSeconds: 5 - failureThreshold: 3 - readinessProbe: - httpGet: - path: /ready - port: 8000 - initialDelaySeconds: 10 - periodSeconds: 5 - timeoutSeconds: 3 - failureThreshold: 3 - volumeMounts: - - name: config - mountPath: /app/config - readOnly: true - volumes: - - name: config - configMap: - name: yaz-config - affinity: - podAntiAffinity: - preferredDuringSchedulingIgnoredDuringExecution: - - weight: 100 - podAffinityTerm: - labelSelector: - matchExpressions: - - key: app - operator: In - values: - - yaz-api - topologyKey: kubernetes.io/hostname ---- -apiVersion: v1 -kind: Service -metadata: - name: yaz-api-service - namespace: yaz-production - labels: - app: yaz-api -spec: - type: ClusterIP - ports: - - port: 80 - targetPort: 8000 - protocol: TCP - name: http - selector: - app: yaz-api ---- -apiVersion: autoscaling/v2 -kind: HorizontalPodAutoscaler -metadata: - name: yaz-api-hpa - namespace: yaz-production -spec: - scaleTargetRef: - apiVersion: apps/v1 - kind: Deployment - name: yaz-api - minReplicas: 3 - maxReplicas: 10 - metrics: - - type: Resource - resource: - name: cpu - target: - type: Utilization - averageUtilization: 70 - - type: Resource - resource: - name: memory - target: - type: Utilization - averageUtilization: 80 - behavior: - scaleDown: - stabilizationWindowSeconds: 300 - policies: - - type: Percent - value: 50 - periodSeconds: 60 - scaleUp: - stabilizationWindowSeconds: 60 - policies: - - type: Percent - value: 100 - periodSeconds: 30 - - type: Pods - value: 2 - periodSeconds: 30 - selectPolicy: Max diff --git a/infra/kubernetes/production/backup-cronjob.yaml b/infra/kubernetes/production/backup-cronjob.yaml deleted file mode 100644 index 13ba4dd18ef570bb85035598606fea0ebfa1a561..0000000000000000000000000000000000000000 --- a/infra/kubernetes/production/backup-cronjob.yaml +++ /dev/null @@ -1,57 +0,0 @@ -apiVersion: batch/v1 -kind: CronJob -metadata: - name: database-backup - namespace: yaz-production -spec: - schedule: "0 2 * * *" # Daily at 2 AM UTC - concurrencyPolicy: Forbid - successfulJobsHistoryLimit: 7 - failedJobsHistoryLimit: 3 - jobTemplate: - spec: - template: - spec: - containers: - - name: backup - image: postgres:16-alpine - command: - - /bin/sh - - -c - - | - BACKUP_FILE="/backups/yaz_backup_$(date +%Y%m%d_%H%M%S).sql.gz" - pg_dump $DATABASE_URL | gzip > $BACKUP_FILE - echo "Backup completed: $BACKUP_FILE" - - # Upload to S3 or object storage - # aws s3 cp $BACKUP_FILE s3://yaz-backups/$(date +%Y/%m/%d)/ - - # Cleanup old backups (keep 30 days) - find /backups -name "yaz_backup_*.sql.gz" -mtime +30 -delete - env: - - name: DATABASE_URL - valueFrom: - secretKeyRef: - name: yaz-secrets - key: database-url - volumeMounts: - - name: backup-storage - mountPath: /backups - restartPolicy: OnFailure - volumes: - - name: backup-storage - persistentVolumeClaim: - claimName: backup-pvc ---- -apiVersion: v1 -kind: PersistentVolumeClaim -metadata: - name: backup-pvc - namespace: yaz-production -spec: - accessModes: - - ReadWriteOnce - resources: - requests: - storage: 500Gi - storageClassName: standard diff --git a/infra/kubernetes/production/config.yaml b/infra/kubernetes/production/config.yaml deleted file mode 100644 index 97f41d1ab0057e2fd7572f484f04b91bed248eca..0000000000000000000000000000000000000000 --- a/infra/kubernetes/production/config.yaml +++ /dev/null @@ -1,71 +0,0 @@ -apiVersion: v1 -kind: ConfigMap -metadata: - name: yaz-config - namespace: yaz-production -data: - config.yml: | - environment: production - debug: false - - server: - host: 0.0.0.0 - port: 8000 - workers: 4 - timeout: 120 - - database: - pool_size: 20 - max_overflow: 10 - pool_timeout: 30 - pool_recycle: 3600 - echo: false - - redis: - enabled: true - max_connections: 50 - socket_timeout: 5 - socket_connect_timeout: 5 - - cache: - default_ttl: 300 - max_size: 10000 - - security: - session_timeout: 1800 - mfa_enabled: true - password_min_length: 12 - max_login_attempts: 5 - lockout_duration: 900 - - logging: - level: INFO - format: json - handlers: - - console - - file - - syslog - - monitoring: - enabled: true - prometheus_port: 9090 - health_check_interval: 30 - - backup: - enabled: true - schedule: "0 2 * * *" # Daily at 2 AM - retention_days: 30 - encryption: true ---- -apiVersion: v1 -kind: Secret -metadata: - name: yaz-secrets - namespace: yaz-production -type: Opaque -stringData: - database-url: postgresql://user:password@postgres:5432/yaz_prod - redis-url: redis://:password@redis:6379/0 - secret-key: CHANGE_THIS_IN_PRODUCTION - jwt-secret: CHANGE_THIS_IN_PRODUCTION - encryption-key: CHANGE_THIS_IN_PRODUCTION diff --git a/infra/kubernetes/production/database.yaml b/infra/kubernetes/production/database.yaml deleted file mode 100644 index 5089e43111b94f13d9f5e7ab9e0a63726010e844..0000000000000000000000000000000000000000 --- a/infra/kubernetes/production/database.yaml +++ /dev/null @@ -1,183 +0,0 @@ -apiVersion: v1 -kind: PersistentVolumeClaim -metadata: - name: postgres-pvc - namespace: yaz-production -spec: - accessModes: - - ReadWriteOnce - resources: - requests: - storage: 100Gi - storageClassName: fast-ssd ---- -apiVersion: apps/v1 -kind: StatefulSet -metadata: - name: postgres - namespace: yaz-production -spec: - serviceName: postgres - replicas: 1 - selector: - matchLabels: - app: postgres - template: - metadata: - labels: - app: postgres - spec: - containers: - - name: postgres - image: postgres:16-alpine - ports: - - containerPort: 5432 - name: postgres - env: - - name: POSTGRES_DB - value: yaz_prod - - name: POSTGRES_USER - valueFrom: - secretKeyRef: - name: postgres-secrets - key: username - - name: POSTGRES_PASSWORD - valueFrom: - secretKeyRef: - name: postgres-secrets - key: password - - name: PGDATA - value: /var/lib/postgresql/data/pgdata - volumeMounts: - - name: postgres-storage - mountPath: /var/lib/postgresql/data - resources: - requests: - memory: "2Gi" - cpu: "1000m" - limits: - memory: "4Gi" - cpu: "2000m" - livenessProbe: - exec: - command: - - pg_isready - - -U - - postgres - initialDelaySeconds: 30 - periodSeconds: 10 - readinessProbe: - exec: - command: - - pg_isready - - -U - - postgres - initialDelaySeconds: 5 - periodSeconds: 5 - volumeClaimTemplates: - - metadata: - name: postgres-storage - spec: - accessModes: ["ReadWriteOnce"] - storageClassName: fast-ssd - resources: - requests: - storage: 100Gi ---- -apiVersion: v1 -kind: Service -metadata: - name: postgres - namespace: yaz-production -spec: - type: ClusterIP - ports: - - port: 5432 - targetPort: 5432 - selector: - app: postgres ---- -apiVersion: apps/v1 -kind: Deployment -metadata: - name: redis - namespace: yaz-production -spec: - replicas: 1 - selector: - matchLabels: - app: redis - template: - metadata: - labels: - app: redis - spec: - containers: - - name: redis - image: redis:7-alpine - ports: - - containerPort: 6379 - name: redis - command: - - redis-server - - --requirepass - - $(REDIS_PASSWORD) - - --maxmemory - - 2gb - - --maxmemory-policy - - allkeys-lru - - --appendonly - - "yes" - env: - - name: REDIS_PASSWORD - valueFrom: - secretKeyRef: - name: redis-secrets - key: password - resources: - requests: - memory: "1Gi" - cpu: "500m" - limits: - memory: "2Gi" - cpu: "1000m" - volumeMounts: - - name: redis-storage - mountPath: /data - livenessProbe: - exec: - command: - - redis-cli - - ping - initialDelaySeconds: 30 - periodSeconds: 10 - volumes: - - name: redis-storage - persistentVolumeClaim: - claimName: redis-pvc ---- -apiVersion: v1 -kind: Service -metadata: - name: redis - namespace: yaz-production -spec: - type: ClusterIP - ports: - - port: 6379 - targetPort: 6379 - selector: - app: redis ---- -apiVersion: v1 -kind: PersistentVolumeClaim -metadata: - name: redis-pvc - namespace: yaz-production -spec: - accessModes: - - ReadWriteOnce - resources: - requests: - storage: 20Gi - storageClassName: fast-ssd diff --git a/infra/kubernetes/production/deployment-enhanced.yaml b/infra/kubernetes/production/deployment-enhanced.yaml deleted file mode 100644 index bdaa486274f9d890d09f8960b1a17985832cb03e..0000000000000000000000000000000000000000 --- a/infra/kubernetes/production/deployment-enhanced.yaml +++ /dev/null @@ -1,295 +0,0 @@ ---- -# YAZ Care Platform - Production Deployment Manifest -# Sprint 35: Zero-downtime deployment with advanced health checks -apiVersion: apps/v1 -kind: Deployment -metadata: - name: yaz-care - namespace: yaz-care-production - labels: - app: yaz-care - component: api - version: v5.0.2 - tier: production - annotations: - deployment.kubernetes.io/revision: "1" - prometheus.io/scrape: "true" - prometheus.io/port: "8000" - prometheus.io/path: "/metrics" -spec: - replicas: 3 # High availability - strategy: - type: RollingUpdate - rollingUpdate: - maxSurge: 1 # Allow 1 extra pod during update - maxUnavailable: 0 # Zero-downtime deployment - selector: - matchLabels: - app: yaz-care - component: api - template: - metadata: - labels: - app: yaz-care - component: api - version: v5.0.2 - annotations: - prometheus.io/scrape: "true" - prometheus.io/port: "8000" - seccomp.security.alpha.kubernetes.io/pod: runtime/default - spec: - # Security Context (HIPAA compliance) - securityContext: - runAsNonRoot: true - runAsUser: 1000 - runAsGroup: 1000 - fsGroup: 1000 - seccompProfile: - type: RuntimeDefault - - # Service Account - serviceAccountName: yaz-care - - # Init Container - Database Migration - initContainers: - - name: db-migration - image: ghcr.io/elanass/yaz-care:v5.0.2 - command: - - sh - - -c - - | - echo "Running database migrations..." - alembic upgrade head - echo "Migrations completed successfully" - envFrom: - - configMapRef: - name: yaz-care-config - - secretRef: - name: yaz-care-secrets - resources: - requests: - memory: "256Mi" - cpu: "100m" - limits: - memory: "512Mi" - cpu: "500m" - securityContext: - allowPrivilegeEscalation: false - capabilities: - drop: - - ALL - readOnlyRootFilesystem: false - - # Main Application Container - containers: - - name: yaz-care - image: ghcr.io/elanass/yaz-care:v5.0.2 - imagePullPolicy: IfNotPresent - - # Security Context - securityContext: - allowPrivilegeEscalation: false - capabilities: - drop: - - ALL - readOnlyRootFilesystem: false - runAsNonRoot: true - runAsUser: 1000 - - # Ports - ports: - - name: http - containerPort: 8000 - protocol: TCP - - name: metrics - containerPort: 9090 - protocol: TCP - - # Environment Variables - env: - - name: ENVIRONMENT - value: "production" - - name: LOG_LEVEL - value: "info" - - name: WORKERS - value: "4" - - name: POD_NAME - valueFrom: - fieldRef: - fieldPath: metadata.name - - name: POD_NAMESPACE - valueFrom: - fieldRef: - fieldPath: metadata.namespace - - name: POD_IP - valueFrom: - fieldRef: - fieldPath: status.podIP - - # Environment from ConfigMap and Secrets - envFrom: - - configMapRef: - name: yaz-care-config - - secretRef: - name: yaz-care-secrets - - # Resource Requests and Limits - resources: - requests: - memory: "512Mi" - cpu: "250m" - limits: - memory: "2Gi" - cpu: "1000m" - - # Liveness Probe - Restart if unhealthy - livenessProbe: - httpGet: - path: /api/v1/health - port: http - scheme: HTTP - initialDelaySeconds: 90 - periodSeconds: 30 - timeoutSeconds: 10 - successThreshold: 1 - failureThreshold: 3 - - # Readiness Probe - Remove from load balancer if not ready - readinessProbe: - httpGet: - path: /api/v1/health - port: http - scheme: HTTP - initialDelaySeconds: 30 - periodSeconds: 10 - timeoutSeconds: 5 - successThreshold: 1 - failureThreshold: 3 - - # Startup Probe - Allow slow startup - startupProbe: - httpGet: - path: /api/v1/health - port: http - initialDelaySeconds: 0 - periodSeconds: 10 - timeoutSeconds: 5 - successThreshold: 1 - failureThreshold: 12 # 120 seconds max startup time - - # Volume Mounts - volumeMounts: - - name: logs - mountPath: /app/logs - - name: data - mountPath: /app/data - - name: config - mountPath: /app/config/production - readOnly: true - - name: tmp - mountPath: /tmp - - # Volumes - volumes: - - name: logs - persistentVolumeClaim: - claimName: yaz-care-logs - - name: data - persistentVolumeClaim: - claimName: yaz-care-data - - name: config - configMap: - name: yaz-care-config - - name: tmp - emptyDir: - sizeLimit: "1Gi" - - # Pod Anti-Affinity - Spread pods across nodes - affinity: - podAntiAffinity: - preferredDuringSchedulingIgnoredDuringExecution: - - weight: 100 - podAffinityTerm: - labelSelector: - matchExpressions: - - key: app - operator: In - values: - - yaz-care - topologyKey: kubernetes.io/hostname - - # Tolerations - tolerations: - - key: "node-role.kubernetes.io/production" - operator: "Equal" - value: "true" - effect: "NoSchedule" - - # DNS Configuration - dnsPolicy: ClusterFirst - - # Termination Grace Period - terminationGracePeriodSeconds: 60 - - # Image Pull Secrets - imagePullSecrets: - - name: ghcr-secret - ---- -# Horizontal Pod Autoscaler -apiVersion: autoscaling/v2 -kind: HorizontalPodAutoscaler -metadata: - name: yaz-care-hpa - namespace: yaz-care-production -spec: - scaleTargetRef: - apiVersion: apps/v1 - kind: Deployment - name: yaz-care - minReplicas: 3 - maxReplicas: 10 - metrics: - - type: Resource - resource: - name: cpu - target: - type: Utilization - averageUtilization: 70 - - type: Resource - resource: - name: memory - target: - type: Utilization - averageUtilization: 80 - behavior: - scaleDown: - stabilizationWindowSeconds: 300 - policies: - - type: Percent - value: 50 - periodSeconds: 60 - scaleUp: - stabilizationWindowSeconds: 0 - policies: - - type: Percent - value: 100 - periodSeconds: 15 - - type: Pods - value: 2 - periodSeconds: 15 - selectPolicy: Max - ---- -# Pod Disruption Budget -apiVersion: policy/v1 -kind: PodDisruptionBudget -metadata: - name: yaz-care-pdb - namespace: yaz-care-production -spec: - minAvailable: 2 - selector: - matchLabels: - app: yaz-care - component: api diff --git a/infra/kubernetes/production/ingress.yaml b/infra/kubernetes/production/ingress.yaml deleted file mode 100644 index e0415f532ef480e3b76f5f49fd59859f871148a4..0000000000000000000000000000000000000000 --- a/infra/kubernetes/production/ingress.yaml +++ /dev/null @@ -1,45 +0,0 @@ -apiVersion: networking.k8s.io/v1 -kind: Ingress -metadata: - name: yaz-ingress - namespace: yaz-production - annotations: - kubernetes.io/ingress.class: nginx - cert-manager.io/cluster-issuer: letsencrypt-prod - nginx.ingress.kubernetes.io/ssl-redirect: "true" - nginx.ingress.kubernetes.io/force-ssl-redirect: "true" - nginx.ingress.kubernetes.io/rate-limit: "100" - nginx.ingress.kubernetes.io/proxy-body-size: "50m" - nginx.ingress.kubernetes.io/proxy-read-timeout: "120" - nginx.ingress.kubernetes.io/proxy-send-timeout: "120" - nginx.ingress.kubernetes.io/enable-cors: "true" - nginx.ingress.kubernetes.io/cors-allow-origin: "https://app.yazcare.com" - nginx.ingress.kubernetes.io/cors-allow-methods: "GET, POST, PUT, PATCH, DELETE, OPTIONS" - nginx.ingress.kubernetes.io/cors-allow-headers: "Authorization, Content-Type" -spec: - tls: - - hosts: - - app.yazcare.com - - api.yazcare.com - secretName: yaz-tls-cert - rules: - - host: api.yazcare.com - http: - paths: - - path: / - pathType: Prefix - backend: - service: - name: yaz-api-service - port: - number: 80 - - host: app.yazcare.com - http: - paths: - - path: /api - pathType: Prefix - backend: - service: - name: yaz-api-service - port: - number: 80 diff --git a/infra/kubernetes/redis-statefulset.yaml b/infra/kubernetes/redis-statefulset.yaml deleted file mode 100644 index 561641ea15da7bf970afffeddcb7d88419de220a..0000000000000000000000000000000000000000 --- a/infra/kubernetes/redis-statefulset.yaml +++ /dev/null @@ -1,191 +0,0 @@ ---- -apiVersion: apps/v1 -kind: StatefulSet -metadata: - name: redis - namespace: yaz-care - labels: - app: redis -spec: - serviceName: redis - replicas: 3 - selector: - matchLabels: - app: redis - - template: - metadata: - labels: - app: redis - spec: - containers: - - name: redis - image: redis:7-alpine - - command: - - redis-server - - /etc/redis/redis.conf - - ports: - - name: client - containerPort: 6379 - protocol: TCP - - name: gossip - containerPort: 16379 - protocol: TCP - - env: - - name: REDIS_PASSWORD - valueFrom: - secretKeyRef: - name: yaz-care-secrets - key: REDIS_PASSWORD - - volumeMounts: - - name: redis-storage - mountPath: /data - - name: redis-config - mountPath: /etc/redis/redis.conf - subPath: redis.conf - - resources: - requests: - memory: "512Mi" - cpu: "250m" - limits: - memory: "2Gi" - cpu: "1000m" - - livenessProbe: - exec: - command: - - redis-cli - - ping - initialDelaySeconds: 30 - periodSeconds: 10 - timeoutSeconds: 5 - failureThreshold: 3 - - readinessProbe: - exec: - command: - - redis-cli - - ping - initialDelaySeconds: 10 - periodSeconds: 5 - timeoutSeconds: 3 - failureThreshold: 3 - - volumes: - - name: redis-config - configMap: - name: redis-config - - volumeClaimTemplates: - - metadata: - name: redis-storage - spec: - accessModes: ["ReadWriteOnce"] - resources: - requests: - storage: 10Gi - ---- -apiVersion: v1 -kind: Service -metadata: - name: redis - namespace: yaz-care - labels: - app: redis -spec: - type: ClusterIP - ports: - - name: client - port: 6379 - targetPort: 6379 - protocol: TCP - - name: gossip - port: 16379 - targetPort: 16379 - protocol: TCP - selector: - app: redis - ---- -apiVersion: v1 -kind: Service -metadata: - name: redis-headless - namespace: yaz-care - labels: - app: redis -spec: - type: ClusterIP - clusterIP: None - ports: - - name: client - port: 6379 - targetPort: 6379 - protocol: TCP - - name: gossip - port: 16379 - targetPort: 16379 - protocol: TCP - selector: - app: redis - ---- -apiVersion: v1 -kind: ConfigMap -metadata: - name: redis-config - namespace: yaz-care -data: - redis.conf: | - # Network - bind 0.0.0.0 - port 6379 - tcp-backlog 511 - timeout 0 - tcp-keepalive 300 - - # General - daemonize no - supervised no - pidfile /var/run/redis.pid - loglevel notice - - # Persistence - appendonly yes - appendfilename "appendonly.aof" - appendfsync everysec - no-appendfsync-on-rewrite no - auto-aof-rewrite-percentage 100 - auto-aof-rewrite-min-size 64mb - - # RDB snapshots - save 900 1 - save 300 10 - save 60 10000 - stop-writes-on-bgsave-error yes - rdbcompression yes - rdbchecksum yes - dbfilename dump.rdb - dir /data - - # Memory management - maxmemory 1gb - maxmemory-policy allkeys-lru - - # Cluster mode (enable for multi-node) - # cluster-enabled yes - # cluster-config-file nodes.conf - # cluster-node-timeout 5000 - - # Security - # requirepass ${REDIS_PASSWORD} - - # Performance - slowlog-log-slower-than 10000 - slowlog-max-len 128 diff --git a/infra/kubernetes/regions/africa-north/deployment.yaml b/infra/kubernetes/regions/africa-north/deployment.yaml deleted file mode 100644 index 070a688fba8593bb6c9f005bf93cc4981af130a0..0000000000000000000000000000000000000000 --- a/infra/kubernetes/regions/africa-north/deployment.yaml +++ /dev/null @@ -1,389 +0,0 @@ -# YAZ Care Platform - Morocco (Africa North) Region Deployment -# Primary region for YAZ Care Platform -# Optimized for North Africa + Middle East + Southern Europe latency - -apiVersion: v1 -kind: Namespace -metadata: - name: yaz-care - labels: - name: yaz-care - environment: production - region: africa-north - country: morocco - primary-region: "true" - ---- -# Region-specific ConfigMap -apiVersion: v1 -kind: ConfigMap -metadata: - name: yaz-config-morocco - namespace: yaz-care - labels: - region: africa-north -data: - # Application Settings - APP_ENV: "production" - PYTHONPATH: "/app/src" - LOG_LEVEL: "INFO" - ENABLE_METRICS: "true" - ENABLE_TRACING: "true" - - # Region Configuration - REGION: "africa-north-1" - REGION_CODE: "ma-1" - REGION_NAME: "Morocco Primary" - TIMEZONE: "Africa/Casablanca" - DEFAULT_LOCALE: "fr-MA" - SUPPORTED_LOCALES: "fr-MA,ar-MA,en-US" - - # Database Configuration - DATABASE_HOST: "postgres-primary.yaz-care.svc.cluster.local" - DATABASE_READ_HOST: "postgres-replica.yaz-care.svc.cluster.local" - DATABASE_PORT: "5432" - - # Redis Configuration - REDIS_HOST: "redis-cluster.yaz-care.svc.cluster.local" - REDIS_PORT: "6379" - REDIS_CLUSTER_MODE: "true" - - # Observability - JAEGER_ENDPOINT: "http://jaeger.observability.svc.cluster.local:14268/api/traces" - PROMETHEUS_GATEWAY: "http://prometheus.observability.svc.cluster.local:9090" - OTEL_EXPORTER_OTLP_ENDPOINT: "http://otel-collector.observability.svc.cluster.local:4317" - - # CDN & Edge Configuration - CDN_ENABLED: "true" - CDN_PROVIDER: "cloudflare" - EDGE_CACHE_TTL: "3600" - - # Healthcare Compliance (Morocco + EU GDPR) - HIPAA_AUDIT_ENABLED: "true" - GDPR_COMPLIANCE_ENABLED: "true" - DATA_RESIDENCY: "morocco" - PHI_ENCRYPTION_ENABLED: "true" - AUDIT_LOG_RETENTION_DAYS: "2555" - ---- -# Main Web Application Deployment -apiVersion: apps/v1 -kind: Deployment -metadata: - name: yaz-web - namespace: yaz-care - labels: - app: yaz-web - version: v6.0.0 - region: africa-north -spec: - replicas: 3 - strategy: - type: RollingUpdate - rollingUpdate: - maxSurge: 1 - maxUnavailable: 0 - selector: - matchLabels: - app: yaz-web - template: - metadata: - labels: - app: yaz-web - version: v6.0.0 - region: africa-north - annotations: - prometheus.io/scrape: "true" - prometheus.io/port: "8000" - prometheus.io/path: "/metrics" - spec: - affinity: - podAntiAffinity: - preferredDuringSchedulingIgnoredDuringExecution: - - weight: 100 - podAffinityTerm: - labelSelector: - matchExpressions: - - key: app - operator: In - values: - - yaz-web - topologyKey: kubernetes.io/hostname - containers: - - name: yaz-web - image: yazcare/yaz-platform:v6.0.0 - imagePullPolicy: Always - ports: - - name: http - containerPort: 8000 - protocol: TCP - - name: metrics - containerPort: 9090 - protocol: TCP - envFrom: - - configMapRef: - name: yaz-config-morocco - - secretRef: - name: yaz-secrets - env: - - name: POD_NAME - valueFrom: - fieldRef: - fieldPath: metadata.name - - name: POD_IP - valueFrom: - fieldRef: - fieldPath: status.podIP - resources: - requests: - memory: "512Mi" - cpu: "250m" - limits: - memory: "2Gi" - cpu: "2000m" - livenessProbe: - httpGet: - path: /health/liveness - port: 8000 - initialDelaySeconds: 30 - periodSeconds: 10 - timeoutSeconds: 5 - failureThreshold: 3 - readinessProbe: - httpGet: - path: /health/readiness - port: 8000 - initialDelaySeconds: 10 - periodSeconds: 5 - timeoutSeconds: 3 - failureThreshold: 3 - startupProbe: - httpGet: - path: /health - port: 8000 - initialDelaySeconds: 5 - periodSeconds: 5 - failureThreshold: 30 - volumeMounts: - - name: app-logs - mountPath: /app/logs - - name: tmp - mountPath: /tmp - securityContext: - runAsNonRoot: true - runAsUser: 1000 - readOnlyRootFilesystem: true - allowPrivilegeEscalation: false - volumes: - - name: app-logs - emptyDir: {} - - name: tmp - emptyDir: {} - securityContext: - fsGroup: 1000 - terminationGracePeriodSeconds: 30 - ---- -# Service for Web Application -apiVersion: v1 -kind: Service -metadata: - name: yaz-web-service - namespace: yaz-care - labels: - app: yaz-web - region: africa-north -spec: - type: ClusterIP - ports: - - name: http - port: 80 - targetPort: 8000 - protocol: TCP - - name: metrics - port: 9090 - targetPort: 9090 - protocol: TCP - selector: - app: yaz-web - ---- -# Horizontal Pod Autoscaler -apiVersion: autoscaling/v2 -kind: HorizontalPodAutoscaler -metadata: - name: yaz-web-hpa - namespace: yaz-care -spec: - scaleTargetRef: - apiVersion: apps/v1 - kind: Deployment - name: yaz-web - minReplicas: 3 - maxReplicas: 20 - metrics: - - type: Resource - resource: - name: cpu - target: - type: Utilization - averageUtilization: 70 - - type: Resource - resource: - name: memory - target: - type: Utilization - averageUtilization: 80 - - type: Pods - pods: - metric: - name: http_requests_per_second - target: - type: AverageValue - averageValue: "1000" - behavior: - scaleDown: - stabilizationWindowSeconds: 300 - policies: - - type: Percent - value: 10 - periodSeconds: 60 - scaleUp: - stabilizationWindowSeconds: 0 - policies: - - type: Percent - value: 100 - periodSeconds: 15 - - type: Pods - value: 4 - periodSeconds: 15 - selectPolicy: Max - ---- -# Ingress for Morocco Primary Region -apiVersion: networking.k8s.io/v1 -kind: Ingress -metadata: - name: yaz-ingress-morocco - namespace: yaz-care - annotations: - kubernetes.io/ingress.class: nginx - nginx.ingress.kubernetes.io/ssl-redirect: "true" - nginx.ingress.kubernetes.io/proxy-body-size: "50m" - nginx.ingress.kubernetes.io/proxy-read-timeout: "300" - nginx.ingress.kubernetes.io/proxy-send-timeout: "300" - nginx.ingress.kubernetes.io/proxy-connect-timeout: "60" - nginx.ingress.kubernetes.io/rate-limit: "100" - nginx.ingress.kubernetes.io/rate-limit-window: "1m" - cert-manager.io/cluster-issuer: "letsencrypt-prod" - # Cloudflare integration - external-dns.alpha.kubernetes.io/cloudflare-proxied: "true" - # Security headers - nginx.ingress.kubernetes.io/configuration-snippet: | - add_header X-Frame-Options "DENY" always; - add_header X-Content-Type-Options "nosniff" always; - add_header X-XSS-Protection "1; mode=block" always; - add_header Referrer-Policy "strict-origin-when-cross-origin" always; - add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self' data:; connect-src 'self' wss: https:;" always; -spec: - tls: - - hosts: - - yazcare.ma - - app.yazcare.ma - - api.yazcare.ma - secretName: yaz-tls-morocco - rules: - - host: yazcare.ma - http: - paths: - - path: / - pathType: Prefix - backend: - service: - name: yaz-web-service - port: - number: 80 - - host: app.yazcare.ma - http: - paths: - - path: / - pathType: Prefix - backend: - service: - name: yaz-web-service - port: - number: 80 - - host: api.yazcare.ma - http: - paths: - - path: / - pathType: Prefix - backend: - service: - name: yaz-web-service - port: - number: 80 - ---- -# Pod Disruption Budget for High Availability -apiVersion: policy/v1 -kind: PodDisruptionBudget -metadata: - name: yaz-web-pdb - namespace: yaz-care -spec: - minAvailable: 2 - selector: - matchLabels: - app: yaz-web - ---- -# Network Policy for Security -apiVersion: networking.k8s.io/v1 -kind: NetworkPolicy -metadata: - name: yaz-web-network-policy - namespace: yaz-care -spec: - podSelector: - matchLabels: - app: yaz-web - policyTypes: - - Ingress - - Egress - ingress: - - from: - - namespaceSelector: - matchLabels: - name: ingress-nginx - - podSelector: - matchLabels: - app: prometheus - ports: - - protocol: TCP - port: 8000 - - protocol: TCP - port: 9090 - egress: - - to: - - podSelector: - matchLabels: - app: postgres - ports: - - protocol: TCP - port: 5432 - - to: - - podSelector: - matchLabels: - app: redis - ports: - - protocol: TCP - port: 6379 - - to: - - namespaceSelector: {} - podSelector: - matchLabels: - k8s-app: kube-dns - ports: - - protocol: UDP - port: 53 diff --git a/infra/kubernetes/regions/africa-north/observability.yaml b/infra/kubernetes/regions/africa-north/observability.yaml deleted file mode 100644 index cec22bb4649c277cf284af488adc6962c20d3895..0000000000000000000000000000000000000000 --- a/infra/kubernetes/regions/africa-north/observability.yaml +++ /dev/null @@ -1,753 +0,0 @@ -# YAZ Care Platform - Morocco Observability Stack -# OpenTelemetry, Prometheus, Grafana, Alerting - -apiVersion: v1 -kind: Namespace -metadata: - name: observability - labels: - name: observability - region: africa-north - ---- -# OpenTelemetry Collector Configuration -apiVersion: v1 -kind: ConfigMap -metadata: - name: otel-collector-config - namespace: observability -data: - otel-collector-config.yaml: | - receivers: - otlp: - protocols: - grpc: - endpoint: 0.0.0.0:4317 - http: - endpoint: 0.0.0.0:4318 - prometheus: - config: - scrape_configs: - - job_name: 'yaz-care-apps' - kubernetes_sd_configs: - - role: pod - namespaces: - names: - - yaz-care - relabel_configs: - - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_scrape] - action: keep - regex: true - - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_path] - action: replace - target_label: __metrics_path__ - regex: (.+) - - source_labels: [__address__, __meta_kubernetes_pod_annotation_prometheus_io_port] - action: replace - regex: ([^:]+)(?::\d+)?;(\d+) - replacement: $1:$2 - target_label: __address__ - - processors: - batch: - timeout: 10s - send_batch_size: 1024 - memory_limiter: - check_interval: 1s - limit_mib: 1000 - spike_limit_mib: 200 - resource: - attributes: - - key: service.region - value: africa-north - action: upsert - - key: deployment.environment - value: production - action: upsert - - exporters: - prometheus: - endpoint: "0.0.0.0:8889" - namespace: yaz_care - send_timestamps: true - metric_expiration: 180m - otlp: - endpoint: "jaeger-collector.observability.svc.cluster.local:4317" - tls: - insecure: true - logging: - loglevel: info - - extensions: - health_check: - endpoint: 0.0.0.0:13133 - zpages: - endpoint: 0.0.0.0:55679 - - service: - extensions: [health_check, zpages] - pipelines: - traces: - receivers: [otlp] - processors: [memory_limiter, batch, resource] - exporters: [otlp, logging] - metrics: - receivers: [otlp, prometheus] - processors: [memory_limiter, batch] - exporters: [prometheus] - logs: - receivers: [otlp] - processors: [memory_limiter, batch] - exporters: [logging] - ---- -# OpenTelemetry Collector Deployment -apiVersion: apps/v1 -kind: Deployment -metadata: - name: otel-collector - namespace: observability - labels: - app: otel-collector - region: africa-north -spec: - replicas: 2 - selector: - matchLabels: - app: otel-collector - template: - metadata: - labels: - app: otel-collector - region: africa-north - spec: - containers: - - name: otel-collector - image: otel/opentelemetry-collector-contrib:0.91.0 - args: - - --config=/etc/otel-collector-config.yaml - ports: - - containerPort: 4317 - name: otlp-grpc - - containerPort: 4318 - name: otlp-http - - containerPort: 8889 - name: prometheus - - containerPort: 13133 - name: health - resources: - requests: - memory: "256Mi" - cpu: "200m" - limits: - memory: "1Gi" - cpu: "1000m" - volumeMounts: - - name: otel-config - mountPath: /etc/otel-collector-config.yaml - subPath: otel-collector-config.yaml - livenessProbe: - httpGet: - path: / - port: 13133 - initialDelaySeconds: 10 - periodSeconds: 10 - readinessProbe: - httpGet: - path: / - port: 13133 - initialDelaySeconds: 5 - periodSeconds: 5 - volumes: - - name: otel-config - configMap: - name: otel-collector-config - ---- -# OpenTelemetry Collector Service -apiVersion: v1 -kind: Service -metadata: - name: otel-collector - namespace: observability -spec: - type: ClusterIP - ports: - - port: 4317 - targetPort: 4317 - name: otlp-grpc - - port: 4318 - targetPort: 4318 - name: otlp-http - - port: 8889 - targetPort: 8889 - name: prometheus - selector: - app: otel-collector - ---- -# Prometheus Configuration -apiVersion: v1 -kind: ConfigMap -metadata: - name: prometheus-config - namespace: observability -data: - prometheus.yml: | - global: - scrape_interval: 15s - evaluation_interval: 15s - external_labels: - region: africa-north - cluster: yaz-care-morocco - - alerting: - alertmanagers: - - static_configs: - - targets: - - alertmanager:9093 - - rule_files: - - /etc/prometheus/rules/*.yml - - scrape_configs: - - job_name: 'prometheus' - static_configs: - - targets: ['localhost:9090'] - - - job_name: 'otel-collector' - static_configs: - - targets: ['otel-collector:8889'] - - - job_name: 'yaz-care-pods' - kubernetes_sd_configs: - - role: pod - namespaces: - names: - - yaz-care - relabel_configs: - - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_scrape] - action: keep - regex: true - - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_path] - action: replace - target_label: __metrics_path__ - regex: (.+) - - source_labels: [__address__, __meta_kubernetes_pod_annotation_prometheus_io_port] - action: replace - regex: ([^:]+)(?::\d+)?;(\d+) - replacement: $1:$2 - target_label: __address__ - - action: labelmap - regex: __meta_kubernetes_pod_label_(.+) - - source_labels: [__meta_kubernetes_namespace] - action: replace - target_label: kubernetes_namespace - - source_labels: [__meta_kubernetes_pod_name] - action: replace - target_label: kubernetes_pod_name - - - job_name: 'postgres' - static_configs: - - targets: ['postgres-primary.yaz-care:9187', 'postgres-replica.yaz-care:9187'] - - - job_name: 'redis' - static_configs: - - targets: ['redis-cluster.yaz-care:9121'] - - - job_name: 'nginx-ingress' - kubernetes_sd_configs: - - role: pod - namespaces: - names: - - ingress-nginx - relabel_configs: - - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_scrape] - action: keep - regex: true - ---- -# Prometheus Alert Rules -apiVersion: v1 -kind: ConfigMap -metadata: - name: prometheus-rules - namespace: observability -data: - yaz-care-alerts.yml: | - groups: - - name: yaz-care-sla - interval: 30s - rules: - # API Latency SLA - - alert: APILatencyHigh - expr: histogram_quantile(0.95, sum(rate(http_request_duration_seconds_bucket{job="yaz-care-pods"}[5m])) by (le, endpoint)) > 0.2 - for: 5m - labels: - severity: warning - team: platform - annotations: - summary: "API latency exceeds 200ms p95" - description: "Endpoint {{ $labels.endpoint }} has p95 latency of {{ $value }}s" - - - alert: APILatencyCritical - expr: histogram_quantile(0.99, sum(rate(http_request_duration_seconds_bucket{job="yaz-care-pods"}[5m])) by (le, endpoint)) > 0.5 - for: 2m - labels: - severity: critical - team: platform - annotations: - summary: "API latency critical - exceeds 500ms p99" - description: "Endpoint {{ $labels.endpoint }} has p99 latency of {{ $value }}s" - - # Error Rate - - alert: ErrorRateElevated - expr: sum(rate(http_requests_total{status=~"5.."}[5m])) / sum(rate(http_requests_total[5m])) > 0.01 - for: 5m - labels: - severity: warning - team: platform - annotations: - summary: "Error rate exceeds 1%" - description: "Current error rate: {{ $value | humanizePercentage }}" - - - alert: ErrorRateCritical - expr: sum(rate(http_requests_total{status=~"5.."}[5m])) / sum(rate(http_requests_total[5m])) > 0.05 - for: 2m - labels: - severity: critical - team: platform - annotations: - summary: "Error rate critical - exceeds 5%" - description: "Current error rate: {{ $value | humanizePercentage }}" - - # Cache Performance - - alert: CacheHitRateLow - expr: sum(rate(cache_hits_total[5m])) / (sum(rate(cache_hits_total[5m])) + sum(rate(cache_misses_total[5m]))) < 0.90 - for: 10m - labels: - severity: warning - team: platform - annotations: - summary: "Cache hit rate below 90%" - description: "Current cache hit rate: {{ $value | humanizePercentage }}" - - - name: yaz-care-infrastructure - interval: 30s - rules: - # Database - - alert: PostgresConnectionPoolExhausted - expr: pg_stat_activity_count{state="active"} / pg_settings_max_connections > 0.8 - for: 5m - labels: - severity: warning - team: dba - annotations: - summary: "PostgreSQL connection pool >80% utilized" - description: "Active connections: {{ $value | humanizePercentage }} of max" - - - alert: PostgresReplicationLag - expr: pg_replication_lag_seconds > 5 - for: 2m - labels: - severity: critical - team: dba - annotations: - summary: "PostgreSQL replication lag exceeds 5 seconds" - description: "Current lag: {{ $value }}s" - - # Redis - - alert: RedisMemoryHigh - expr: redis_memory_used_bytes / redis_memory_max_bytes > 0.85 - for: 5m - labels: - severity: warning - team: platform - annotations: - summary: "Redis memory usage exceeds 85%" - description: "Memory usage: {{ $value | humanizePercentage }}" - - - alert: RedisClusterDown - expr: redis_cluster_state != 1 - for: 1m - labels: - severity: critical - team: platform - annotations: - summary: "Redis cluster is not healthy" - description: "Cluster state: {{ $value }}" - - # Kubernetes - - alert: PodCrashLooping - expr: rate(kube_pod_container_status_restarts_total{namespace="yaz-care"}[15m]) > 0.1 - for: 5m - labels: - severity: warning - team: platform - annotations: - summary: "Pod is crash looping" - description: "Pod {{ $labels.pod }} is restarting frequently" - - - alert: PodNotReady - expr: kube_pod_status_ready{namespace="yaz-care", condition="true"} == 0 - for: 5m - labels: - severity: warning - team: platform - annotations: - summary: "Pod not ready" - description: "Pod {{ $labels.pod }} has been not ready for 5 minutes" - - - name: yaz-care-security - interval: 30s - rules: - # Tenant Isolation - - alert: TenantIsolationViolation - expr: sum(rate(tenant_isolation_violations_total[5m])) > 0 - for: 1m - labels: - severity: critical - team: security - annotations: - summary: "CRITICAL: Tenant isolation violation detected" - description: "Cross-tenant access attempt detected. Immediate investigation required." - - # PHI Access - - alert: PHIAccessAnomaly - expr: sum(rate(phi_access_total[5m])) / avg_over_time(sum(rate(phi_access_total[5m]))[24h:5m]) > 3 - for: 5m - labels: - severity: warning - team: security - annotations: - summary: "PHI access rate 3x higher than normal" - description: "Unusual PHI access pattern detected. Review audit logs." - - # Authentication - - alert: HighAuthenticationFailures - expr: sum(rate(authentication_failures_total[5m])) > 10 - for: 5m - labels: - severity: warning - team: security - annotations: - summary: "High authentication failure rate" - description: "{{ $value }} auth failures per second. Possible brute force attack." - - - name: yaz-care-clinical - interval: 30s - rules: - # Clinical Algorithm Performance - - alert: ClinicalAlgorithmSlow - expr: histogram_quantile(0.95, sum(rate(clinical_algorithm_duration_seconds_bucket[5m])) by (le, algorithm)) > 0.05 - for: 5m - labels: - severity: warning - team: clinical - annotations: - summary: "Clinical algorithm exceeds 50ms p95" - description: "Algorithm {{ $labels.algorithm }} taking {{ $value }}s" - - # Critical Lab Results - - alert: PanicValueBacklog - expr: sum(panic_values_pending) > 10 - for: 2m - labels: - severity: critical - team: clinical - annotations: - summary: "Panic lab values pending acknowledgment" - description: "{{ $value }} panic values awaiting acknowledgment" - ---- -# Prometheus Deployment -apiVersion: apps/v1 -kind: Deployment -metadata: - name: prometheus - namespace: observability - labels: - app: prometheus - region: africa-north -spec: - replicas: 1 - selector: - matchLabels: - app: prometheus - template: - metadata: - labels: - app: prometheus - region: africa-north - spec: - serviceAccountName: prometheus - containers: - - name: prometheus - image: prom/prometheus:v2.48.0 - args: - - --config.file=/etc/prometheus/prometheus.yml - - --storage.tsdb.path=/prometheus - - --storage.tsdb.retention.time=15d - - --web.enable-lifecycle - - --web.enable-admin-api - ports: - - containerPort: 9090 - name: http - resources: - requests: - memory: "1Gi" - cpu: "500m" - limits: - memory: "4Gi" - cpu: "2000m" - volumeMounts: - - name: prometheus-config - mountPath: /etc/prometheus/prometheus.yml - subPath: prometheus.yml - - name: prometheus-rules - mountPath: /etc/prometheus/rules - - name: prometheus-storage - mountPath: /prometheus - livenessProbe: - httpGet: - path: /-/healthy - port: 9090 - initialDelaySeconds: 30 - periodSeconds: 15 - readinessProbe: - httpGet: - path: /-/ready - port: 9090 - initialDelaySeconds: 5 - periodSeconds: 5 - volumes: - - name: prometheus-config - configMap: - name: prometheus-config - - name: prometheus-rules - configMap: - name: prometheus-rules - - name: prometheus-storage - persistentVolumeClaim: - claimName: prometheus-pvc - ---- -# Prometheus Service -apiVersion: v1 -kind: Service -metadata: - name: prometheus - namespace: observability -spec: - type: ClusterIP - ports: - - port: 9090 - targetPort: 9090 - name: http - selector: - app: prometheus - ---- -# Prometheus PVC -apiVersion: v1 -kind: PersistentVolumeClaim -metadata: - name: prometheus-pvc - namespace: observability -spec: - accessModes: - - ReadWriteOnce - storageClassName: fast-ssd - resources: - requests: - storage: 100Gi - ---- -# Prometheus ServiceAccount -apiVersion: v1 -kind: ServiceAccount -metadata: - name: prometheus - namespace: observability - ---- -# Prometheus ClusterRole -apiVersion: rbac.authorization.k8s.io/v1 -kind: ClusterRole -metadata: - name: prometheus -rules: - - apiGroups: [""] - resources: - - nodes - - nodes/proxy - - services - - endpoints - - pods - verbs: ["get", "list", "watch"] - - apiGroups: ["extensions"] - resources: - - ingresses - verbs: ["get", "list", "watch"] - - nonResourceURLs: ["/metrics"] - verbs: ["get"] - ---- -# Prometheus ClusterRoleBinding -apiVersion: rbac.authorization.k8s.io/v1 -kind: ClusterRoleBinding -metadata: - name: prometheus -roleRef: - apiGroup: rbac.authorization.k8s.io - kind: ClusterRole - name: prometheus -subjects: - - kind: ServiceAccount - name: prometheus - namespace: observability - ---- -# Alertmanager Configuration -apiVersion: v1 -kind: ConfigMap -metadata: - name: alertmanager-config - namespace: observability -data: - alertmanager.yml: | - global: - resolve_timeout: 5m - smtp_smarthost: 'smtp.mailgun.org:587' - smtp_from: 'alerts@yazcare.ma' - - route: - group_by: ['alertname', 'severity', 'team'] - group_wait: 30s - group_interval: 5m - repeat_interval: 4h - receiver: 'default-receiver' - routes: - - match: - severity: critical - receiver: 'critical-receiver' - continue: true - - match: - team: security - receiver: 'security-receiver' - - match: - team: clinical - receiver: 'clinical-receiver' - - match: - team: dba - receiver: 'dba-receiver' - - receivers: - - name: 'default-receiver' - email_configs: - - to: 'platform-team@yazcare.ma' - send_resolved: true - webhook_configs: - - url: 'http://slack-webhook.yaz-care.svc.cluster.local/webhook' - send_resolved: true - - - name: 'critical-receiver' - email_configs: - - to: 'oncall@yazcare.ma' - send_resolved: true - pagerduty_configs: - - service_key_file: /etc/alertmanager/secrets/pagerduty-key - send_resolved: true - webhook_configs: - - url: 'http://slack-webhook.yaz-care.svc.cluster.local/webhook-critical' - send_resolved: true - - - name: 'security-receiver' - email_configs: - - to: 'security@yazcare.ma' - send_resolved: true - webhook_configs: - - url: 'http://slack-webhook.yaz-care.svc.cluster.local/webhook-security' - send_resolved: true - - - name: 'clinical-receiver' - email_configs: - - to: 'clinical-informatics@yazcare.ma' - send_resolved: true - - - name: 'dba-receiver' - email_configs: - - to: 'dba@yazcare.ma' - send_resolved: true - - inhibit_rules: - - source_match: - severity: 'critical' - target_match: - severity: 'warning' - equal: ['alertname', 'instance'] - ---- -# Alertmanager Deployment -apiVersion: apps/v1 -kind: Deployment -metadata: - name: alertmanager - namespace: observability -spec: - replicas: 2 - selector: - matchLabels: - app: alertmanager - template: - metadata: - labels: - app: alertmanager - region: africa-north - spec: - containers: - - name: alertmanager - image: prom/alertmanager:v0.26.0 - args: - - --config.file=/etc/alertmanager/alertmanager.yml - - --storage.path=/alertmanager - - --cluster.listen-address=0.0.0.0:9094 - ports: - - containerPort: 9093 - name: http - - containerPort: 9094 - name: cluster - resources: - requests: - memory: "128Mi" - cpu: "100m" - limits: - memory: "256Mi" - cpu: "200m" - volumeMounts: - - name: alertmanager-config - mountPath: /etc/alertmanager - - name: alertmanager-storage - mountPath: /alertmanager - volumes: - - name: alertmanager-config - configMap: - name: alertmanager-config - - name: alertmanager-storage - emptyDir: {} - ---- -# Alertmanager Service -apiVersion: v1 -kind: Service -metadata: - name: alertmanager - namespace: observability -spec: - type: ClusterIP - ports: - - port: 9093 - targetPort: 9093 - name: http - selector: - app: alertmanager diff --git a/infra/kubernetes/regions/africa-north/postgres.yaml b/infra/kubernetes/regions/africa-north/postgres.yaml deleted file mode 100644 index 556cbde78b968c2a7ea09f8a38ed5758901874d2..0000000000000000000000000000000000000000 --- a/infra/kubernetes/regions/africa-north/postgres.yaml +++ /dev/null @@ -1,432 +0,0 @@ -# YAZ Care Platform - Morocco PostgreSQL Configuration -# Primary database with read replicas for high availability - -apiVersion: v1 -kind: ConfigMap -metadata: - name: postgres-config - namespace: yaz-care - labels: - region: africa-north -data: - POSTGRES_DB: "yazcare_prod" - POSTGRES_USER: "yazcare" - PGDATA: "/var/lib/postgresql/data/pgdata" - # Performance tuning for healthcare workloads - postgresql.conf: | - # Connection Settings - max_connections = 200 - superuser_reserved_connections = 3 - - # Memory Settings (adjust based on node size) - shared_buffers = 2GB - effective_cache_size = 6GB - maintenance_work_mem = 512MB - work_mem = 64MB - - # Write-Ahead Log - wal_level = replica - max_wal_senders = 10 - wal_keep_size = 1GB - synchronous_commit = on - - # Query Planner - random_page_cost = 1.1 - effective_io_concurrency = 200 - - # Parallel Query - max_worker_processes = 8 - max_parallel_workers_per_gather = 4 - max_parallel_workers = 8 - max_parallel_maintenance_workers = 4 - - # Checkpoints - checkpoint_completion_target = 0.9 - checkpoint_timeout = 10min - max_wal_size = 4GB - min_wal_size = 1GB - - # Logging - log_destination = 'stderr' - logging_collector = on - log_directory = 'log' - log_filename = 'postgresql-%Y-%m-%d_%H%M%S.log' - log_statement = 'ddl' - log_min_duration_statement = 200 - log_checkpoints = on - log_connections = on - log_disconnections = on - log_lock_waits = on - - # Autovacuum - autovacuum = on - autovacuum_max_workers = 3 - autovacuum_naptime = 30s - autovacuum_vacuum_cost_limit = 400 - - # SSL/TLS - ssl = on - ssl_cert_file = '/etc/ssl/certs/server.crt' - ssl_key_file = '/etc/ssl/private/server.key' - - # Row Level Security - row_security = on - ---- -# Primary PostgreSQL StatefulSet -apiVersion: apps/v1 -kind: StatefulSet -metadata: - name: postgres-primary - namespace: yaz-care - labels: - app: postgres - role: primary - region: africa-north -spec: - serviceName: postgres-primary - replicas: 1 - selector: - matchLabels: - app: postgres - role: primary - template: - metadata: - labels: - app: postgres - role: primary - region: africa-north - annotations: - prometheus.io/scrape: "true" - prometheus.io/port: "9187" - spec: - containers: - - name: postgres - image: postgres:16-alpine - ports: - - containerPort: 5432 - name: postgres - envFrom: - - configMapRef: - name: postgres-config - - secretRef: - name: postgres-secrets - resources: - requests: - memory: "4Gi" - cpu: "2000m" - limits: - memory: "8Gi" - cpu: "4000m" - volumeMounts: - - name: postgres-data - mountPath: /var/lib/postgresql/data - - name: postgres-config-volume - mountPath: /etc/postgresql/conf.d - - name: ssl-certs - mountPath: /etc/ssl/certs - readOnly: true - - name: ssl-keys - mountPath: /etc/ssl/private - readOnly: true - livenessProbe: - exec: - command: - - pg_isready - - -U - - yazcare - initialDelaySeconds: 30 - periodSeconds: 10 - readinessProbe: - exec: - command: - - pg_isready - - -U - - yazcare - initialDelaySeconds: 5 - periodSeconds: 5 - - name: postgres-exporter - image: prometheuscommunity/postgres-exporter:v0.15.0 - ports: - - containerPort: 9187 - name: metrics - env: - - name: DATA_SOURCE_NAME - valueFrom: - secretKeyRef: - name: postgres-secrets - key: EXPORTER_DSN - resources: - requests: - memory: "64Mi" - cpu: "50m" - limits: - memory: "128Mi" - cpu: "100m" - volumes: - - name: postgres-config-volume - configMap: - name: postgres-config - - name: ssl-certs - secret: - secretName: postgres-ssl-certs - - name: ssl-keys - secret: - secretName: postgres-ssl-keys - volumeClaimTemplates: - - metadata: - name: postgres-data - spec: - accessModes: ["ReadWriteOnce"] - storageClassName: fast-ssd - resources: - requests: - storage: 500Gi - ---- -# PostgreSQL Read Replica StatefulSet -apiVersion: apps/v1 -kind: StatefulSet -metadata: - name: postgres-replica - namespace: yaz-care - labels: - app: postgres - role: replica - region: africa-north -spec: - serviceName: postgres-replica - replicas: 2 - selector: - matchLabels: - app: postgres - role: replica - template: - metadata: - labels: - app: postgres - role: replica - region: africa-north - annotations: - prometheus.io/scrape: "true" - prometheus.io/port: "9187" - spec: - containers: - - name: postgres - image: postgres:16-alpine - ports: - - containerPort: 5432 - name: postgres - env: - - name: PGDATA - value: /var/lib/postgresql/data/pgdata - - name: POSTGRES_PRIMARY_HOST - value: postgres-primary.yaz-care.svc.cluster.local - envFrom: - - secretRef: - name: postgres-secrets - command: - - bash - - -c - - | - # Wait for primary to be ready - until pg_isready -h postgres-primary -U yazcare; do - echo "Waiting for primary..." - sleep 2 - done - - # Initialize replica from primary - if [ ! -s "$PGDATA/PG_VERSION" ]; then - pg_basebackup -h postgres-primary -U replication -D $PGDATA -Fp -Xs -P -R - fi - - # Start replica - exec postgres - resources: - requests: - memory: "2Gi" - cpu: "1000m" - limits: - memory: "4Gi" - cpu: "2000m" - volumeMounts: - - name: postgres-data - mountPath: /var/lib/postgresql/data - - name: ssl-certs - mountPath: /etc/ssl/certs - readOnly: true - livenessProbe: - exec: - command: - - pg_isready - - -U - - yazcare - initialDelaySeconds: 30 - periodSeconds: 10 - readinessProbe: - exec: - command: - - pg_isready - - -U - - yazcare - initialDelaySeconds: 5 - periodSeconds: 5 - - name: postgres-exporter - image: prometheuscommunity/postgres-exporter:v0.15.0 - ports: - - containerPort: 9187 - name: metrics - env: - - name: DATA_SOURCE_NAME - valueFrom: - secretKeyRef: - name: postgres-secrets - key: EXPORTER_DSN - resources: - requests: - memory: "64Mi" - cpu: "50m" - limits: - memory: "128Mi" - cpu: "100m" - volumes: - - name: ssl-certs - secret: - secretName: postgres-ssl-certs - volumeClaimTemplates: - - metadata: - name: postgres-data - spec: - accessModes: ["ReadWriteOnce"] - storageClassName: fast-ssd - resources: - requests: - storage: 500Gi - ---- -# Primary PostgreSQL Service -apiVersion: v1 -kind: Service -metadata: - name: postgres-primary - namespace: yaz-care - labels: - app: postgres - role: primary -spec: - type: ClusterIP - ports: - - port: 5432 - targetPort: 5432 - name: postgres - - port: 9187 - targetPort: 9187 - name: metrics - selector: - app: postgres - role: primary - ---- -# Replica PostgreSQL Service (for read queries) -apiVersion: v1 -kind: Service -metadata: - name: postgres-replica - namespace: yaz-care - labels: - app: postgres - role: replica -spec: - type: ClusterIP - ports: - - port: 5432 - targetPort: 5432 - name: postgres - - port: 9187 - targetPort: 9187 - name: metrics - selector: - app: postgres - role: replica - ---- -# PgBouncer Connection Pooler -apiVersion: apps/v1 -kind: Deployment -metadata: - name: pgbouncer - namespace: yaz-care - labels: - app: pgbouncer - region: africa-north -spec: - replicas: 2 - selector: - matchLabels: - app: pgbouncer - template: - metadata: - labels: - app: pgbouncer - region: africa-north - spec: - containers: - - name: pgbouncer - image: edoburu/pgbouncer:1.21.0 - ports: - - containerPort: 5432 - name: pgbouncer - env: - - name: DATABASE_URL - valueFrom: - secretKeyRef: - name: postgres-secrets - key: DATABASE_URL - - name: POOL_MODE - value: "transaction" - - name: MAX_CLIENT_CONN - value: "1000" - - name: DEFAULT_POOL_SIZE - value: "50" - - name: MIN_POOL_SIZE - value: "10" - - name: RESERVE_POOL_SIZE - value: "10" - - name: RESERVE_POOL_TIMEOUT - value: "5" - - name: SERVER_LIFETIME - value: "3600" - - name: SERVER_IDLE_TIMEOUT - value: "600" - resources: - requests: - memory: "128Mi" - cpu: "100m" - limits: - memory: "256Mi" - cpu: "500m" - livenessProbe: - tcpSocket: - port: 5432 - initialDelaySeconds: 10 - periodSeconds: 10 - readinessProbe: - tcpSocket: - port: 5432 - initialDelaySeconds: 5 - periodSeconds: 5 - ---- -# PgBouncer Service -apiVersion: v1 -kind: Service -metadata: - name: pgbouncer - namespace: yaz-care -spec: - type: ClusterIP - ports: - - port: 5432 - targetPort: 5432 - selector: - app: pgbouncer diff --git a/infra/kubernetes/regions/africa-north/redis.yaml b/infra/kubernetes/regions/africa-north/redis.yaml deleted file mode 100644 index 962be3cf4a93f75d001f022435115d337713ba13..0000000000000000000000000000000000000000 --- a/infra/kubernetes/regions/africa-north/redis.yaml +++ /dev/null @@ -1,316 +0,0 @@ -# YAZ Care Platform - Morocco Redis Cluster Configuration -# High-availability Redis cluster with Sentinel for failover - -apiVersion: v1 -kind: ConfigMap -metadata: - name: redis-config - namespace: yaz-care - labels: - region: africa-north -data: - redis.conf: | - # Network - bind 0.0.0.0 - port 6379 - tcp-backlog 511 - timeout 0 - tcp-keepalive 300 - - # Memory Management - maxmemory 2gb - maxmemory-policy allkeys-lru - maxmemory-samples 5 - - # Persistence (AOF for durability) - appendonly yes - appendfsync everysec - auto-aof-rewrite-percentage 100 - auto-aof-rewrite-min-size 64mb - - # RDB Snapshots - save 900 1 - save 300 10 - save 60 10000 - stop-writes-on-bgsave-error yes - rdbcompression yes - - # Replication - replica-read-only yes - repl-diskless-sync yes - repl-diskless-sync-delay 5 - - # Security - protected-mode yes - requirepass ${REDIS_PASSWORD} - masterauth ${REDIS_PASSWORD} - - # Performance - activerehashing yes - hz 10 - dynamic-hz yes - - # Cluster Mode - cluster-enabled yes - cluster-config-file nodes.conf - cluster-node-timeout 5000 - cluster-replica-validity-factor 10 - cluster-migration-barrier 1 - cluster-require-full-coverage yes - ---- -# Redis Cluster StatefulSet -apiVersion: apps/v1 -kind: StatefulSet -metadata: - name: redis-cluster - namespace: yaz-care - labels: - app: redis - role: cluster - region: africa-north -spec: - serviceName: redis-cluster - replicas: 6 # 3 masters + 3 replicas - selector: - matchLabels: - app: redis - role: cluster - template: - metadata: - labels: - app: redis - role: cluster - region: africa-north - annotations: - prometheus.io/scrape: "true" - prometheus.io/port: "9121" - spec: - affinity: - podAntiAffinity: - preferredDuringSchedulingIgnoredDuringExecution: - - weight: 100 - podAffinityTerm: - labelSelector: - matchExpressions: - - key: app - operator: In - values: - - redis - topologyKey: kubernetes.io/hostname - containers: - - name: redis - image: redis:7-alpine - ports: - - containerPort: 6379 - name: redis - - containerPort: 16379 - name: cluster-bus - command: - - redis-server - - /etc/redis/redis.conf - env: - - name: REDIS_PASSWORD - valueFrom: - secretKeyRef: - name: redis-secrets - key: REDIS_PASSWORD - - name: POD_IP - valueFrom: - fieldRef: - fieldPath: status.podIP - resources: - requests: - memory: "1Gi" - cpu: "500m" - limits: - memory: "2Gi" - cpu: "1000m" - volumeMounts: - - name: redis-data - mountPath: /data - - name: redis-config - mountPath: /etc/redis - livenessProbe: - exec: - command: - - redis-cli - - -a - - $(REDIS_PASSWORD) - - ping - initialDelaySeconds: 30 - periodSeconds: 10 - readinessProbe: - exec: - command: - - redis-cli - - -a - - $(REDIS_PASSWORD) - - ping - initialDelaySeconds: 5 - periodSeconds: 5 - - name: redis-exporter - image: oliver006/redis_exporter:v1.55.0 - ports: - - containerPort: 9121 - name: metrics - env: - - name: REDIS_PASSWORD - valueFrom: - secretKeyRef: - name: redis-secrets - key: REDIS_PASSWORD - - name: REDIS_ADDR - value: "localhost:6379" - resources: - requests: - memory: "32Mi" - cpu: "25m" - limits: - memory: "64Mi" - cpu: "100m" - volumes: - - name: redis-config - configMap: - name: redis-config - volumeClaimTemplates: - - metadata: - name: redis-data - spec: - accessModes: ["ReadWriteOnce"] - storageClassName: fast-ssd - resources: - requests: - storage: 20Gi - ---- -# Redis Cluster Service -apiVersion: v1 -kind: Service -metadata: - name: redis-cluster - namespace: yaz-care - labels: - app: redis - role: cluster -spec: - type: ClusterIP - clusterIP: None - ports: - - port: 6379 - targetPort: 6379 - name: redis - - port: 16379 - targetPort: 16379 - name: cluster-bus - - port: 9121 - targetPort: 9121 - name: metrics - selector: - app: redis - role: cluster - ---- -# Redis Cluster Initialization Job -apiVersion: batch/v1 -kind: Job -metadata: - name: redis-cluster-init - namespace: yaz-care - labels: - app: redis - role: init -spec: - template: - spec: - containers: - - name: redis-init - image: redis:7-alpine - command: - - /bin/sh - - -c - - | - echo "Waiting for Redis pods to be ready..." - sleep 30 - - # Get Redis pod IPs - REDIS_NODES="" - for i in $(seq 0 5); do - POD_IP=$(getent hosts redis-cluster-$i.redis-cluster.yaz-care.svc.cluster.local | awk '{ print $1 }') - REDIS_NODES="$REDIS_NODES $POD_IP:6379" - done - - echo "Creating cluster with nodes: $REDIS_NODES" - redis-cli -a ${REDIS_PASSWORD} --cluster create $REDIS_NODES --cluster-replicas 1 --cluster-yes - - echo "Cluster created successfully" - env: - - name: REDIS_PASSWORD - valueFrom: - secretKeyRef: - name: redis-secrets - key: REDIS_PASSWORD - restartPolicy: OnFailure - backoffLimit: 3 - ---- -# Redis Sentinel for High Availability (Optional - for non-cluster mode) -apiVersion: apps/v1 -kind: StatefulSet -metadata: - name: redis-sentinel - namespace: yaz-care - labels: - app: redis-sentinel - region: africa-north -spec: - serviceName: redis-sentinel - replicas: 3 - selector: - matchLabels: - app: redis-sentinel - template: - metadata: - labels: - app: redis-sentinel - region: africa-north - spec: - containers: - - name: sentinel - image: redis:7-alpine - ports: - - containerPort: 26379 - name: sentinel - command: - - redis-sentinel - - /etc/redis/sentinel.conf - volumeMounts: - - name: sentinel-config - mountPath: /etc/redis - resources: - requests: - memory: "128Mi" - cpu: "100m" - limits: - memory: "256Mi" - cpu: "200m" - volumes: - - name: sentinel-config - configMap: - name: redis-sentinel-config - ---- -# Redis Sentinel Config -apiVersion: v1 -kind: ConfigMap -metadata: - name: redis-sentinel-config - namespace: yaz-care -data: - sentinel.conf: | - port 26379 - sentinel monitor mymaster redis-cluster-0.redis-cluster.yaz-care.svc.cluster.local 6379 2 - sentinel auth-pass mymaster ${REDIS_PASSWORD} - sentinel down-after-milliseconds mymaster 5000 - sentinel failover-timeout mymaster 60000 - sentinel parallel-syncs mymaster 1 diff --git a/infra/kubernetes/regions/africa-north/secrets.yaml b/infra/kubernetes/regions/africa-north/secrets.yaml deleted file mode 100644 index f16867147be746dd2c4382c3553acc80e6c155d1..0000000000000000000000000000000000000000 --- a/infra/kubernetes/regions/africa-north/secrets.yaml +++ /dev/null @@ -1,180 +0,0 @@ -# YAZ Care Platform - Morocco Secrets Configuration -# IMPORTANT: These are templates. Actual secrets should be stored in a secrets manager -# and injected at deployment time using External Secrets Operator or similar - -apiVersion: v1 -kind: Secret -metadata: - name: yaz-secrets - namespace: yaz-care - labels: - app: yaz-care - region: africa-north -type: Opaque -stringData: - # Application Secrets (REPLACE BEFORE DEPLOYMENT) - SECRET_KEY: "GENERATE_32_CHAR_SECRET_KEY_HERE" - JWT_SECRET_KEY: "GENERATE_32_CHAR_JWT_SECRET_HERE" - MASTER_ENCRYPTION_KEY: "GENERATE_32_BYTE_ENCRYPTION_KEY" - - # Database Credentials (REPLACE) - DATABASE_URL: "postgresql://yazcare:SECURE_PASSWORD@pgbouncer.yaz-care.svc.cluster.local:5432/yazcare_prod" - POSTGRES_PASSWORD: "GENERATE_SECURE_DB_PASSWORD" - - # Redis Credentials (REPLACE) - REDIS_PASSWORD: "GENERATE_SECURE_REDIS_PASSWORD" - REDIS_URL: "redis://:REDIS_PASSWORD@redis-cluster.yaz-care.svc.cluster.local:6379/0" - ---- -apiVersion: v1 -kind: Secret -metadata: - name: postgres-secrets - namespace: yaz-care - labels: - app: postgres - region: africa-north -type: Opaque -stringData: - POSTGRES_PASSWORD: "GENERATE_SECURE_DB_PASSWORD" - REPLICATION_PASSWORD: "GENERATE_SECURE_REPLICATION_PASSWORD" - DATABASE_URL: "postgresql://yazcare:SECURE_PASSWORD@postgres-primary.yaz-care.svc.cluster.local:5432/yazcare_prod" - EXPORTER_DSN: "postgresql://postgres_exporter:EXPORTER_PASSWORD@localhost:5432/postgres?sslmode=disable" - ---- -apiVersion: v1 -kind: Secret -metadata: - name: redis-secrets - namespace: yaz-care - labels: - app: redis - region: africa-north -type: Opaque -stringData: - REDIS_PASSWORD: "GENERATE_SECURE_REDIS_PASSWORD" - ---- -# External Secrets Operator Configuration (Recommended for Production) -# This allows secrets to be synced from AWS Secrets Manager, HashiCorp Vault, etc. -apiVersion: external-secrets.io/v1beta1 -kind: SecretStore -metadata: - name: aws-secrets-store - namespace: yaz-care -spec: - provider: - aws: - service: SecretsManager - region: eu-west-3 # Paris region (closest AWS region to Morocco) - auth: - jwt: - serviceAccountRef: - name: external-secrets-sa - ---- -apiVersion: external-secrets.io/v1beta1 -kind: ExternalSecret -metadata: - name: yaz-external-secrets - namespace: yaz-care -spec: - refreshInterval: 1h - secretStoreRef: - name: aws-secrets-store - kind: SecretStore - target: - name: yaz-secrets - creationPolicy: Owner - data: - - secretKey: SECRET_KEY - remoteRef: - key: yaz-care/production/app-secrets - property: SECRET_KEY - - secretKey: JWT_SECRET_KEY - remoteRef: - key: yaz-care/production/app-secrets - property: JWT_SECRET_KEY - - secretKey: MASTER_ENCRYPTION_KEY - remoteRef: - key: yaz-care/production/app-secrets - property: MASTER_ENCRYPTION_KEY - - secretKey: DATABASE_URL - remoteRef: - key: yaz-care/production/database - property: DATABASE_URL - - secretKey: POSTGRES_PASSWORD - remoteRef: - key: yaz-care/production/database - property: POSTGRES_PASSWORD - - secretKey: REDIS_PASSWORD - remoteRef: - key: yaz-care/production/redis - property: REDIS_PASSWORD - ---- -# TLS Certificate Secret (Let's Encrypt via cert-manager) -apiVersion: cert-manager.io/v1 -kind: Certificate -metadata: - name: yaz-tls-morocco - namespace: yaz-care -spec: - secretName: yaz-tls-morocco - issuerRef: - name: letsencrypt-prod - kind: ClusterIssuer - dnsNames: - - yazcare.ma - - app.yazcare.ma - - api.yazcare.ma - - "*.yazcare.ma" - privateKey: - algorithm: ECDSA - size: 256 - ---- -# Let's Encrypt Cluster Issuer -apiVersion: cert-manager.io/v1 -kind: ClusterIssuer -metadata: - name: letsencrypt-prod -spec: - acme: - server: https://acme-v02.api.letsencrypt.org/directory - email: ssl-admin@yazcare.ma - privateKeySecretRef: - name: letsencrypt-prod-account-key - solvers: - - http01: - ingress: - class: nginx - - dns01: - cloudflare: - email: dns-admin@yazcare.ma - apiTokenSecretRef: - name: cloudflare-api-token - key: api-token - ---- -# PostgreSQL SSL Certificates -apiVersion: v1 -kind: Secret -metadata: - name: postgres-ssl-certs - namespace: yaz-care -type: kubernetes.io/tls -data: - # These should be generated and replaced before deployment - tls.crt: "BASE64_ENCODED_CERTIFICATE" - tls.key: "BASE64_ENCODED_PRIVATE_KEY" - ---- -# Service Account for External Secrets -apiVersion: v1 -kind: ServiceAccount -metadata: - name: external-secrets-sa - namespace: yaz-care - annotations: - eks.amazonaws.com/role-arn: arn:aws:iam::ACCOUNT_ID:role/yaz-care-external-secrets diff --git a/infra/kubernetes/regions/apac/deployment-patch.yaml b/infra/kubernetes/regions/apac/deployment-patch.yaml deleted file mode 100644 index b5cb74c881e99d3e6904afc63cb516e3799ccafc..0000000000000000000000000000000000000000 --- a/infra/kubernetes/regions/apac/deployment-patch.yaml +++ /dev/null @@ -1,46 +0,0 @@ ---- -# Deployment patch for APAC region - -apiVersion: apps/v1 -kind: Deployment -metadata: - name: yaz-care-api -spec: - replicas: 3 # APAC primary region capacity - template: - spec: - affinity: - nodeAffinity: - requiredDuringSchedulingIgnoredDuringExecution: - nodeSelectorTerms: - - matchExpressions: - - key: topology.kubernetes.io/region - operator: In - values: - - asia-southeast1 - containers: - - name: api - env: - - name: REGION - value: "apac" - - name: COMPLIANCE_MODE - value: "PDPA" - - name: DATA_RESIDENCY - value: "APAC" - - name: PDPA_CONSENT_REQUIRED - value: "true" - - name: CROSS_BORDER_TRANSFER_CONSENT - value: "required" - - name: DATA_BREACH_NOTIFICATION - value: "enabled" - - name: BACKUP_REGION - value: "asia-east" - - name: FAILOVER_ENABLED - value: "true" - resources: - requests: - memory: "1Gi" - cpu: "500m" - limits: - memory: "2Gi" - cpu: "1000m" diff --git a/infra/kubernetes/regions/apac/kustomization.yaml b/infra/kubernetes/regions/apac/kustomization.yaml deleted file mode 100644 index 4cc524ba901de645a2f3b32f94053549bd95e3ca..0000000000000000000000000000000000000000 --- a/infra/kubernetes/regions/apac/kustomization.yaml +++ /dev/null @@ -1,53 +0,0 @@ ---- -# Kustomization for APAC region -# Primary Asia-Pacific deployment with PDPA compliance - -apiVersion: kustomize.config.k8s.io/v1beta1 -kind: Kustomization - -namespace: yaz-care-apac - -resources: - - ../../base - -patchesStrategicMerge: - - deployment-patch.yaml - - ingress-patch.yaml - - configmap-patch.yaml - -configMapGenerator: - - name: regional-config - literals: - - REGION=apac - - REGION_NAME="Asia Pacific" - - COMPLIANCE_FRAMEWORK=PDPA - - DATA_RESIDENCY=APAC - - TIMEZONE=Asia/Singapore - - BACKUP_REGION=asia-east - - DR_ENDPOINT=https://dr.asia-east.yaz.care - - CLOUD_PROVIDER=gcp - - GCP_REGION=asia-southeast1 - - PDPA_ENABLED=true - - DATA_PROTECTION_OFFICER=dpo-apac@yaz.care - -commonLabels: - region: apac - compliance: pdpa - geo: asia-pacific - tier: production - -replicas: - - name: yaz-care-api - count: 3 # APAC primary region - -images: - - name: ghcr.io/elanass/yaz - newTag: "3.3.0" - -secretGenerator: - - name: regional-secrets - literals: - - DB_HOST=yaz-postgres-apac.gcp.internal - - REDIS_HOST=yaz-redis-apac.gcp.internal - - GCS_BUCKET=yaz-care-apac-data - - BACKUP_BUCKET=yaz-care-asia-east-backup diff --git a/infra/kubernetes/regions/eu-west/deployment-patch.yaml b/infra/kubernetes/regions/eu-west/deployment-patch.yaml deleted file mode 100644 index d2c336220e4ff17022706f8ccb280f2dc59c6293..0000000000000000000000000000000000000000 --- a/infra/kubernetes/regions/eu-west/deployment-patch.yaml +++ /dev/null @@ -1,56 +0,0 @@ ---- -# Deployment patch for EU-WEST region - -apiVersion: apps/v1 -kind: Deployment -metadata: - name: yaz-care-api -spec: - replicas: 4 # EU primary region capacity - template: - metadata: - annotations: - gdpr.compliance/enabled: "true" - gdpr.compliance/dpo: "dpo@yaz.care" - spec: - affinity: - nodeAffinity: - requiredDuringSchedulingIgnoredDuringExecution: - nodeSelectorTerms: - - matchExpressions: - - key: topology.kubernetes.io/region - operator: In - values: - - eu-central-1 - containers: - - name: api - env: - - name: REGION - value: "eu-west" - - name: COMPLIANCE_MODE - value: "GDPR" - - name: DATA_RESIDENCY - value: "EU" - - name: GDPR_RIGHT_TO_ERASURE - value: "true" - - name: GDPR_DATA_PORTABILITY - value: "true" - - name: GDPR_CONSENT_MANAGEMENT - value: "true" - - name: GDPR_BREACH_NOTIFICATION_HOURS - value: "72" - - name: DATA_RETENTION_POLICY - value: "gdpr-compliant" - - name: CROSS_BORDER_TRANSFER_CONSENT - value: "required" - - name: BACKUP_REGION - value: "eu-central" - - name: FAILOVER_ENABLED - value: "true" - resources: - requests: - memory: "1Gi" - cpu: "500m" - limits: - memory: "2Gi" - cpu: "1000m" diff --git a/infra/kubernetes/regions/eu-west/kustomization.yaml b/infra/kubernetes/regions/eu-west/kustomization.yaml deleted file mode 100644 index 3cadbd9b3332ab2ddce514b39d4a6cb513b8d2fe..0000000000000000000000000000000000000000 --- a/infra/kubernetes/regions/eu-west/kustomization.yaml +++ /dev/null @@ -1,57 +0,0 @@ ---- -# Kustomization for EU-WEST region -# Primary EU deployment with GDPR compliance - -apiVersion: kustomize.config.k8s.io/v1beta1 -kind: Kustomization - -namespace: yaz-care-eu-west - -resources: - - ../../base - -patchesStrategicMerge: - - deployment-patch.yaml - - ingress-patch.yaml - - configmap-patch.yaml - -configMapGenerator: - - name: regional-config - literals: - - REGION=eu-west - - REGION_NAME="Europe West" - - COMPLIANCE_FRAMEWORK=GDPR - - DATA_RESIDENCY=EU - - TIMEZONE=Europe/Berlin - - BACKUP_REGION=eu-central - - DR_ENDPOINT=https://dr.eu-central.yaz.care - - CLOUD_PROVIDER=aws - - AWS_REGION=eu-central-1 - - GDPR_ENABLED=true - - RIGHT_TO_ERASURE_ENABLED=true - - DATA_PORTABILITY_ENABLED=true - - CONSENT_MANAGEMENT_ENABLED=true - -commonLabels: - region: eu-west - compliance: gdpr - geo: europe - tier: production - -replicas: - - name: yaz-care-api - count: 4 # EU primary region - -images: - - name: ghcr.io/elanass/yaz - newTag: "3.3.0" - -secretGenerator: - - name: regional-secrets - literals: - - DB_HOST=yaz-postgres-eu-west.c1234567.eu-central-1.rds.amazonaws.com - - REDIS_HOST=yaz-redis-eu-west.abc123.euc1.cache.amazonaws.com - - S3_BUCKET=yaz-care-eu-west-data - - BACKUP_BUCKET=yaz-care-eu-central-backup - - DPO_EMAIL=dpo@yaz.care - - GDPR_CONTACT=gdpr@yaz.care diff --git a/infra/kubernetes/regions/us-east/deployment-patch.yaml b/infra/kubernetes/regions/us-east/deployment-patch.yaml deleted file mode 100644 index ba5c1e26a348f79530d3deb57d2a83d1159cb7cf..0000000000000000000000000000000000000000 --- a/infra/kubernetes/regions/us-east/deployment-patch.yaml +++ /dev/null @@ -1,52 +0,0 @@ ---- -# Deployment patch for US-EAST region - -apiVersion: apps/v1 -kind: Deployment -metadata: - name: yaz-care-api -spec: - replicas: 5 # Higher capacity for primary US region - template: - metadata: - annotations: - prometheus.io/scrape: "true" - prometheus.io/port: "8001" - spec: - affinity: - nodeAffinity: - requiredDuringSchedulingIgnoredDuringExecution: - nodeSelectorTerms: - - matchExpressions: - - key: topology.kubernetes.io/region - operator: In - values: - - us-east-1 - containers: - - name: api - env: - - name: REGION - value: "us-east" - - name: COMPLIANCE_MODE - value: "HIPAA" - - name: DATA_RESIDENCY - value: "US" - - name: ENABLE_AUDIT_LOGGING - value: "true" - - name: AUDIT_RETENTION_DAYS - value: "2555" # 7 years for HIPAA - - name: ENCRYPTION_AT_REST - value: "true" - - name: TLS_VERSION_MIN - value: "1.2" - - name: BACKUP_REGION - value: "us-west" - - name: FAILOVER_ENABLED - value: "true" - resources: - requests: - memory: "1Gi" - cpu: "500m" - limits: - memory: "2Gi" - cpu: "1000m" diff --git a/infra/kubernetes/regions/us-east/kustomization.yaml b/infra/kubernetes/regions/us-east/kustomization.yaml deleted file mode 100644 index cc3cca48e754be40fc03e39256da50b97f096519..0000000000000000000000000000000000000000 --- a/infra/kubernetes/regions/us-east/kustomization.yaml +++ /dev/null @@ -1,58 +0,0 @@ ---- -# Kustomization for US-EAST region -# Primary US deployment with HIPAA compliance - -apiVersion: kustomize.config.k8s.io/v1beta1 -kind: Kustomization - -namespace: yaz-care-us-east - -# Base resources from parent directory -resources: - - ../../base - -# Regional patches -patchesStrategicMerge: - - deployment-patch.yaml - - ingress-patch.yaml - - configmap-patch.yaml - -# Regional configuration -configMapGenerator: - - name: regional-config - literals: - - REGION=us-east - - REGION_NAME="United States East" - - COMPLIANCE_FRAMEWORK=HIPAA - - DATA_RESIDENCY=US - - TIMEZONE=America/New_York - - BACKUP_REGION=us-west - - DR_ENDPOINT=https://dr.us-west.yaz.care - - CLOUD_PROVIDER=aws - - AWS_REGION=us-east-1 - -# Regional labels -commonLabels: - region: us-east - compliance: hipaa - geo: north-america - tier: production - -# Resource limits (region-specific scaling) -replicas: - - name: yaz-care-api - count: 5 # Higher for primary US region - -# Regional images (can use region-specific registries) -images: - - name: ghcr.io/elanass/yaz - newTag: "3.3.0" - -# Regional secrets -secretGenerator: - - name: regional-secrets - literals: - - DB_HOST=yaz-postgres-us-east.c1234567.us-east-1.rds.amazonaws.com - - REDIS_HOST=yaz-redis-us-east.abc123.use1.cache.amazonaws.com - - S3_BUCKET=yaz-care-us-east-data - - BACKUP_BUCKET=yaz-care-us-west-backup diff --git a/infra/kubernetes/secrets.yaml b/infra/kubernetes/secrets.yaml deleted file mode 100644 index e4dcb01ab50151e8361f44ef69f352ba19be89b3..0000000000000000000000000000000000000000 --- a/infra/kubernetes/secrets.yaml +++ /dev/null @@ -1,38 +0,0 @@ ---- -apiVersion: v1 -kind: Secret -metadata: - name: yaz-care-secrets - namespace: yaz-care -type: Opaque -stringData: - # Database credentials (base64 encode in production) - DATABASE_URL: "postgresql://yaz_care:CHANGEME@postgres:5432/yaz_care_prod" - POSTGRES_USER: "yaz_care" - POSTGRES_PASSWORD: "CHANGEME_SECURE_PASSWORD" - - # JWT secrets - JWT_SECRET: "CHANGEME_JWT_SECRET_KEY_MIN_32_CHARS" - JWT_ALGORITHM: "HS256" - - # Redis - REDIS_URL: "redis://:CHANGEME@redis:6379/0" - REDIS_PASSWORD: "CHANGEME_REDIS_PASSWORD" - - # S3 Backup credentials - AWS_ACCESS_KEY_ID: "CHANGEME_ACCESS_KEY" - AWS_SECRET_ACCESS_KEY: "CHANGEME_SECRET_KEY" - S3_BUCKET: "yaz-care-backups" - - # Encryption keys - ENCRYPTION_KEY: "CHANGEME_FERNET_KEY" - - # External APIs - OPENAI_API_KEY: "CHANGEME_IF_USING_AI" - ---- -# Note: In production, create secrets using kubectl: -# kubectl create secret generic yaz-care-secrets \ -# --from-literal=DATABASE_URL='postgresql://...' \ -# --from-literal=JWT_SECRET='...' \ -# --namespace=yaz-care diff --git a/infra/kubernetes/service.yaml b/infra/kubernetes/service.yaml deleted file mode 100644 index a2767bf77e55da9156047d831085ca5ab0b3ac0c..0000000000000000000000000000000000000000 --- a/infra/kubernetes/service.yaml +++ /dev/null @@ -1,48 +0,0 @@ ---- -apiVersion: v1 -kind: Service -metadata: - name: yaz-care-api - namespace: yaz-care - labels: - app: yaz-care-api - annotations: - prometheus.io/scrape: "true" - prometheus.io/port: "8001" - prometheus.io/path: "/metrics" -spec: - type: ClusterIP - sessionAffinity: ClientIP - sessionAffinityConfig: - clientIP: - timeoutSeconds: 3600 - ports: - - name: http - port: 8000 - targetPort: 8000 - protocol: TCP - - name: metrics - port: 8001 - targetPort: 8001 - protocol: TCP - selector: - app: yaz-care-api - ---- -apiVersion: v1 -kind: Service -metadata: - name: yaz-care-api-headless - namespace: yaz-care - labels: - app: yaz-care-api -spec: - type: ClusterIP - clusterIP: None - ports: - - name: http - port: 8000 - targetPort: 8000 - protocol: TCP - selector: - app: yaz-care-api diff --git a/infra/load-testing/README.md b/infra/load-testing/README.md deleted file mode 100644 index 0dc54a5f3b1a0b6119407bf7a5acc09341ee233a..0000000000000000000000000000000000000000 --- a/infra/load-testing/README.md +++ /dev/null @@ -1,308 +0,0 @@ -# Load Testing Infrastructure - -## Overview - -This directory contains k6 load testing scripts for the YAZ Care Platform. The tests simulate production-like traffic patterns and validate performance under load. - -## Prerequisites - -```bash -# Install k6 (macOS) -brew install k6 - -# Install k6 (Linux) -sudo gpg -k -sudo gpg --no-default-keyring --keyring /usr/share/keyrings/k6-archive-keyring.gpg --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys C5AD17C747E3415A3642D57D77C6C491D6AC1D69 -echo "deb [signed-by=/usr/share/keyrings/k6-archive-keyring.gpg] https://dl.k6.io/deb stable main" | sudo tee /etc/apt/sources.list.d/k6.list -sudo apt-get update -sudo apt-get install k6 - -# Install k6 (Docker) -docker pull grafana/k6:latest -``` - -## Test Scripts - -### 1. `health-check.js` -Basic health check and warmup test -- **Purpose**: Validate API availability -- **Duration**: 30 seconds -- **VUs**: 10 -- **Endpoints**: `/health`, `/api/v1/docs` - -### 2. `api-smoke-test.js` -Smoke test for all major API endpoints -- **Purpose**: Validate core functionality under minimal load -- **Duration**: 1 minute -- **VUs**: 20 -- **Coverage**: Auth, Labo, Surgio, Clinica APIs - -### 3. `auth-load-test.js` -Authentication flow load testing -- **Scenarios**: - - Login (50% of traffic) - - Token refresh (30% of traffic) - - Registration (10% of traffic) - - Password reset (10% of traffic) -- **Target**: 100 requests/second -- **Duration**: 5 minutes - -### 4. `labo-workflow-load.js` -Laboratory workflow load testing -- **Scenarios**: - - Create lab order (30%) - - Submit specimen (20%) - - File results (15%) - - Verify results (10%) - - Query orders (25%) -- **Target**: 200 orders/minute -- **Duration**: 10 minutes - -### 5. `surgio-load-test.js` -Surgical operations load testing -- **Scenarios**: - - Schedule surgery (20%) - - Update surgical state (30%) - - Query OR availability (30%) - - Analytics dashboard (20%) -- **Target**: 150 requests/second -- **Duration**: 10 minutes - -### 6. `stress-test.js` -Stress test to find system limits -- **Purpose**: Identify breaking point -- **Ramp-up**: 0 β†’ 500 VUs over 5 minutes -- **Peak**: 500 VUs for 5 minutes -- **Ramp-down**: 500 β†’ 0 VUs over 2 minutes - -### 7. `endurance-test.js` -Endurance test for stability -- **Purpose**: Memory leaks, resource exhaustion -- **Duration**: 2 hours -- **VUs**: 100 (constant) -- **Pattern**: Realistic user journeys - -## Running Tests - -### Quick Start - -```bash -# Run health check -k6 run infra/load-testing/health-check.js - -# Run smoke test -k6 run infra/load-testing/api-smoke-test.js - -# Run with custom VUs and duration -k6 run --vus 50 --duration 5m infra/load-testing/auth-load-test.js - -# Run with environment variables -k6 run -e BASE_URL=https://api.yaz.care infra/load-testing/labo-workflow-load.js -``` - -### Advanced Usage - -```bash -# Run with custom thresholds -k6 run --summary-trend-stats="avg,min,med,max,p(95),p(99)" infra/load-testing/stress-test.js - -# Run with output to InfluxDB -k6 run --out influxdb=http://localhost:8086/k6 infra/load-testing/endurance-test.js - -# Run with JSON output -k6 run --out json=results.json infra/load-testing/surgio-load-test.js - -# Run with Grafana Cloud k6 -k6 cloud run infra/load-testing/stress-test.js -``` - -### Docker Execution - -```bash -# Run in Docker -docker run --rm -i -v $PWD:/workspace grafana/k6 run /workspace/infra/load-testing/health-check.js - -# Run with network access to local API -docker run --rm -i --network host -v $PWD:/workspace grafana/k6 run /workspace/infra/load-testing/api-smoke-test.js -``` - -## Performance Targets - -### Response Times (p95) -- **Health check**: < 10ms -- **Authentication**: < 100ms -- **Lab order creation**: < 200ms -- **Surgical scheduling**: < 300ms -- **Analytics queries**: < 500ms -- **Complex reports**: < 1000ms - -### Throughput -- **Health checks**: 1000+ req/s -- **Authentication**: 100+ req/s -- **Lab workflows**: 200+ orders/min -- **Surgical operations**: 150+ req/s -- **Overall platform**: 500+ req/s - -### Error Rates -- **HTTP 5xx errors**: < 0.1% -- **HTTP 4xx errors**: < 1% -- **Timeout errors**: < 0.5% - -### Resource Utilization -- **CPU**: < 70% at peak load -- **Memory**: < 80% of available RAM -- **Database connections**: < 80% of pool size -- **Redis connections**: < 90% of max clients - -## Thresholds & SLOs - -All k6 scripts include built-in thresholds aligned with our SLOs: - -```javascript -export const options = { - thresholds: { - 'http_req_duration': ['p(95)<500'], // 95% of requests under 500ms - 'http_req_failed': ['rate<0.01'], // Less than 1% failure rate - 'http_reqs': ['rate>100'], // At least 100 req/s - }, -}; -``` - -## CI/CD Integration - -### GitHub Actions - -```yaml -name: Load Tests -on: - schedule: - - cron: '0 2 * * *' # Daily at 2 AM - workflow_dispatch: - -jobs: - load-test: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - - name: Run k6 load tests - uses: grafana/k6-action@v0.3.0 - with: - filename: infra/load-testing/api-smoke-test.js - flags: --out json=results.json - - name: Upload results - uses: actions/upload-artifact@v3 - with: - name: k6-results - path: results.json -``` - -### Makefile Integration - -```bash -# Run smoke tests -make load-test-smoke - -# Run full load tests -make load-test-full - -# Run stress tests -make load-test-stress -``` - -## Monitoring & Alerting - -### Grafana Dashboard - -Import the k6 dashboard from `infra/grafana/dashboards/k6_load_tests.json`: -- Real-time VUs and request rate -- Response time percentiles (p50, p95, p99) -- Error rate and HTTP status codes -- Custom metrics and checks - -### Alert Rules - -Configure Prometheus alerts for load test failures: -- Response time SLO breach -- Error rate exceeds threshold -- Resource exhaustion during tests - -## Troubleshooting - -### Common Issues - -**1. Connection refused** -```bash -# Check if API is running -curl http://localhost:8000/health - -# Start the API -python3 main.py serve -``` - -**2. Authentication failures** -```bash -# Verify credentials in config -cat config/environments/test.yml - -# Check auth endpoint -curl -X POST http://localhost:8000/api/v1/auth/login \ - -H "Content-Type: application/json" \ - -d '{"username":"admin","password":"password"}' -``` - -**3. Database connection errors** -```bash -# Check database connectivity -python3 -c "from src.core.database import engine; print(engine.connect())" - -# Check connection pool status -python3 main.py health -``` - -**4. Rate limiting** -```bash -# Temporarily disable rate limiting for load tests -export RATE_LIMIT_ENABLED=false -python3 main.py serve -``` - -## Best Practices - -1. **Start Small**: Begin with smoke tests before running full load tests -2. **Ramp Up Gradually**: Use staged ramp-up patterns to avoid overwhelming the system -3. **Monitor Resources**: Watch CPU, memory, database connections during tests -4. **Test Realistic Scenarios**: Mix read/write operations in realistic proportions -5. **Isolate Tests**: Run load tests against dedicated test environments -6. **Document Baselines**: Record baseline metrics for regression detection -7. **Automate**: Integrate load tests into CI/CD pipelines -8. **Analyze Failures**: Investigate any threshold breaches or errors - -## Results Analysis - -### Key Metrics - -```bash -# Extract summary metrics from JSON output -jq '.metrics' results.json - -# Calculate percentiles -jq '.metrics.http_req_duration.values | {p50, p95, p99}' results.json - -# Get error rate -jq '.metrics.http_req_failed.values.rate' results.json -``` - -### Trend Analysis - -Compare results over time to detect regressions: -- Response time trends -- Throughput degradation -- Error rate increases -- Resource utilization changes - -## References - -- [k6 Documentation](https://k6.io/docs/) -- [k6 Cloud](https://k6.io/cloud/) -- [Performance Testing Guide](https://k6.io/docs/test-types/introduction/) -- [Grafana k6 Integration](https://grafana.com/docs/grafana-cloud/k6/) diff --git a/infra/load-testing/api-smoke-test.js b/infra/load-testing/api-smoke-test.js deleted file mode 100644 index 43ea5bd7f1162610e323965375e7fcb10cde8152..0000000000000000000000000000000000000000 --- a/infra/load-testing/api-smoke-test.js +++ /dev/null @@ -1,248 +0,0 @@ -/** - * YAZ Care Platform - API Smoke Test - * - * Purpose: Validate core API functionality under minimal load - * Duration: 2 minutes - * Virtual Users: 20 - * Coverage: Auth, Labo, Surgio, Clinica APIs - * - * Usage: - * k6 run infra/load-testing/api-smoke-test.js - * k6 run -e BASE_URL=https://api.yaz.care -e ADMIN_USERNAME=admin -e ADMIN_PASSWORD=password infra/load-testing/api-smoke-test.js - */ - -import http from 'k6/http'; -import { check, group, sleep } from 'k6'; -import { Counter, Rate, Trend } from 'k6/metrics'; - -// Custom metrics -const apiErrors = new Counter('api_errors'); -const authFailures = new Rate('auth_failures'); -const apiDuration = new Trend('api_duration'); - -// Test configuration -export const options = { - stages: [ - { duration: '30s', target: 20 }, // Ramp-up to 20 users - { duration: '1m', target: 20 }, // Stay at 20 users - { duration: '30s', target: 0 }, // Ramp-down to 0 users - ], - thresholds: { - 'http_req_duration': ['p(95)<500'], - 'http_req_failed': ['rate<0.01'], - 'api_errors': ['count<10'], - 'auth_failures': ['rate<0.05'], - }, - tags: { - test_type: 'smoke_test', - environment: __ENV.ENVIRONMENT || 'test', - }, -}; - -// Environment configuration -const BASE_URL = __ENV.BASE_URL || 'http://localhost:8000'; -const API_VERSION = 'v1'; -const ADMIN_USERNAME = __ENV.ADMIN_USERNAME || 'admin'; -const ADMIN_PASSWORD = __ENV.ADMIN_PASSWORD || 'admin123'; - -// Shared state -let authToken = null; - -export function setup() { - // Authenticate once to get token - const loginRes = http.post( - `${BASE_URL}/api/${API_VERSION}/auth/login`, - JSON.stringify({ - username: ADMIN_USERNAME, - password: ADMIN_PASSWORD, - }), - { - headers: { 'Content-Type': 'application/json' }, - } - ); - - if (loginRes.status === 200) { - const body = JSON.parse(loginRes.body); - return { - token: body.access_token || body.token, - }; - } - - console.error('Setup failed: Unable to authenticate'); - return { token: null }; -} - -export default function (data) { - const token = data?.token; - const headers = { - 'Content-Type': 'application/json', - ...(token && { 'Authorization': `Bearer ${token}` }), - }; - - // Test 1: Authentication API - group('Authentication API', function () { - const loginRes = http.post( - `${BASE_URL}/api/${API_VERSION}/auth/login`, - JSON.stringify({ - username: ADMIN_USERNAME, - password: ADMIN_PASSWORD, - }), - { headers: { 'Content-Type': 'application/json' } } - ); - - const loginCheck = check(loginRes, { - 'login status is 200': (r) => r.status === 200, - 'login returns token': (r) => { - try { - const body = JSON.parse(r.body); - return body.access_token || body.token; - } catch (e) { - return false; - } - }, - }); - - authFailures.add(!loginCheck); - apiDuration.add(loginRes.timings.duration); - - if (loginRes.status !== 200) { - apiErrors.add(1); - } - }); - - sleep(1); - - // Test 2: Laboratory API - group('Laboratory API', function () { - // List lab tests - const testsRes = http.get( - `${BASE_URL}/api/${API_VERSION}/labo/tests`, - { headers } - ); - - check(testsRes, { - 'lab tests status is 200 or 401': (r) => [200, 401].includes(r.status), - 'lab tests returns JSON': (r) => { - if (r.status === 200) { - try { - JSON.parse(r.body); - return true; - } catch (e) { - return false; - } - } - return true; - }, - }); - - apiDuration.add(testsRes.timings.duration); - - // List lab orders - const ordersRes = http.get( - `${BASE_URL}/api/${API_VERSION}/labo/orders`, - { headers } - ); - - check(ordersRes, { - 'lab orders status is 200 or 401': (r) => [200, 401].includes(r.status), - }); - - apiDuration.add(ordersRes.timings.duration); - }); - - sleep(1); - - // Test 3: Surgical Management API - group('Surgical Management API', function () { - // Get OR availability - const orRes = http.get( - `${BASE_URL}/api/${API_VERSION}/surgio/or/availability`, - { headers } - ); - - check(orRes, { - 'OR availability status is 200 or 401': (r) => [200, 401].includes(r.status), - }); - - apiDuration.add(orRes.timings.duration); - - // List procedures - const proceduresRes = http.get( - `${BASE_URL}/api/${API_VERSION}/surgio/procedures`, - { headers } - ); - - check(proceduresRes, { - 'procedures status is 200 or 401': (r) => [200, 401].includes(r.status), - }); - - apiDuration.add(proceduresRes.timings.duration); - }); - - sleep(1); - - // Test 4: Clinical Data API - group('Clinical Data API', function () { - // List patients - const patientsRes = http.get( - `${BASE_URL}/api/${API_VERSION}/clinica/patients`, - { headers } - ); - - check(patientsRes, { - 'patients status is 200 or 401': (r) => [200, 401].includes(r.status), - }); - - apiDuration.add(patientsRes.timings.duration); - - // List encounters - const encountersRes = http.get( - `${BASE_URL}/api/${API_VERSION}/clinica/encounters`, - { headers } - ); - - check(encountersRes, { - 'encounters status is 200 or 401': (r) => [200, 401].includes(r.status), - }); - - apiDuration.add(encountersRes.timings.duration); - }); - - sleep(2); -} - -export function handleSummary(data) { - const passed = Object.values(data.metrics) - .filter(m => m.thresholds) - .every(m => Object.values(m.thresholds).every(t => t.ok)); - - const summary = { - test_name: 'API Smoke Test', - timestamp: new Date().toISOString(), - passed: passed, - metrics: { - total_requests: data.metrics.http_reqs?.values.count || 0, - requests_per_second: data.metrics.http_reqs?.values.rate || 0, - avg_response_time: data.metrics.http_req_duration?.values.avg || 0, - p95_response_time: data.metrics.http_req_duration?.values['p(95)'] || 0, - p99_response_time: data.metrics.http_req_duration?.values['p(99)'] || 0, - failure_rate: (data.metrics.http_req_failed?.values.rate || 0) * 100, - api_errors: data.metrics.api_errors?.values.count || 0, - auth_failure_rate: (data.metrics.auth_failures?.values.rate || 0) * 100, - }, - thresholds: Object.entries(data.metrics) - .filter(([_, m]) => m.thresholds) - .reduce((acc, [name, m]) => { - acc[name] = Object.entries(m.thresholds).reduce((tacc, [tname, t]) => { - tacc[tname] = t.ok; - return tacc; - }, {}); - return acc; - }, {}), - }; - - return { - 'stdout': JSON.stringify(summary, null, 2), - 'smoke-test-results.json': JSON.stringify(summary, null, 2), - }; -} diff --git a/infra/load-testing/dashboard/app.js b/infra/load-testing/dashboard/app.js deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/infra/load-testing/dashboard/package.json b/infra/load-testing/dashboard/package.json deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/infra/load-testing/endurance-test.js b/infra/load-testing/endurance-test.js deleted file mode 100644 index 0b2c4e2bfa81ced69e27854f47169e2512277b08..0000000000000000000000000000000000000000 --- a/infra/load-testing/endurance-test.js +++ /dev/null @@ -1,300 +0,0 @@ -/** - * YAZ Care Platform - Endurance Test (Soak Test) - * - * Purpose: Validate system stability over extended period - * Focus: Memory leaks, resource exhaustion, connection pool saturation - * Duration: 2 hours - * Virtual Users: 100 (constant) - * - * Usage: - * k6 run infra/load-testing/endurance-test.js - * k6 run -e DURATION=4h -e VUS=150 infra/load-testing/endurance-test.js - */ - -import http from 'k6/http'; -import { check, group, sleep } from 'k6'; -import { Counter, Rate, Trend, Gauge } from 'k6/metrics'; -import { randomString, randomIntBetween, randomItem } from 'https://jslib.k6.io/k6-utils/1.4.0/index.js'; - -// Custom metrics for endurance tracking -const memoryIssues = new Counter('memory_issues'); -const connectionErrors = new Counter('connection_errors'); -const degradationEvents = new Counter('degradation_events'); -const currentResponseTime = new Gauge('current_response_time'); -const baselineDeviation = new Trend('baseline_deviation'); - -// Test configuration -export const options = { - stages: [ - { duration: '5m', target: 100 }, // Ramp-up to 100 VUs - { duration: __ENV.DURATION || '2h', target: 100 }, // Maintain for 2 hours - { duration: '5m', target: 0 }, // Ramp-down - ], - thresholds: { - 'http_req_duration': [ - 'p(95)<800', // Response time should remain consistent - 'p(99)<1500', - ], - 'http_req_failed': ['rate<0.02'], // Less than 2% failure rate - 'connection_errors': ['count<50'], - 'degradation_events': ['count<20'], - }, - ext: { - loadimpact: { - projectID: 3545656, - name: 'YAZ Care Platform - Endurance Test', - }, - }, -}; - -// Configuration -const BASE_URL = __ENV.BASE_URL || 'http://localhost:8000'; -const API_VERSION = 'v1'; -const VUS = parseInt(__ENV.VUS || '100'); -const CHECK_INTERVAL_MS = 60000; // Check for degradation every minute - -// Baseline response time (set during first iteration) -let baselineResponseTime = 0; -let iterationCount = 0; - -let authToken = null; - -export function setup() { - console.log(`Starting endurance test with ${VUS} VUs for ${__ENV.DURATION || '2h'}`); - - const loginRes = http.post( - `${BASE_URL}/api/${API_VERSION}/auth/login`, - JSON.stringify({ - username: __ENV.ADMIN_USERNAME || 'admin', - password: __ENV.ADMIN_PASSWORD || 'admin123', - }), - { headers: { 'Content-Type': 'application/json' } } - ); - - if (loginRes.status === 200) { - const body = JSON.parse(loginRes.body); - return { token: body.access_token || body.token }; - } - - return { token: null }; -} - -export default function (data) { - iterationCount++; - - const token = data?.token; - const headers = { - 'Content-Type': 'application/json', - ...(token && { 'Authorization': `Bearer ${token}` }), - }; - - // Realistic user journey simulation - group('User Journey - Clinical Workflow', function () { - // 1. Check health - const healthRes = http.get(`${BASE_URL}/health`); - check(healthRes, { - 'health check OK': (r) => r.status === 200, - }); - - sleep(randomIntBetween(1, 3)); - - // 2. View patient list - const patientsRes = http.get( - `${BASE_URL}/api/${API_VERSION}/clinica/patients?limit=20`, - { headers } - ); - - const avgResponseTime = patientsRes.timings.duration; - currentResponseTime.add(avgResponseTime); - - // Set baseline after first few iterations - if (iterationCount === 10 && baselineResponseTime === 0) { - baselineResponseTime = avgResponseTime; - console.log(`Baseline response time set: ${baselineResponseTime}ms`); - } - - // Check for degradation (response time > 2x baseline) - if (baselineResponseTime > 0 && avgResponseTime > baselineResponseTime * 2) { - degradationEvents.add(1); - const deviation = ((avgResponseTime - baselineResponseTime) / baselineResponseTime) * 100; - baselineDeviation.add(deviation); - } - - check(patientsRes, { - 'patients loaded': (r) => [200, 401].includes(r.status), - 'response time acceptable': (r) => r.timings.duration < 1000, - }); - - if (patientsRes.status === 0 || patientsRes.error_code === 1050) { - connectionErrors.add(1); - } - - sleep(randomIntBetween(2, 5)); - - // 3. Create lab order - const orderPayload = { - patient_id: `patient_endurance_${randomString(8)}`, - patient_name: `Endurance Test Patient ${randomString(6)}`, - test_name: randomItem(['CBC', 'CMP', 'Lipid Panel', 'HbA1c', 'TSH']), - test_code: `END_${randomIntBetween(10000, 99999)}`, - priority: randomItem(['routine', 'urgent']), - ordering_physician: randomItem(['Dr. Smith', 'Dr. Johnson', 'Dr. Williams']), - specimen_type: randomItem(['blood', 'urine', 'serum']), - }; - - const orderRes = http.post( - `${BASE_URL}/api/${API_VERSION}/labo/orders`, - JSON.stringify(orderPayload), - { headers } - ); - - check(orderRes, { - 'lab order created or auth required': (r) => [200, 201, 401].includes(r.status), - }); - - sleep(randomIntBetween(3, 7)); - - // 4. Query lab orders - const ordersRes = http.get( - `${BASE_URL}/api/${API_VERSION}/labo/orders?limit=50`, - { headers } - ); - - check(ordersRes, { - 'orders retrieved': (r) => [200, 401].includes(r.status), - }); - - sleep(randomIntBetween(2, 4)); - - // 5. Check OR availability - const orRes = http.get( - `${BASE_URL}/api/${API_VERSION}/surgio/or/availability`, - { headers } - ); - - check(orRes, { - 'OR availability checked': (r) => [200, 401].includes(r.status), - }); - - sleep(randomIntBetween(2, 5)); - }); - - // Periodically run memory-intensive operations - if (iterationCount % 50 === 0) { - group('Heavy Analytics Query', function () { - const analyticsRes = http.get( - `${BASE_URL}/api/${API_VERSION}/analytics/dashboard?range=30d`, - { headers } - ); - - // Check for memory-related errors - if (analyticsRes.status === 503 || analyticsRes.status === 507) { - memoryIssues.add(1); - } - - check(analyticsRes, { - 'analytics loaded or auth required': (r) => [200, 401, 404].includes(r.status), - }); - }); - } - - // Random think time between iterations - sleep(randomIntBetween(5, 15)); -} - -export function handleSummary(data) { - const metrics = data.metrics; - - // Calculate key metrics - const totalRequests = metrics.http_reqs?.values.count || 0; - const throughput = metrics.http_reqs?.values.rate || 0; - const avgResponseTime = metrics.http_req_duration?.values.avg || 0; - const p95ResponseTime = metrics.http_req_duration?.values['p(95)'] || 0; - const p99ResponseTime = metrics.http_req_duration?.values['p(99)'] || 0; - const failureRate = (metrics.http_req_failed?.values.rate || 0) * 100; - - // Stability indicators - const connectionErrorCount = metrics.connection_errors?.values.count || 0; - const degradationEventCount = metrics.degradation_events?.values.count || 0; - const memoryIssueCount = metrics.memory_issues?.values.count || 0; - - // Calculate stability score (0-100) - let stabilityScore = 100; - stabilityScore -= Math.min(failureRate * 10, 30); // Max -30 for failures - stabilityScore -= Math.min(degradationEventCount * 2, 20); // Max -20 for degradation - stabilityScore -= Math.min(connectionErrorCount, 20); // Max -20 for connection errors - stabilityScore -= Math.min(memoryIssueCount * 5, 20); // Max -20 for memory issues - stabilityScore = Math.max(0, stabilityScore); - - // Determine if system passed endurance test - const passed = stabilityScore >= 80 && - failureRate < 2 && - degradationEventCount < 20 && - p95ResponseTime < 800; - - const summary = { - test_name: 'YAZ Care Platform - Endurance Test', - timestamp: new Date().toISOString(), - configuration: { - virtual_users: VUS, - duration: __ENV.DURATION || '2h', - total_duration_minutes: calculateTotalMinutes(__ENV.DURATION || '2h'), - }, - performance: { - total_requests: totalRequests, - throughput_rps: throughput.toFixed(2), - avg_response_time_ms: avgResponseTime.toFixed(2), - p95_response_time_ms: p95ResponseTime.toFixed(2), - p99_response_time_ms: p99ResponseTime.toFixed(2), - failure_rate_percent: failureRate.toFixed(2), - }, - stability: { - stability_score: stabilityScore.toFixed(2), - baseline_response_time_ms: baselineResponseTime.toFixed(2), - degradation_events: degradationEventCount, - connection_errors: connectionErrorCount, - memory_issues: memoryIssueCount, - passed: passed, - }, - insights: { - memory_leaks_detected: memoryIssueCount > 5, - performance_degradation: degradationEventCount > 10, - connection_pool_saturation: connectionErrorCount > 20, - recommendation: generateRecommendation(stabilityScore, degradationEventCount, memoryIssueCount, connectionErrorCount), - }, - thresholds_passed: Object.entries(metrics) - .filter(([_, m]) => m.thresholds) - .every(([_, m]) => Object.values(m.thresholds).every(t => t.ok)), - }; - - return { - 'stdout': JSON.stringify(summary, null, 2), - 'endurance-test-results.json': JSON.stringify(summary, null, 2), - }; -} - -function calculateTotalMinutes(duration) { - const match = duration.match(/(\d+)([hm])/); - if (!match) return 120; // Default 2 hours - - const value = parseInt(match[1]); - const unit = match[2]; - - return unit === 'h' ? value * 60 : value; -} - -function generateRecommendation(stabilityScore, degradations, memoryIssues, connectionErrors) { - if (stabilityScore >= 90) { - return 'System demonstrates excellent stability under sustained load. Ready for production.'; - } else if (stabilityScore >= 80) { - return 'System is generally stable but shows minor issues. Monitor in production.'; - } else if (memoryIssues > 5) { - return 'Potential memory leak detected. Investigate memory usage patterns and implement garbage collection tuning.'; - } else if (connectionErrors > 20) { - return 'Connection pool saturation detected. Increase database connection pool size or implement connection queuing.'; - } else if (degradations > 10) { - return 'Performance degradation over time detected. Review resource allocation and optimize slow queries.'; - } else { - return 'System shows instability under sustained load. Conduct detailed profiling and performance optimization.'; - } -} diff --git a/infra/load-testing/health-check.js b/infra/load-testing/health-check.js deleted file mode 100644 index f02003b3151018d036ea304c1b5322cb9709f888..0000000000000000000000000000000000000000 --- a/infra/load-testing/health-check.js +++ /dev/null @@ -1,134 +0,0 @@ -/** - * YAZ Care Platform - Health Check Load Test - * - * Purpose: Validate API availability and basic functionality - * Duration: 30 seconds - * Virtual Users: 10 - * Endpoints: Health check, API docs - * - * Usage: - * k6 run infra/load-testing/health-check.js - * k6 run -e BASE_URL=https://api.yaz.care infra/load-testing/health-check.js - */ - -import http from 'k6/http'; -import { check, sleep } from 'k6'; -import { Rate, Trend } from 'k6/metrics'; - -// Custom metrics -const healthCheckFailRate = new Rate('health_check_failures'); -const healthCheckDuration = new Trend('health_check_duration'); - -// Test configuration -export const options = { - vus: 10, - duration: '30s', - thresholds: { - 'http_req_duration': ['p(95)<50'], // 95% of requests should complete under 50ms - 'http_req_failed': ['rate<0.01'], // Less than 1% of requests should fail - 'health_check_failures': ['rate<0.01'], - 'health_check_duration': ['p(95)<50'], - }, - tags: { - test_type: 'health_check', - environment: __ENV.ENVIRONMENT || 'test', - }, -}; - -// Environment configuration -const BASE_URL = __ENV.BASE_URL || 'http://localhost:8000'; - -export default function () { - // Test 1: Health endpoint - const healthRes = http.get(`${BASE_URL}/health`); - - const healthCheck = check(healthRes, { - 'health check status is 200': (r) => r.status === 200, - 'health check returns JSON': (r) => r.headers['Content-Type']?.includes('application/json'), - 'health check status is healthy': (r) => { - try { - const body = JSON.parse(r.body); - return body.status === 'healthy'; - } catch (e) { - return false; - } - }, - 'health check response time < 50ms': (r) => r.timings.duration < 50, - }); - - healthCheckFailRate.add(!healthCheck); - healthCheckDuration.add(healthRes.timings.duration); - - sleep(0.5); - - // Test 2: API documentation - const docsRes = http.get(`${BASE_URL}/docs`); - - check(docsRes, { - 'docs endpoint accessible': (r) => r.status === 200, - 'docs returns HTML': (r) => r.headers['Content-Type']?.includes('text/html'), - }); - - sleep(1); -} - -export function handleSummary(data) { - return { - 'stdout': textSummary(data, { indent: ' ', enableColors: true }), - 'summary.json': JSON.stringify(data, null, 2), - }; -} - -function textSummary(data, opts) { - const indent = opts?.indent || ''; - const colors = opts?.enableColors ?? false; - - let summary = '\n'; - summary += `${indent}βœ“ Health Check Load Test Summary\n`; - summary += `${indent}${'='.repeat(50)}\n\n`; - - const metrics = data.metrics; - - // Request metrics - if (metrics.http_reqs) { - summary += `${indent}Total Requests: ${metrics.http_reqs.values.count}\n`; - summary += `${indent}Requests/sec: ${metrics.http_reqs.values.rate.toFixed(2)}\n\n`; - } - - // Duration metrics - if (metrics.http_req_duration) { - const dur = metrics.http_req_duration.values; - summary += `${indent}Response Time:\n`; - summary += `${indent} avg: ${dur.avg.toFixed(2)}ms\n`; - summary += `${indent} min: ${dur.min.toFixed(2)}ms\n`; - summary += `${indent} med: ${dur.med.toFixed(2)}ms\n`; - summary += `${indent} max: ${dur.max.toFixed(2)}ms\n`; - summary += `${indent} p(95): ${dur['p(95)'].toFixed(2)}ms\n`; - summary += `${indent} p(99): ${dur['p(99)'].toFixed(2)}ms\n\n`; - } - - // Failure rate - if (metrics.http_req_failed) { - const failRate = (metrics.http_req_failed.values.rate * 100).toFixed(2); - summary += `${indent}Failure Rate: ${failRate}%\n\n`; - } - - // Custom metrics - if (metrics.health_check_failures) { - const healthFailRate = (metrics.health_check_failures.values.rate * 100).toFixed(2); - summary += `${indent}Health Check Failures: ${healthFailRate}%\n`; - } - - // Threshold results - const thresholds = data.root_group?.checks; - if (thresholds) { - summary += `\n${indent}Checks:\n`; - for (const [name, result] of Object.entries(thresholds)) { - const passed = result.passes === result.fails + result.passes; - const status = passed ? 'βœ“' : 'βœ—'; - summary += `${indent} ${status} ${name}: ${result.passes}/${result.passes + result.fails}\n`; - } - } - - return summary; -} diff --git a/infra/load-testing/k6/scripts/healthcare-load-test.js b/infra/load-testing/k6/scripts/healthcare-load-test.js deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/infra/load-testing/labo-workflow-load.js b/infra/load-testing/labo-workflow-load.js deleted file mode 100644 index 842ad9da3f86ce2b84d7a45bd4d4b9d56eae7ec0..0000000000000000000000000000000000000000 --- a/infra/load-testing/labo-workflow-load.js +++ /dev/null @@ -1,311 +0,0 @@ -/** - * YAZ Care Platform - Laboratory Workflow Load Test - * - * Purpose: Test laboratory order processing under load - * Duration: 10 minutes - * Target: 200 orders per minute - * Scenarios: Create orders, submit specimens, file results, verify, query - * - * Usage: - * k6 run infra/load-testing/labo-workflow-load.js - * k6 run -e TARGET_RPS=300 infra/load-testing/labo-workflow-load.js - */ - -import http from 'k6/http'; -import { check, group, sleep } from 'k6'; -import { Counter, Rate, Trend } from 'k6/metrics'; -import { randomString, randomIntBetween, randomItem } from 'https://jslib.k6.io/k6-utils/1.4.0/index.js'; - -// Custom metrics -const labOrdersCreated = new Counter('lab_orders_created'); -const labOrdersFailed = new Counter('lab_orders_failed'); -const labOrderDuration = new Trend('lab_order_duration'); -const specimenProcessingDuration = new Trend('specimen_processing_duration'); -const resultFilingDuration = new Trend('result_filing_duration'); - -// Test configuration -export const options = { - scenarios: { - create_orders: { - executor: 'constant-arrival-rate', - rate: 60, // 60 orders per minute (30% of traffic) - timeUnit: '1m', - duration: '10m', - preAllocatedVUs: 20, - maxVUs: 50, - exec: 'createLabOrder', - }, - submit_specimens: { - executor: 'constant-arrival-rate', - rate: 40, // 40 specimens per minute (20% of traffic) - timeUnit: '1m', - duration: '10m', - preAllocatedVUs: 10, - maxVUs: 30, - exec: 'submitSpecimen', - }, - file_results: { - executor: 'constant-arrival-rate', - rate: 30, // 30 results per minute (15% of traffic) - timeUnit: '1m', - duration: '10m', - preAllocatedVUs: 10, - maxVUs: 20, - exec: 'fileResults', - }, - query_orders: { - executor: 'constant-arrival-rate', - rate: 50, // 50 queries per minute (25% of traffic) - timeUnit: '1m', - duration: '10m', - preAllocatedVUs: 10, - maxVUs: 20, - exec: 'queryOrders', - }, - }, - thresholds: { - 'http_req_duration': ['p(95)<500', 'p(99)<1000'], - 'http_req_failed': ['rate<0.01'], - 'lab_order_duration': ['p(95)<300'], - 'specimen_processing_duration': ['p(95)<200'], - 'result_filing_duration': ['p(95)<250'], - 'lab_orders_failed': ['count<50'], - }, -}; - -// Configuration -const BASE_URL = __ENV.BASE_URL || 'http://localhost:8000'; -const API_VERSION = 'v1'; -const TARGET_RPS = parseInt(__ENV.TARGET_RPS || '200'); - -// Test data -const LAB_TESTS = [ - 'CBC', 'CMP', 'Lipid Panel', 'HbA1c', 'TSH', - 'Vitamin D', 'Iron Panel', 'Liver Panel', 'Kidney Function', 'Urinalysis' -]; - -const SPECIMEN_TYPES = ['blood', 'urine', 'serum', 'plasma', 'csf']; -const PRIORITIES = ['routine', 'urgent', 'stat']; -const PHYSICIANS = ['Dr. Smith', 'Dr. Johnson', 'Dr. Williams', 'Dr. Brown', 'Dr. Davis']; - -// Shared authentication -let authToken = null; - -export function setup() { - const loginRes = http.post( - `${BASE_URL}/api/${API_VERSION}/auth/login`, - JSON.stringify({ - username: __ENV.ADMIN_USERNAME || 'admin', - password: __ENV.ADMIN_PASSWORD || 'admin123', - }), - { headers: { 'Content-Type': 'application/json' } } - ); - - if (loginRes.status === 200) { - const body = JSON.parse(loginRes.body); - return { token: body.access_token || body.token }; - } - - return { token: null }; -} - -export function createLabOrder(data) { - const token = data?.token; - const headers = { - 'Content-Type': 'application/json', - ...(token && { 'Authorization': `Bearer ${token}` }), - }; - - const orderPayload = { - patient_id: `patient_${randomString(8)}`, - patient_name: `Patient ${randomString(6)}`, - test_name: randomItem(LAB_TESTS), - test_code: `TEST_${randomIntBetween(1000, 9999)}`, - priority: randomItem(PRIORITIES), - ordering_physician: randomItem(PHYSICIANS), - clinical_notes: `Test ordered for diagnostic evaluation ${randomString(10)}`, - specimen_type: randomItem(SPECIMEN_TYPES), - }; - - const startTime = Date.now(); - const res = http.post( - `${BASE_URL}/api/${API_VERSION}/labo/orders`, - JSON.stringify(orderPayload), - { headers } - ); - - const duration = Date.now() - startTime; - labOrderDuration.add(duration); - - const success = check(res, { - 'order created successfully': (r) => r.status === 201 || r.status === 200, - 'order returns ID': (r) => { - if (r.status === 200 || r.status === 201) { - try { - const body = JSON.parse(r.body); - return body.id || body.order_id; - } catch (e) { - return false; - } - } - return true; // Don't fail if auth required - }, - }); - - if (success) { - labOrdersCreated.add(1); - } else { - labOrdersFailed.add(1); - } - - sleep(randomIntBetween(1, 3)); -} - -export function submitSpecimen(data) { - const token = data?.token; - const headers = { - 'Content-Type': 'application/json', - ...(token && { 'Authorization': `Bearer ${token}` }), - }; - - const specimenPayload = { - order_id: `order_${randomString(10)}`, - specimen_id: `SPEC_${randomString(8)}`, - specimen_type: randomItem(SPECIMEN_TYPES), - collection_time: new Date().toISOString(), - collected_by: `Nurse ${randomString(5)}`, - volume_ml: randomIntBetween(5, 50), - container_type: randomItem(['vacutainer', 'urine_cup', 'tube']), - }; - - const startTime = Date.now(); - const res = http.post( - `${BASE_URL}/api/${API_VERSION}/labo/specimens`, - JSON.stringify(specimenPayload), - { headers } - ); - - const duration = Date.now() - startTime; - specimenProcessingDuration.add(duration); - - check(res, { - 'specimen submitted': (r) => [200, 201, 401].includes(r.status), - }); - - sleep(randomIntBetween(1, 2)); -} - -export function fileResults(data) { - const token = data?.token; - const headers = { - 'Content-Type': 'application/json', - ...(token && { 'Authorization': `Bearer ${token}` }), - }; - - const resultsPayload = { - order_id: `order_${randomString(10)}`, - test_name: randomItem(LAB_TESTS), - results: { - value: randomIntBetween(50, 200), - unit: randomItem(['mg/dL', 'mmol/L', 'g/dL', 'IU/L']), - reference_range: '70-110', - flag: randomItem(['normal', 'high', 'low']), - }, - performed_by: `Tech ${randomString(5)}`, - performed_at: new Date().toISOString(), - verified: false, - }; - - const startTime = Date.now(); - const res = http.post( - `${BASE_URL}/api/${API_VERSION}/labo/results`, - JSON.stringify(resultsPayload), - { headers } - ); - - const duration = Date.now() - startTime; - resultFilingDuration.add(duration); - - check(res, { - 'results filed': (r) => [200, 201, 401].includes(r.status), - }); - - sleep(randomIntBetween(1, 3)); -} - -export function queryOrders(data) { - const token = data?.token; - const headers = { - ...(token && { 'Authorization': `Bearer ${token}` }), - }; - - // Query orders with various filters - const queryParams = [ - `status=${randomItem(['pending', 'in_progress', 'completed'])}`, - `priority=${randomItem(PRIORITIES)}`, - `test_name=${encodeURIComponent(randomItem(LAB_TESTS))}`, - `limit=${randomIntBetween(10, 50)}`, - ]; - - const res = http.get( - `${BASE_URL}/api/${API_VERSION}/labo/orders?${randomItem(queryParams)}`, - { headers } - ); - - check(res, { - 'query successful': (r) => [200, 401].includes(r.status), - 'query returns data': (r) => { - if (r.status === 200) { - try { - const body = JSON.parse(r.body); - return Array.isArray(body) || Array.isArray(body.data) || Array.isArray(body.results); - } catch (e) { - return false; - } - } - return true; - }, - }); - - sleep(randomIntBetween(1, 2)); -} - -export function handleSummary(data) { - const summary = { - test_name: 'Laboratory Workflow Load Test', - timestamp: new Date().toISOString(), - duration_minutes: 10, - metrics: { - total_requests: data.metrics.http_reqs?.values.count || 0, - requests_per_second: data.metrics.http_reqs?.values.rate || 0, - - // Performance - avg_response_time_ms: data.metrics.http_req_duration?.values.avg || 0, - p95_response_time_ms: data.metrics.http_req_duration?.values['p(95)'] || 0, - p99_response_time_ms: data.metrics.http_req_duration?.values['p(99)'] || 0, - - // Lab-specific metrics - orders_created: data.metrics.lab_orders_created?.values.count || 0, - orders_failed: data.metrics.lab_orders_failed?.values.count || 0, - avg_order_duration_ms: data.metrics.lab_order_duration?.values.avg || 0, - p95_order_duration_ms: data.metrics.lab_order_duration?.values['p(95)'] || 0, - - avg_specimen_processing_ms: data.metrics.specimen_processing_duration?.values.avg || 0, - p95_specimen_processing_ms: data.metrics.specimen_processing_duration?.values['p(95)'] || 0, - - avg_result_filing_ms: data.metrics.result_filing_duration?.values.avg || 0, - p95_result_filing_ms: data.metrics.result_filing_duration?.values['p(95)'] || 0, - - // Error rates - http_failure_rate_percent: (data.metrics.http_req_failed?.values.rate || 0) * 100, - }, - thresholds_passed: Object.entries(data.metrics) - .filter(([_, m]) => m.thresholds) - .every(([_, m]) => Object.values(m.thresholds).every(t => t.ok)), - }; - - return { - 'stdout': JSON.stringify(summary, null, 2), - 'labo-workflow-results.json': JSON.stringify(summary, null, 2), - }; -} diff --git a/infra/load-testing/locustfile.py b/infra/load-testing/locustfile.py deleted file mode 100644 index c3be914313523a12899e324a347dc8f22effa02c..0000000000000000000000000000000000000000 --- a/infra/load-testing/locustfile.py +++ /dev/null @@ -1,428 +0,0 @@ -""" -YAZ Care Platform - Load Testing Suite -Sprint 35 Phase 3: Performance validation for 1000 concurrent users - -Clinical Workflows Tested: -- Patient admission (ADT) -- Lab order creation (LABO) -- Surgical case scheduling (SURGIO) -- Medication dispensing (PHARMA) -- Clinical documentation (CLINICA) - -Performance Targets: -- P50: <100ms -- P95: <200ms -- P99: <500ms -- Error Rate: <1% -- Throughput: 1000+ RPS -""" - -from locust import HttpUser, task, between, events -from locust.contrib.fasthttp import FastHttpUser -import random -import uuid -import json -from datetime import datetime, timedelta -import structlog - -logger = structlog.get_logger() - -# ============================================================================ -# Test Data Generators -# ============================================================================ - -class TestDataGenerator: - """Generate realistic healthcare test data""" - - FIRST_NAMES = ["John", "Jane", "Michael", "Sarah", "David", "Emily", "Robert", "Lisa"] - LAST_NAMES = ["Smith", "Johnson", "Williams", "Brown", "Jones", "Garcia", "Miller"] - - LAB_TESTS = [ - "CBC", "BMP", "CMP", "Lipid Panel", "HbA1c", - "TSH", "Urinalysis", "PT/INR", "Troponin" - ] - - PROCEDURES = [ - "Appendectomy", "Cholecystectomy", "Hernia Repair", - "Total Hip Replacement", "Knee Arthroscopy", "Colonoscopy" - ] - - MEDICATIONS = [ - "Lisinopril", "Metformin", "Amlodipine", "Simvastatin", - "Levothyroxine", "Omeprazole", "Aspirin", "Metoprolol" - ] - - @staticmethod - def generate_patient(): - """Generate random patient data""" - return { - "first_name": random.choice(TestDataGenerator.FIRST_NAMES), - "last_name": random.choice(TestDataGenerator.LAST_NAMES), - "date_of_birth": (datetime.now() - timedelta(days=random.randint(365*20, 365*80))).isoformat(), - "gender": random.choice(["M", "F", "O"]), - "mrn": f"MRN{random.randint(100000, 999999)}", - "phone": f"+1{random.randint(2000000000, 9999999999)}", - "email": f"patient{random.randint(1000, 9999)}@example.com" - } - - @staticmethod - def generate_lab_order(patient_id): - """Generate random lab order""" - return { - "patient_id": patient_id, - "test_name": random.choice(TestDataGenerator.LAB_TESTS), - "priority": random.choice(["routine", "stat", "urgent"]), - "ordered_by": f"dr_smith_{random.randint(1, 10)}", - "clinical_indication": "Routine screening" - } - - @staticmethod - def generate_surgical_case(patient_id): - """Generate random surgical case""" - return { - "patient_id": patient_id, - "procedure": random.choice(TestDataGenerator.PROCEDURES), - "scheduled_date": (datetime.now() + timedelta(days=random.randint(1, 30))).isoformat(), - "surgeon": f"dr_jones_{random.randint(1, 5)}", - "anesthesia_type": random.choice(["general", "spinal", "local"]), - "estimated_duration": random.randint(30, 240) - } - - @staticmethod - def generate_medication_order(patient_id): - """Generate random medication order""" - return { - "patient_id": patient_id, - "medication": random.choice(TestDataGenerator.MEDICATIONS), - "dosage": f"{random.choice([5, 10, 20, 40])}mg", - "frequency": random.choice(["daily", "BID", "TID", "QID"]), - "route": random.choice(["oral", "IV", "IM", "subcutaneous"]), - "duration_days": random.randint(7, 30) - } - -# ============================================================================ -# Load Test Users -# ============================================================================ - -class ClinicalWorkflowUser(FastHttpUser): - """ - Simulates clinical user performing typical workflows - - Performance: Uses FastHttpUser for <10ms overhead per request - Wait Time: 1-3 seconds between requests (realistic user behavior) - """ - - wait_time = between(1, 3) - - def on_start(self): - """Initialize user session with authentication""" - self.tenant_id = f"tenant_{random.randint(1, 10)}" - self.authenticate() - - def authenticate(self): - """Authenticate user and get JWT token""" - response = self.client.post( - "/api/v1/auth/login", - json={ - "username": f"clinician_{random.randint(1, 100)}@hospital.com", - "password": "test_password_123" - }, - name="Authentication" - ) - - if response.status_code == 200: - data = response.json() - self.token = data.get("access_token") - self.client.headers.update({ - "Authorization": f"Bearer {self.token}", - "X-Tenant-ID": self.tenant_id - }) - - @task(10) - def patient_admission(self): - """ - Task: Create patient admission (ADT workflow) - Weight: 10 (most common operation) - Target: <100ms p95 - """ - patient_data = TestDataGenerator.generate_patient() - - with self.client.post( - "/api/v1/clinica/patients", - json=patient_data, - catch_response=True, - name="Patient Admission" - ) as response: - if response.status_code == 201: - self.patient_id = response.json().get("id") - response.success() - else: - response.failure(f"Failed with status {response.status_code}") - - @task(8) - def create_lab_order(self): - """ - Task: Create lab order (LABO workflow) - Weight: 8 - Target: <150ms p95 - """ - if not hasattr(self, 'patient_id'): - return - - lab_order = TestDataGenerator.generate_lab_order(self.patient_id) - - with self.client.post( - "/api/v1/labo/orders", - json=lab_order, - catch_response=True, - name="Create Lab Order" - ) as response: - if response.status_code == 201: - response.success() - else: - response.failure(f"Failed with status {response.status_code}") - - @task(5) - def schedule_surgery(self): - """ - Task: Schedule surgical case (SURGIO workflow) - Weight: 5 - Target: <200ms p95 - """ - if not hasattr(self, 'patient_id'): - return - - surgical_case = TestDataGenerator.generate_surgical_case(self.patient_id) - - with self.client.post( - "/api/v1/surgio/cases", - json=surgical_case, - catch_response=True, - name="Schedule Surgery" - ) as response: - if response.status_code == 201: - response.success() - else: - response.failure(f"Failed with status {response.status_code}") - - @task(7) - def prescribe_medication(self): - """ - Task: Create medication order (PHARMA workflow) - Weight: 7 - Target: <150ms p95 - """ - if not hasattr(self, 'patient_id'): - return - - med_order = TestDataGenerator.generate_medication_order(self.patient_id) - - with self.client.post( - "/api/v1/pharma/orders", - json=med_order, - catch_response=True, - name="Prescribe Medication" - ) as response: - if response.status_code == 201: - response.success() - else: - response.failure(f"Failed with status {response.status_code}") - - @task(15) - def view_patient_list(self): - """ - Task: View patient list (read-heavy operation) - Weight: 15 (most common read) - Target: <50ms p95 (should hit cache) - """ - with self.client.get( - "/api/v1/clinica/patients", - params={"limit": 50, "offset": 0}, - catch_response=True, - name="View Patient List" - ) as response: - if response.status_code == 200: - response.success() - else: - response.failure(f"Failed with status {response.status_code}") - - @task(12) - def view_lab_results(self): - """ - Task: View lab results - Weight: 12 - Target: <100ms p95 - """ - if not hasattr(self, 'patient_id'): - return - - with self.client.get( - f"/api/v1/labo/results?patient_id={self.patient_id}", - catch_response=True, - name="View Lab Results" - ) as response: - if response.status_code == 200: - response.success() - else: - response.failure(f"Failed with status {response.status_code}") - - @task(3) - def generate_clinical_report(self): - """ - Task: Generate clinical report (complex operation) - Weight: 3 (less frequent, more expensive) - Target: <500ms p95 - """ - if not hasattr(self, 'patient_id'): - return - - with self.client.post( - "/api/v1/analytics/reports/clinical", - json={ - "patient_id": self.patient_id, - "report_type": "comprehensive", - "date_range": 30 - }, - catch_response=True, - name="Generate Clinical Report" - ) as response: - if response.status_code == 200: - response.success() - else: - response.failure(f"Failed with status {response.status_code}") - -# ============================================================================ -# Administrative User (lighter load) -# ============================================================================ - -class AdminUser(FastHttpUser): - """ - Simulates administrative user performing management tasks - Weight: Lower than clinical users (1:10 ratio) - """ - - wait_time = between(5, 15) - - @task(5) - def view_dashboard(self): - """View admin dashboard""" - self.client.get("/api/v1/admin/dashboard", name="Admin Dashboard") - - @task(3) - def view_analytics(self): - """View analytics data""" - self.client.get("/api/v1/analytics/summary", name="Analytics Summary") - - @task(2) - def manage_users(self): - """View user management""" - self.client.get("/api/v1/admin/users", name="User Management") - -# ============================================================================ -# Event Listeners for Custom Metrics -# ============================================================================ - -@events.test_start.add_listener -def on_test_start(environment, **kwargs): - """Initialize test metrics""" - logger.info("load_test_started", - target_users=environment.parsed_options.num_users, - target_host=environment.host) - -@events.test_stop.add_listener -def on_test_stop(environment, **kwargs): - """Report final metrics""" - stats = environment.stats - - logger.info("load_test_completed", - total_requests=stats.total.num_requests, - total_failures=stats.total.num_failures, - avg_response_time=stats.total.avg_response_time, - min_response_time=stats.total.min_response_time, - max_response_time=stats.total.max_response_time) - - # Check SLA compliance - p95 = stats.total.get_response_time_percentile(0.95) - p99 = stats.total.get_response_time_percentile(0.99) - error_rate = (stats.total.num_failures / stats.total.num_requests * 100) if stats.total.num_requests > 0 else 0 - - sla_met = p95 < 200 and p99 < 500 and error_rate < 1.0 - - logger.info("sla_validation", - p95_latency=p95, - p99_latency=p99, - error_rate=error_rate, - sla_met=sla_met) - - if not sla_met: - logger.error("sla_violation", - p95_target=200, - p95_actual=p95, - p99_target=500, - p99_actual=p99, - error_rate_target=1.0, - error_rate_actual=error_rate) - -# ============================================================================ -# Load Test Shapes (Ramp-up Scenarios) -# ============================================================================ - -from locust import LoadTestShape - -class ProductionLoadShape(LoadTestShape): - """ - Custom load shape simulating production traffic patterns - - Phase 1 (0-5 min): Ramp up to 100 users - Phase 2 (5-10 min): Ramp up to 500 users - Phase 3 (10-20 min): Peak load 1000 users - Phase 4 (20-25 min): Ramp down to 500 users - Phase 5 (25-30 min): Ramp down to 100 users - """ - - stages = [ - {"duration": 300, "users": 100, "spawn_rate": 10}, - {"duration": 600, "users": 500, "spawn_rate": 20}, - {"duration": 1200, "users": 1000, "spawn_rate": 25}, - {"duration": 1500, "users": 500, "spawn_rate": 25}, - {"duration": 1800, "users": 100, "spawn_rate": 20} - ] - - def tick(self): - run_time = self.get_run_time() - - for stage in self.stages: - if run_time < stage["duration"]: - tick_data = (stage["users"], stage["spawn_rate"]) - return tick_data - - return None - -# ============================================================================ -# Run Instructions: -# ============================================================================ -# -# Basic load test (CLI): -# locust -f infra/load-testing/locustfile.py --host=http://localhost:8000 -# -# Web UI: -# locust -f infra/load-testing/locustfile.py --host=http://localhost:8000 --web-host=0.0.0.0 -# -# Headless with 1000 users: -# locust -f infra/load-testing/locustfile.py \ -# --host=http://localhost:8000 \ -# --users=1000 \ -# --spawn-rate=50 \ -# --run-time=30m \ -# --headless \ -# --html=report.html \ -# --csv=results -# -# Production validation: -# locust -f infra/load-testing/locustfile.py \ -# --host=https://api.yazcare.com \ -# --users=1000 \ -# --spawn-rate=50 \ -# --run-time=1h \ -# --headless -# ============================================================================ diff --git a/infra/load-testing/stress-test.js b/infra/load-testing/stress-test.js deleted file mode 100644 index ccd3862c35898fc675c5be9fcc9927d79255f700..0000000000000000000000000000000000000000 --- a/infra/load-testing/stress-test.js +++ /dev/null @@ -1,311 +0,0 @@ -/** - * YAZ Care Platform - Stress Test - * - * Purpose: Identify system breaking point and resource limits - * Pattern: Gradual ramp-up to 500 VUs, sustained peak, then ramp-down - * Duration: 12 minutes total - * - * Usage: - * k6 run infra/load-testing/stress-test.js - * k6 run -e MAX_VUS=1000 infra/load-testing/stress-test.js - */ - -import http from 'k6/http'; -import { check, group, sleep } from 'k6'; -import { Counter, Rate, Trend, Gauge } from 'k6/metrics'; -import { randomString, randomIntBetween, randomItem } from 'https://jslib.k6.io/k6-utils/1.4.0/index.js'; - -// Custom metrics -const activeUsers = new Gauge('active_users'); -const systemErrors = new Counter('system_errors'); -const timeouts = new Counter('timeouts'); -const slowRequests = new Counter('slow_requests'); -const successRate = new Rate('success_rate'); - -// Test configuration -export const options = { - stages: [ - { duration: '5m', target: 500 }, // Ramp-up: 0 β†’ 500 VUs over 5 minutes - { duration: '5m', target: 500 }, // Peak load: 500 VUs for 5 minutes - { duration: '2m', target: 0 }, // Ramp-down: 500 β†’ 0 VUs over 2 minutes - ], - thresholds: { - // Stress test thresholds are more lenient to find breaking point - 'http_req_duration': [ - 'p(95)<1000', // 95% under 1 second - 'p(99)<2000', // 99% under 2 seconds - ], - 'http_req_failed': ['rate<0.05'], // Less than 5% failure rate - 'system_errors': ['count<100'], - 'timeouts': ['count<50'], - 'success_rate': ['rate>0.95'], - }, - ext: { - loadimpact: { - projectID: 3545656, - name: 'YAZ Care Platform - Stress Test', - }, - }, -}; - -// Configuration -const BASE_URL = __ENV.BASE_URL || 'http://localhost:8000'; -const API_VERSION = 'v1'; -const MAX_VUS = parseInt(__ENV.MAX_VUS || '500'); -const REQUEST_TIMEOUT = '30s'; - -// Test endpoints -const ENDPOINTS = [ - { path: '/health', weight: 10 }, - { path: '/api/v1/auth/me', weight: 15 }, - { path: '/api/v1/labo/orders', weight: 20 }, - { path: '/api/v1/labo/tests', weight: 15 }, - { path: '/api/v1/surgio/or/availability', weight: 10 }, - { path: '/api/v1/surgio/procedures', weight: 10 }, - { path: '/api/v1/clinica/patients', weight: 10 }, - { path: '/api/v1/clinica/encounters', weight: 10 }, -]; - -let authToken = null; - -export function setup() { - console.log(`Starting stress test with target of ${MAX_VUS} virtual users`); - - const loginRes = http.post( - `${BASE_URL}/api/${API_VERSION}/auth/login`, - JSON.stringify({ - username: __ENV.ADMIN_USERNAME || 'admin', - password: __ENV.ADMIN_PASSWORD || 'admin123', - }), - { - headers: { 'Content-Type': 'application/json' }, - timeout: REQUEST_TIMEOUT, - } - ); - - if (loginRes.status === 200) { - const body = JSON.parse(loginRes.body); - return { token: body.access_token || body.token }; - } - - console.warn('Setup: Authentication failed, continuing without token'); - return { token: null }; -} - -export default function (data) { - activeUsers.add(1); - - const token = data?.token; - const headers = { - 'Content-Type': 'application/json', - ...(token && { 'Authorization': `Bearer ${token}` }), - }; - - // Randomly select endpoint based on weights - const endpoint = selectWeightedEndpoint(ENDPOINTS); - - const startTime = new Date(); - const res = http.get( - `${BASE_URL}${endpoint.path}`, - { - headers, - timeout: REQUEST_TIMEOUT, - } - ); - const duration = new Date() - startTime; - - // Track slow requests (> 1 second) - if (duration > 1000) { - slowRequests.add(1); - } - - // Track timeouts - if (res.status === 0 || res.error === 'request timeout') { - timeouts.add(1); - } - - // Track system errors (5xx) - if (res.status >= 500) { - systemErrors.add(1); - } - - const success = check(res, { - 'status is not 5xx': (r) => r.status < 500, - 'response time < 2s': (r) => r.timings.duration < 2000, - 'no timeout': (r) => r.status !== 0, - }); - - successRate.add(success); - - // Variable think time based on endpoint - const thinkTime = randomIntBetween(500, 2000) / 1000; - sleep(thinkTime); - - // Occasionally create lab orders or surgical procedures (write operations) - if (Math.random() < 0.1) { - performWriteOperation(BASE_URL, headers); - } -} - -function selectWeightedEndpoint(endpoints) { - const totalWeight = endpoints.reduce((sum, e) => sum + e.weight, 0); - const random = Math.random() * totalWeight; - - let cumulativeWeight = 0; - for (const endpoint of endpoints) { - cumulativeWeight += endpoint.weight; - if (random <= cumulativeWeight) { - return endpoint; - } - } - - return endpoints[0]; -} - -function performWriteOperation(baseUrl, headers) { - const operations = [ - () => createLabOrder(baseUrl, headers), - () => scheduleOnlineSurgery(baseUrl, headers), - ]; - - const operation = randomItem(operations); - operation(); -} - -function createLabOrder(baseUrl, headers) { - const payload = { - patient_id: `patient_stress_${randomString(8)}`, - patient_name: `Stress Test Patient ${randomString(6)}`, - test_name: randomItem(['CBC', 'CMP', 'Lipid Panel', 'HbA1c']), - test_code: `STRESS_${randomIntBetween(1000, 9999)}`, - priority: randomItem(['routine', 'urgent', 'stat']), - ordering_physician: `Dr. ${randomString(6)}`, - specimen_type: randomItem(['blood', 'urine', 'serum']), - }; - - const res = http.post( - `${baseUrl}/api/v1/labo/orders`, - JSON.stringify(payload), - { - headers, - timeout: REQUEST_TIMEOUT, - } - ); - - check(res, { - 'order created or auth required': (r) => [200, 201, 401].includes(r.status), - }); -} - -function scheduleOnlineSurgery(baseUrl, headers) { - const payload = { - patient_id: `patient_stress_${randomString(8)}`, - procedure_name: randomItem(['Appendectomy', 'Cholecystectomy', 'Hernia Repair']), - surgeon: `Dr. ${randomString(6)}`, - scheduled_date: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString(), - or_number: randomIntBetween(1, 10), - estimated_duration_minutes: randomIntBetween(60, 240), - }; - - const res = http.post( - `${baseUrl}/api/v1/surgio/procedures`, - JSON.stringify(payload), - { - headers, - timeout: REQUEST_TIMEOUT, - } - ); - - check(res, { - 'procedure scheduled or auth required': (r) => [200, 201, 401].includes(r.status), - }); -} - -export function handleSummary(data) { - const metrics = data.metrics; - - // Calculate derived metrics - const avgResponseTime = metrics.http_req_duration?.values.avg || 0; - const p95ResponseTime = metrics.http_req_duration?.values['p(95)'] || 0; - const p99ResponseTime = metrics.http_req_duration?.values['p(99)'] || 0; - const maxResponseTime = metrics.http_req_duration?.values.max || 0; - - const totalRequests = metrics.http_reqs?.values.count || 0; - const failedRequests = (metrics.http_req_failed?.values.rate || 0) * totalRequests; - const throughput = metrics.http_reqs?.values.rate || 0; - - const systemErrorCount = metrics.system_errors?.values.count || 0; - const timeoutCount = metrics.timeouts?.values.count || 0; - const slowRequestCount = metrics.slow_requests?.values.count || 0; - const successRatePercent = (metrics.success_rate?.values.rate || 0) * 100; - - // Determine if system is stable - const isStable = successRatePercent > 95 && p95ResponseTime < 1000 && systemErrorCount < 100; - - // Find breaking point (if any) - const breakingPoint = findBreakingPoint(data); - - const summary = { - test_name: 'YAZ Care Platform - Stress Test', - timestamp: new Date().toISOString(), - configuration: { - max_vus: MAX_VUS, - duration_minutes: 12, - ramp_up_minutes: 5, - peak_duration_minutes: 5, - ramp_down_minutes: 2, - }, - performance: { - total_requests: totalRequests, - failed_requests: Math.round(failedRequests), - throughput_rps: throughput.toFixed(2), - success_rate_percent: successRatePercent.toFixed(2), - - response_times: { - avg_ms: avgResponseTime.toFixed(2), - p50_ms: (metrics.http_req_duration?.values.med || 0).toFixed(2), - p95_ms: p95ResponseTime.toFixed(2), - p99_ms: p99ResponseTime.toFixed(2), - max_ms: maxResponseTime.toFixed(2), - }, - }, - errors: { - system_errors_5xx: systemErrorCount, - timeouts: timeoutCount, - slow_requests_over_1s: slowRequestCount, - }, - stability: { - is_stable: isStable, - breaking_point_vus: breakingPoint, - recommendation: isStable - ? `System is stable at ${MAX_VUS} VUs. Consider increasing load.` - : `System showed degradation. Breaking point around ${breakingPoint} VUs.`, - }, - thresholds_passed: Object.entries(metrics) - .filter(([_, m]) => m.thresholds) - .every(([_, m]) => Object.values(m.thresholds).every(t => t.ok)), - }; - - return { - 'stdout': JSON.stringify(summary, null, 2), - 'stress-test-results.json': JSON.stringify(summary, null, 2), - }; -} - -function findBreakingPoint(data) { - // Analyze metrics over time to identify degradation point - // This is a simplified heuristic - const p95 = data.metrics.http_req_duration?.values['p(95)'] || 0; - const errorRate = data.metrics.http_req_failed?.values.rate || 0; - - if (p95 > 2000 || errorRate > 0.1) { - // System is breaking, estimate at ~80% of target - return Math.round(MAX_VUS * 0.8); - } else if (p95 > 1000 || errorRate > 0.05) { - // System showing stress, estimate at ~90% of target - return Math.round(MAX_VUS * 0.9); - } - - // System handled load well - return MAX_VUS; -} diff --git a/infra/ops/ast_security_check.py b/infra/ops/ast_security_check.py deleted file mode 100644 index ef5e301dff0518c7ca357d47ac691627ac604041..0000000000000000000000000000000000000000 --- a/infra/ops/ast_security_check.py +++ /dev/null @@ -1,238 +0,0 @@ -#!/usr/bin/env python3 -""" -YAZ Care Platform - AST Security Checks -Enforces architectural rules via static analysis -""" - -import ast -import sys -from pathlib import Path -from typing import List, Dict, Set -import json - -class SecurityViolationDetector(ast.NodeVisitor): - """AST visitor to detect security/architecture violations""" - - def __init__(self, file_path: Path): - self.file_path = file_path - self.violations: List[Dict] = [] - self.imports: Set[str] = set() - self.class_names: Set[str] = set() - - def visit_Import(self, node): - """Track import statements""" - for alias in node.names: - self.imports.add(alias.name) - self.generic_visit(node) - - def visit_ImportFrom(self, node): - """Track from imports""" - if node.module: - for alias in node.names: - full_name = f"{node.module}.{alias.name}" - self.imports.add(full_name) - self.imports.add(alias.name) - self.generic_visit(node) - - def visit_ClassDef(self, node): - """Track class definitions""" - self.class_names.add(node.name) - - # Check for model classes in apps (VIOLATION) - if self._is_app_file() and self._is_model_class(node): - self.violations.append({ - "type": "MODEL_IN_APP", - "message": f"Model class '{node.name}' found in app directory", - "line": node.lineno, - "rule": "Apps never touch DB - models must be in /core" - }) - - self.generic_visit(node) - - def _is_app_file(self) -> bool: - """Check if file is in app directory""" - return "src/apps/" in str(self.file_path) - - def _is_model_class(self, node) -> bool: - """Check if class appears to be a data model""" - # Check inheritance - for base in node.bases: - if isinstance(base, ast.Name): - base_name = base.id - if any(model_indicator in base_name.lower() for model_indicator in - ["model", "base", "table", "entity"]): - return True - elif isinstance(base, ast.Attribute): - attr_name = base.attr - if any(model_indicator in attr_name.lower() for model_indicator in - ["model", "base", "table", "entity"]): - return True - - # Check decorators - for decorator in node.decorator_list: - if isinstance(decorator, ast.Name) and "table" in decorator.id.lower(): - return True - - return False - - def check_forbidden_imports(self): - """Check for forbidden imports in apps""" - if not self._is_app_file(): - return - - forbidden_patterns = [ - ("sqlalchemy", "Direct SQLAlchemy use forbidden in apps"), - ("sqlmodel", "Direct SQLModel use forbidden in apps"), - ("database", "Direct database imports forbidden in apps"), - ("Session", "Database session forbidden in apps"), - ("sessionmaker", "Database session creation forbidden in apps"), - ] - - for pattern, message in forbidden_patterns: - for import_name in self.imports: - if pattern.lower() in import_name.lower(): - self.violations.append({ - "type": "FORBIDDEN_IMPORT", - "message": f"Forbidden import: {import_name} - {message}", - "line": 1, # Hard to get exact line from imports set - "rule": "Apps never touch DB - import from core.services instead" - }) - -def check_file(file_path: Path) -> List[Dict]: - """Check single Python file for violations""" - try: - with open(file_path, 'r', encoding='utf-8') as f: - source = f.read() - - tree = ast.parse(source) - detector = SecurityViolationDetector(file_path) - detector.visit(tree) - detector.check_forbidden_imports() - - return detector.violations - - except Exception as e: - return [{ - "type": "PARSE_ERROR", - "message": f"Failed to parse {file_path}: {e}", - "line": 0, - "rule": "File must be valid Python" - }] - -def check_route_guards(file_path: Path) -> List[Dict]: - """Check that routes use proper guards""" - violations = [] - - try: - with open(file_path, 'r', encoding='utf-8') as f: - content = f.read() - - # If this is an API file, check for router usage - if "api.py" in str(file_path) and "@router." in content: - # Check if mount_app is used - if "mount_app" not in content and "include_router" not in content: - violations.append({ - "type": "UNGUARDED_ROUTER", - "message": "Router not mounted with mount_app - bypasses guards", - "line": 0, - "rule": "All routes must go through mount_app for tenant+license guards" - }) - - except Exception as e: - violations.append({ - "type": "GUARD_CHECK_ERROR", - "message": f"Failed to check guards in {file_path}: {e}", - "line": 0, - "rule": "File must be readable for guard verification" - }) - - return violations - -def main(): - """Run AST security checks""" - print("πŸ”’ YAZ Care Platform - AST Security Checks") - print("=" * 50) - print("Enforcing immutable laws via static analysis...") - - # Find all Python files - python_files = [] - for pattern in ["src/**/*.py", "core/**/*.py"]: - python_files.extend(Path(".").glob(pattern)) - - all_violations = [] - files_checked = 0 - - for py_file in python_files: - if py_file.name == "__pycache__": - continue - - files_checked += 1 - - # Check architectural violations - violations = check_file(py_file) - - # Check route guard usage - violations.extend(check_route_guards(py_file)) - - for violation in violations: - violation["file"] = str(py_file) - all_violations.append(violation) - - # Group violations by type - violation_types = {} - for v in all_violations: - v_type = v["type"] - if v_type not in violation_types: - violation_types[v_type] = [] - violation_types[v_type].append(v) - - # Report results - print(f"πŸ“Š Checked {files_checked} Python files") - - if not all_violations: - print("βœ… No violations found - all immutable laws enforced") - - # Save clean results - results = { - "status": "passed", - "files_checked": files_checked, - "violations": [], - "timestamp": "2024-10-31T23:00:00Z" - } - - Path("logs").mkdir(exist_ok=True) - with open("logs/ast_security_check.json", "w") as f: - json.dump(results, f, indent=2) - - return 0 - - else: - print(f"❌ Found {len(all_violations)} violations across {len(violation_types)} categories") - print() - - for v_type, violations in violation_types.items(): - print(f"🚨 {v_type}: {len(violations)} violations") - for v in violations[:3]: # Show first 3 - print(f" β€’ {v['file']}:{v['line']} - {v['message']}") - if len(violations) > 3: - print(f" β€’ ... and {len(violations) - 3} more") - print() - - # Save violation results - results = { - "status": "failed", - "files_checked": files_checked, - "violations": all_violations, - "violation_count": len(all_violations), - "timestamp": "2024-10-31T23:00:00Z" - } - - Path("logs").mkdir(exist_ok=True) - with open("logs/ast_security_check.json", "w") as f: - json.dump(results, f, indent=2) - - print("πŸ›‘ BUILD SHOULD FAIL - Fix violations before proceeding") - return 1 - -if __name__ == "__main__": - sys.exit(main()) \ No newline at end of file diff --git a/infra/ops/check_dupes.py b/infra/ops/check_dupes.py deleted file mode 100644 index a66a795e01ae4f5903cf375d3f107feb5c68cf84..0000000000000000000000000000000000000000 --- a/infra/ops/check_dupes.py +++ /dev/null @@ -1,318 +0,0 @@ -#!/usr/bin/env python3 -""" -YAZ Care Platform - Duplicate Code Detection -Scans for duplicate models, services, and shared code across apps -""" - -import sys -import hashlib -from pathlib import Path -from typing import Dict, List, Set, Tuple -import ast -import json -from collections import defaultdict -import argparse - -def hash_file_content(file_path: Path) -> str: - """Generate hash of file content for comparison""" - try: - with open(file_path, 'r', encoding='utf-8') as f: - content = f.read().strip() - # Normalize whitespace for comparison - normalized = '\n'.join(line.strip() for line in content.split('\n') if line.strip()) - return hashlib.md5(normalized.encode()).hexdigest() - except Exception: - return "" - -def extract_class_names(file_path: Path) -> Set[str]: - """Extract class names from Python file""" - try: - with open(file_path, 'r', encoding='utf-8') as f: - tree = ast.parse(f.read()) - - classes = set() - for node in ast.walk(tree): - if isinstance(node, ast.ClassDef): - classes.add(node.name) - return classes - except Exception: - return set() - -def extract_function_names(file_path: Path) -> Set[str]: - """Extract function names from Python file""" - try: - with open(file_path, 'r', encoding='utf-8') as f: - tree = ast.parse(f.read()) - - functions = set() - for node in ast.walk(tree): - if isinstance(node, ast.FunctionDef): - functions.add(node.name) - return functions - except Exception: - return set() - -def find_duplicates_by_content(paths: List[Path]) -> Dict[str, List[Path]]: - """Find files with identical content""" - hash_to_files = defaultdict(list) - - for path in paths: - if path.is_file() and path.suffix == '.py': - file_hash = hash_file_content(path) - if file_hash: # Only add non-empty hashes - hash_to_files[file_hash].append(path) - - # Return only duplicates (hash maps to 2+ files) - return {h: files for h, files in hash_to_files.items() if len(files) > 1} - -def find_duplicates_by_class_names(paths: List[Path]) -> Dict[str, List[Path]]: - """Find files that define the same class names""" - class_to_files: Dict[str, List[Path]] = defaultdict(list) - - for path in paths: - if path.is_file() and path.suffix == '.py': - classes = extract_class_names(path) - for class_name in classes: - class_to_files[class_name].append(path) - - # Return only duplicates - return {cls: files for cls, files in class_to_files.items() if len(files) > 1} - -def analyze_directory(directory: Path, patterns: List[str] = None) -> Dict: - """Analyze directory for duplicates""" - if patterns is None: - patterns = ["**/*.py"] - - all_files = [] - for pattern in patterns: - all_files.extend(directory.glob(pattern)) - - # Categorize files - model_files = [f for f in all_files if 'model' in f.name.lower() or '/models/' in str(f)] - service_files = [f for f in all_files if 'service' in f.name.lower() or '/services/' in str(f)] - other_files = [f for f in all_files if f not in model_files and f not in service_files] - - results = { - "directory": str(directory), - "total_files": len(all_files), - "model_files": len(model_files), - "service_files": len(service_files), - "other_files": len(other_files), - "duplicates": { - "by_content": {}, - "by_class_names": {}, - "models": {}, - "services": {} - } - } - - # Find content duplicates - content_dupes = find_duplicates_by_content(all_files) - results["duplicates"]["by_content"] = { - h: [str(f) for f in files] for h, files in content_dupes.items() - } - - # Find class name duplicates - class_dupes = find_duplicates_by_class_names(all_files) - results["duplicates"]["by_class_names"] = { - cls: [str(f) for f in files] for cls, files in class_dupes.items() - } - - # Analyze models specifically - if model_files: - model_class_dupes = find_duplicates_by_class_names(model_files) - results["duplicates"]["models"] = { - cls: [str(f) for f in files] for cls, files in model_class_dupes.items() - } - - # Analyze services specifically - if service_files: - service_class_dupes = find_duplicates_by_class_names(service_files) - results["duplicates"]["services"] = { - cls: [str(f) for f in files] for cls, files in service_class_dupes.items() - } - - return results - -def generate_consolidation_plan(apps_analysis: Dict, core_analysis: Dict) -> List[Dict]: - """Generate plan for consolidating code to /core""" - plan = [] - - # Find models in apps that should move to core - for app_name, app_data in apps_analysis.items(): - app_path = Path(app_data["directory"]) - - # Check for models directory - models_dir = app_path / "models" - if models_dir.exists(): - plan.append({ - "action": "move_directory", - "source": str(models_dir), - "target": f"core/models/{app_name}", - "reason": "Consolidate app models to core", - "type": "models" - }) - - # Check for services directory - services_dir = app_path / "services" - if services_dir.exists(): - plan.append({ - "action": "move_directory", - "source": str(services_dir), - "target": f"core/services/{app_name}", - "reason": "Consolidate app services to core", - "type": "services" - }) - - # Check for individual model files - model_files = list(app_path.glob("**/model*.py")) - for model_file in model_files: - if "models" not in str(model_file): # Not already in models dir - plan.append({ - "action": "move_file", - "source": str(model_file), - "target": f"core/models/{app_name}/{model_file.name}", - "reason": "Move standalone model file to core", - "type": "models" - }) - - return plan - -def check_models_in_apps_violation() -> List[Path]: - """Check for SQLModel violations in apps directory""" - violations = [] - apps_path = Path("apps") - - if not apps_path.exists(): - return violations - - for py_file in apps_path.rglob("*.py"): - try: - with open(py_file, 'r', encoding='utf-8') as f: - content = f.read() - # Check for SQLModel imports and table definitions - if ('SQLModel' in content or 'table=True' in content or - 'from sqlmodel import' in content): - violations.append(py_file) - except Exception: - pass - - return violations - -def main(): - """Main duplicate detection and consolidation planning""" - parser = argparse.ArgumentParser(description="Detect duplicates and plan consolidation") - parser.add_argument("--paths", nargs="+", default=["apps", "core"], help="Paths to analyze") - parser.add_argument("--output", default="logs/duplicate_analysis.json", help="Output file") - parser.add_argument("--plan", action="store_true", help="Generate consolidation plan") - parser.add_argument("--fail-on-violation", action="store_true", help="Exit 1 if violations found") - args = parser.parse_args() - - print("πŸ” YAZ Care Platform - Duplicate Code Detection") - print("=" * 50) - - results = { - "timestamp": subprocess.run(["date", "-Iseconds"], capture_output=True, text=True).stdout.strip(), - "analysis": {}, - "consolidation_plan": [] - } - - # Analyze each path - for path_str in args.paths: - path = Path(path_str) - if not path.exists(): - print(f"⚠️ Path {path} does not exist, skipping...") - continue - - print(f"Analyzing {path}...") - - if path.name == "apps": - # Analyze each app subdirectory - app_results = {} - for app_dir in path.iterdir(): - if app_dir.is_dir() and not app_dir.name.startswith('.'): - app_analysis = analyze_directory(app_dir) - app_results[app_dir.name] = app_analysis - - # Report findings - content_dupes = len(app_analysis["duplicates"]["by_content"]) - class_dupes = len(app_analysis["duplicates"]["by_class_names"]) - - if content_dupes > 0 or class_dupes > 0: - print(f" πŸ“± {app_dir.name}: {content_dupes} content dupes, {class_dupes} class dupes") - else: - print(f" πŸ“± {app_dir.name}: βœ… No duplicates") - - results["analysis"]["apps"] = app_results - else: - # Analyze single directory - analysis = analyze_directory(path) - results["analysis"][path.name] = analysis - - content_dupes = len(analysis["duplicates"]["by_content"]) - class_dupes = len(analysis["duplicates"]["by_class_names"]) - print(f" πŸ“ {path.name}: {content_dupes} content dupes, {class_dupes} class dupes") - - # Generate consolidation plan if requested - if args.plan and "apps" in results["analysis"]: - print("\nπŸ“‹ Generating consolidation plan...") - plan = generate_consolidation_plan( - results["analysis"]["apps"], - results["analysis"].get("core", {}) - ) - results["consolidation_plan"] = plan - - print(f"Generated {len(plan)} consolidation actions:") - for i, action in enumerate(plan[:10], 1): # Show first 10 - print(f" {i}. {action['action']}: {action['source']} β†’ {action['target']}") - - if len(plan) > 10: - print(f" ... and {len(plan) - 10} more actions") - - # Save results - output_path = Path(args.output) - output_path.parent.mkdir(exist_ok=True) - - with open(output_path, 'w') as f: - json.dump(results, f, indent=2) - - print(f"\nπŸ“ Analysis saved to {output_path}") - - # Check for SQLModel violations in apps - print("\nπŸ” Checking for SQLModel violations in apps...") - model_violations = check_models_in_apps_violation() - - # Summary - total_dupes = 0 - for analysis_group in results["analysis"].values(): - if isinstance(analysis_group, dict): - if "duplicates" in analysis_group: - total_dupes += len(analysis_group["duplicates"]["by_content"]) - else: - # This is apps analysis - for app_analysis in analysis_group.values(): - total_dupes += len(app_analysis["duplicates"]["by_content"]) - - violations_found = total_dupes > 0 or len(model_violations) > 0 - - if model_violations: - print(f"\n❌ Found {len(model_violations)} SQLModel violations in apps:") - for violation in model_violations: - print(f" - {violation}") - - if total_dupes > 0: - print(f"\n❌ Found {total_dupes} duplicate file groups") - print("πŸ”§ Review consolidation plan and execute moves") - - if violations_found: - if args.fail_on_violation: - return 1 - print("\nπŸ”§ Consolidation required") - return 1 - else: - print("\nβœ… No duplicates or violations found") - return 0 - -if __name__ == "__main__": - import subprocess - sys.exit(main()) diff --git a/infra/ops/check_unguarded_routes.py b/infra/ops/check_unguarded_routes.py deleted file mode 100644 index 0641faac47405e656017b6676acd5db7725eb3b7..0000000000000000000000000000000000000000 --- a/infra/ops/check_unguarded_routes.py +++ /dev/null @@ -1,270 +0,0 @@ -#!/usr/bin/env python3 -""" -YAZ Care Platform - Unguarded Routes Detection -Ensures all routes are protected by tenant_guard and license_guard -""" - -import ast -import sys -from pathlib import Path -from typing import List, Dict, Set, Tuple -import argparse -import json - -class RouteAnalyzer(ast.NodeVisitor): - """AST visitor to find FastAPI routes and their guards""" - - def __init__(self): - self.routes: List[Dict] = [] - self.current_file = None - self.decorators_in_scope: Set[str] = set() - self.dependencies_in_scope: List[str] = [] - - def visit_FunctionDef(self, node: ast.FunctionDef): - """Visit function definitions to find route handlers""" - route_decorators = [] - dependencies = [] - - # Check decorators for route definitions - for decorator in node.decorator_list: - if isinstance(decorator, ast.Name): - # Simple decorator like @router.get - if any(method in decorator.id for method in ['get', 'post', 'put', 'delete', 'patch']): - route_decorators.append(decorator.id) - elif isinstance(decorator, ast.Attribute): - # Attribute decorator like router.get, app.post - if hasattr(decorator, 'attr') and decorator.attr in ['get', 'post', 'put', 'delete', 'patch', 'options', 'head']: - route_decorators.append(f"{self._get_name(decorator.value)}.{decorator.attr}") - - # Check function parameters for Depends() - for arg in node.args.args: - if hasattr(arg, 'annotation'): - annotation_str = ast.unparse(arg.annotation) if arg.annotation else "" - if 'Depends(' in annotation_str: - dependencies.append(annotation_str) - - # If this is a route handler, record it - if route_decorators: - route_info = { - 'file': str(self.current_file), - 'function': node.name, - 'line': node.lineno, - 'decorators': route_decorators, - 'dependencies': dependencies, - 'has_tenant_guard': any('tenant' in dep.lower() for dep in dependencies), - 'has_license_guard': any('license' in dep.lower() for dep in dependencies), - 'is_guarded': False - } - - # Check if properly guarded - route_info['is_guarded'] = ( - route_info['has_tenant_guard'] and route_info['has_license_guard'] - ) or any('require_' in dep for dep in dependencies) - - self.routes.append(route_info) - - self.generic_visit(node) - - def _get_name(self, node): - """Get name from AST node""" - if isinstance(node, ast.Name): - return node.id - elif isinstance(node, ast.Attribute): - return f"{self._get_name(node.value)}.{node.attr}" - else: - return "unknown" - -def analyze_file(file_path: Path) -> List[Dict]: - """Analyze a Python file for unguarded routes""" - try: - with open(file_path, 'r', encoding='utf-8') as f: - content = f.read() - - tree = ast.parse(content) - analyzer = RouteAnalyzer() - analyzer.current_file = file_path - analyzer.visit(tree) - - return analyzer.routes - except Exception as e: - print(f"⚠️ Warning: Could not analyze {file_path}: {e}") - return [] - -def find_all_route_files(base_paths: List[str]) -> List[Path]: - """Find all Python files that might contain routes""" - route_files = [] - - for base_path in base_paths: - path = Path(base_path) - if not path.exists(): - continue - - # Look for common route file patterns - patterns = [ - "**/router*.py", - "**/route*.py", - "**/api*.py", - "**/main.py", - "**/app.py", - "**/__init__.py" - ] - - for pattern in patterns: - route_files.extend(path.glob(pattern)) - - return list(set(route_files)) # Remove duplicates - -def check_mount_app_usage(base_paths: List[str]) -> Dict: - """Check if routes are properly mounted via mount_app""" - mount_usage = { - 'files_with_mount_app': [], - 'files_with_direct_include': [], - 'violations': [] - } - - for base_path in base_paths: - path = Path(base_path) - if not path.exists(): - continue - - for py_file in path.rglob("*.py"): - try: - with open(py_file, 'r', encoding='utf-8') as f: - content = f.read() - - if 'mount_app(' in content: - mount_usage['files_with_mount_app'].append(str(py_file)) - elif 'include_router(' in content and 'mount_app' not in content: - mount_usage['files_with_direct_include'].append(str(py_file)) - mount_usage['violations'].append({ - 'file': str(py_file), - 'issue': 'Uses include_router instead of mount_app', - 'severity': 'high' - }) - except Exception: - pass - - return mount_usage - -def generate_guard_report(routes: List[Dict], mount_usage: Dict) -> Dict: - """Generate comprehensive guard compliance report""" - total_routes = len(routes) - guarded_routes = [r for r in routes if r['is_guarded']] - unguarded_routes = [r for r in routes if not r['is_guarded']] - - # Categorize unguarded routes - public_endpoints = [] - security_violations = [] - - for route in unguarded_routes: - # Check if this might be a legitimate public endpoint - function_name = route['function'].lower() - if any(keyword in function_name for keyword in ['health', 'docs', 'openapi', 'static', 'favicon']): - public_endpoints.append(route) - else: - security_violations.append(route) - - report = { - 'summary': { - 'total_routes': total_routes, - 'guarded_routes': len(guarded_routes), - 'unguarded_routes': len(unguarded_routes), - 'public_endpoints': len(public_endpoints), - 'security_violations': len(security_violations), - 'compliance_percentage': (len(guarded_routes) / max(total_routes, 1)) * 100 - }, - 'violations': { - 'unguarded_routes': security_violations, - 'mount_app_violations': mount_usage['violations'] - }, - 'public_endpoints': public_endpoints, - 'mount_usage': mount_usage - } - - return report - -def main(): - """Main guard compliance checker""" - parser = argparse.ArgumentParser(description="Check route guard compliance") - parser.add_argument("--paths", nargs="+", default=["apps", "core", "src"], - help="Paths to check for routes") - parser.add_argument("--output", default="logs/guard_compliance.json", - help="Output file for detailed report") - parser.add_argument("--fail-on-violation", action="store_true", - help="Exit with code 1 if violations found") - - args = parser.parse_args() - - print("πŸ›‘οΈ YAZ Care Platform - Route Guard Compliance Check") - print("=" * 55) - - # Find all route files - route_files = find_all_route_files(args.paths) - print(f"Found {len(route_files)} potential route files") - - # Analyze routes - all_routes = [] - for file_path in route_files: - routes = analyze_file(file_path) - all_routes.extend(routes) - - # Check mount_app usage - mount_usage = check_mount_app_usage(args.paths) - - # Generate report - report = generate_guard_report(all_routes, mount_usage) - - # Display summary - summary = report['summary'] - print(f"\nπŸ“Š Guard Compliance Summary:") - print(f" Total routes: {summary['total_routes']}") - print(f" Guarded routes: {summary['guarded_routes']}") - print(f" Unguarded routes: {summary['unguarded_routes']}") - print(f" Public endpoints: {summary['public_endpoints']}") - print(f" Security violations: {summary['security_violations']}") - print(f" Compliance: {summary['compliance_percentage']:.1f}%") - - # Display mount_app violations - mount_violations = len(mount_usage['violations']) - if mount_violations > 0: - print(f"\n❌ Found {mount_violations} mount_app violations:") - for violation in mount_usage['violations'][:5]: # Show first 5 - print(f" - {violation['file']}: {violation['issue']}") - if mount_violations > 5: - print(f" ... and {mount_violations - 5} more") - - # Display security violations - security_violations = report['violations']['unguarded_routes'] - if security_violations: - print(f"\n🚨 Security Violations ({len(security_violations)}):") - for violation in security_violations[:5]: # Show first 5 - print(f" - {violation['file']}:{violation['line']} {violation['function']}()") - if len(security_violations) > 5: - print(f" ... and {len(security_violations) - 5} more") - - # Save detailed report - output_path = Path(args.output) - output_path.parent.mkdir(exist_ok=True) - - with open(output_path, 'w') as f: - json.dump(report, f, indent=2) - - print(f"\nπŸ“ Detailed report saved to {output_path}") - - # Determine exit code - has_violations = ( - summary['security_violations'] > 0 or - len(mount_usage['violations']) > 0 - ) - - if has_violations: - print("\n❌ Guard compliance violations found") - if args.fail_on_violation: - return 1 - return 1 - else: - print("\nβœ… All routes properly guarded") - return 0 - -if __name__ == "__main__": - sys.exit(main()) \ No newline at end of file diff --git a/infra/ops/db_snapshot.sh b/infra/ops/db_snapshot.sh deleted file mode 100755 index 890504ca3dfd19945f0bdb8b2ea1c32ef348fe1b..0000000000000000000000000000000000000000 --- a/infra/ops/db_snapshot.sh +++ /dev/null @@ -1,165 +0,0 @@ -#!/bin/bash -""" -YAZ Care Platform - Database Snapshot -Creates safety snapshot of current database before major changes -""" - -set -euo pipefail - -# Configuration -BACKUP_DIR="storage/backups/snapshots" -TIMESTAMP=$(date +"%Y%m%d_%H%M%S") -DB_NAME="yaz_platform" -DB_USER="yazcare_user" -DB_HOST="localhost" -DB_PORT="5432" - -# Colors for output -RED='\033[0;31m' -GREEN='\033[0;32m' -YELLOW='\033[1;33m' -BLUE='\033[0;34m' -NC='\033[0m' # No Color - -log() { - echo -e "${BLUE}[$(date '+%Y-%m-%d %H:%M:%S')]${NC} $1" -} - -error() { - echo -e "${RED}[ERROR]${NC} $1" >&2 -} - -success() { - echo -e "${GREEN}[SUCCESS]${NC} $1" -} - -warning() { - echo -e "${YELLOW}[WARNING]${NC} $1" -} - -# Create backup directory -mkdir -p "$BACKUP_DIR" - -log "πŸ” YAZ Care Platform - Database Snapshot" -log "Creating safety snapshot before deployment..." - -# Check if database is accessible -log "Checking database connectivity..." - -if command -v docker >/dev/null 2>&1; then - # Try Docker container first - if docker ps --format "table {{.Names}}" | grep -q "postgres\|yaz.*postgres"; then - CONTAINER_NAME=$(docker ps --format "{{.Names}}" | grep -E "postgres|yaz.*postgres" | head -1) - log "Found PostgreSQL container: $CONTAINER_NAME" - - DB_CMD="docker exec $CONTAINER_NAME pg_dump -U $DB_USER -h localhost $DB_NAME" - DB_CHECK="docker exec $CONTAINER_NAME psql -U $DB_USER -h localhost -d $DB_NAME -c '\dt'" - else - warning "No PostgreSQL Docker container found, trying local connection..." - DB_CMD="pg_dump -U $DB_USER -h $DB_HOST -p $DB_PORT $DB_NAME" - DB_CHECK="psql -U $DB_USER -h $DB_HOST -p $DB_PORT -d $DB_NAME -c '\dt'" - fi -else - # Direct connection - DB_CMD="pg_dump -U $DB_USER -h $DB_HOST -p $DB_PORT $DB_NAME" - DB_CHECK="psql -U $DB_USER -h $DB_HOST -p $DB_PORT -d $DB_NAME -c '\dt'" -fi - -# Test database connection -log "Testing database connection..." -if ! $DB_CHECK >/dev/null 2>&1; then - error "Cannot connect to database" - error "Please ensure PostgreSQL is running and credentials are correct" - - # Try to find running database containers/processes - log "Searching for database services..." - - if command -v docker >/dev/null 2>&1; then - POSTGRES_CONTAINERS=$(docker ps --filter "ancestor=postgres" --format "{{.Names}}" 2>/dev/null || true) - if [ -n "$POSTGRES_CONTAINERS" ]; then - log "Found PostgreSQL containers: $POSTGRES_CONTAINERS" - fi - fi - - if command -v pgrep >/dev/null 2>&1; then - POSTGRES_PROCESSES=$(pgrep -f postgres 2>/dev/null || true) - if [ -n "$POSTGRES_PROCESSES" ]; then - log "Found PostgreSQL processes: $POSTGRES_PROCESSES" - fi - fi - - exit 1 -fi - -success "Database connection established" - -# Get database info -log "Gathering database information..." -TABLE_COUNT=$($DB_CHECK 2>/dev/null | grep -c "public |" || echo "0") -log "Found $TABLE_COUNT tables in database" - -# Create snapshot -SNAPSHOT_FILE="$BACKUP_DIR/snapshot_${TIMESTAMP}.sql" -METADATA_FILE="$BACKUP_DIR/snapshot_${TIMESTAMP}.json" - -log "Creating database snapshot..." -log "Snapshot file: $SNAPSHOT_FILE" - -if $DB_CMD > "$SNAPSHOT_FILE" 2>/dev/null; then - SNAPSHOT_SIZE=$(du -h "$SNAPSHOT_FILE" | cut -f1) - success "Database snapshot created successfully ($SNAPSHOT_SIZE)" - - # Create metadata - cat > "$METADATA_FILE" << EOF -{ - "timestamp": "$TIMESTAMP", - "database": "$DB_NAME", - "user": "$DB_USER", - "host": "$DB_HOST", - "port": "$DB_PORT", - "table_count": $TABLE_COUNT, - "snapshot_file": "$SNAPSHOT_FILE", - "size": "$SNAPSHOT_SIZE", - "created_by": "preflight_check", - "purpose": "safety_snapshot_before_deployment" -} -EOF - - log "Metadata saved to: $METADATA_FILE" - - # Test snapshot integrity - log "Testing snapshot integrity..." - if head -20 "$SNAPSHOT_FILE" | grep -q "PostgreSQL database dump"; then - success "Snapshot integrity verified" - else - warning "Snapshot may be corrupted - please verify manually" - fi - - # Show recent snapshots - log "Recent snapshots in $BACKUP_DIR:" - ls -lah "$BACKUP_DIR"/snapshot_*.sql 2>/dev/null | tail -5 || log "No previous snapshots found" - - # Clean old snapshots (keep last 10) - SNAPSHOT_COUNT=$(ls -1 "$BACKUP_DIR"/snapshot_*.sql 2>/dev/null | wc -l) - if [ "$SNAPSHOT_COUNT" -gt 10 ]; then - log "Cleaning old snapshots (keeping last 10)..." - ls -1t "$BACKUP_DIR"/snapshot_*.sql | tail -n +11 | xargs rm -f - ls -1t "$BACKUP_DIR"/snapshot_*.json | tail -n +11 | xargs rm -f - success "Old snapshots cleaned" - fi - - success "βœ… Database snapshot completed successfully" - log "πŸ“ Snapshot: $SNAPSHOT_FILE ($SNAPSHOT_SIZE)" - log "πŸš€ Safe to proceed with deployment" - -else - error "Failed to create database snapshot" - error "Check database permissions and disk space" - exit 1 -fi - -# Create symlink to latest snapshot -cd "$BACKUP_DIR" -ln -sf "snapshot_${TIMESTAMP}.sql" "latest.sql" -ln -sf "snapshot_${TIMESTAMP}.json" "latest.json" -log "Latest snapshot symlinked as 'latest.sql'" \ No newline at end of file diff --git a/infra/ops/infra.py b/infra/ops/infra.py deleted file mode 100644 index aef43ef5152d3bed4831b1c365a7ee9d62220d53..0000000000000000000000000000000000000000 --- a/infra/ops/infra.py +++ /dev/null @@ -1,168 +0,0 @@ -#!/usr/bin/env python3 -""" -YAZ Care Platform - Infrastructure Consolidation -Consolidates scattered infrastructure configs into organized structure -""" - -import shutil -from pathlib import Path - -def consolidate_infrastructure(): - """Consolidate and organize infrastructure configurations""" - - project_root = Path("/workspaces/yaz") - - # Create organized infra structure - infra_new = project_root / "infra_organized" - infra_new.mkdir(exist_ok=True) - - # Create environment-specific directories - environments = ["development", "staging", "production"] - for env in environments: - (infra_new / env).mkdir(exist_ok=True) - (infra_new / env / "docker").mkdir(exist_ok=True) - (infra_new / env / "k8s").mkdir(exist_ok=True) - (infra_new / env / "monitoring").mkdir(exist_ok=True) - - print("βœ… Infrastructure organization structure created") - - # Consolidate Docker Compose files - docker_unified = """# YAZ Care Platform - Environment-Specific Docker Compose -# Generated by infrastructure consolidation - -version: '3.8' - -services: - yaz-api: - build: ../../.. - environment: - - YAZ_ENVIRONMENT={environment} - ports: - - "8000:8000" - - postgres: - image: postgres:15-alpine - environment: - POSTGRES_DB: yaz_care - POSTGRES_USER: yaz_user - POSTGRES_PASSWORD: yaz_password - - redis: - image: redis:7-alpine -""" - - for env in environments: - compose_file = infra_new / env / "docker" / "docker-compose.yml" - compose_file.write_text(docker_unified.format(environment=env)) - - print("βœ… Consolidated Docker Compose files created") - - # Create Kubernetes manifests template - k8s_template = """apiVersion: apps/v1 -kind: Deployment -metadata: - name: yaz-care-api - namespace: yaz-{environment} -spec: - replicas: {replicas} - selector: - matchLabels: - app: yaz-care-api - template: - metadata: - labels: - app: yaz-care-api - spec: - containers: - - name: yaz-care-api - image: yaz-care:latest - ports: - - containerPort: 8000 - env: - - name: YAZ_ENVIRONMENT - value: "{environment}" ---- -apiVersion: v1 -kind: Service -metadata: - name: yaz-care-service -spec: - selector: - app: yaz-care-api - ports: - - port: 80 - targetPort: 8000 -""" - - replica_counts = {"development": 1, "staging": 2, "production": 3} - - for env in environments: - k8s_file = infra_new / env / "k8s" / "deployment.yaml" - k8s_file.write_text(k8s_template.format( - environment=env, - replicas=replica_counts[env] - )) - - print("βœ… Consolidated Kubernetes manifests created") - - # Create monitoring configuration - monitoring_template = """# Prometheus configuration for {environment} -global: - scrape_interval: 15s - -scrape_configs: - - job_name: 'yaz-care-api' - static_configs: - - targets: ['yaz-api:8000'] - - - job_name: 'postgres' - static_configs: - - targets: ['postgres:5432'] -""" - - for env in environments: - monitoring_file = infra_new / env / "monitoring" / "prometheus.yml" - monitoring_file.write_text(monitoring_template.format(environment=env)) - - print("βœ… Consolidated monitoring configurations created") - - # Create maintenance script - maintenance_script = infra_new / "maintain.py" - maintenance_script.write_text('''#!/usr/bin/env python3 -""" -Infrastructure maintenance utilities -""" - -import subprocess -import sys - -def cleanup_old_configs(): - """Remove old scattered configuration files""" - old_paths = [ - "/workspaces/yaz/docker-compose.prod.yml", - "/workspaces/yaz/infra/deployment/", - "/workspaces/yaz/deployment/", - ] - - for path in old_paths: - try: - if Path(path).exists(): - if Path(path).is_dir(): - shutil.rmtree(path) - else: - Path(path).unlink() - print(f"βœ… Removed: {path}") - except Exception as e: - print(f"⚠️ Failed to remove {path}: {e}") - -if __name__ == "__main__": - cleanup_old_configs() -''') - maintenance_script.chmod(0o755) - - print("βœ… Infrastructure consolidation complete!") - print(f"πŸ“ New structure: {infra_new}") - print("πŸ”§ Run maintain.py to cleanup old configurations") - -if __name__ == "__main__": - consolidate_infrastructure() \ No newline at end of file diff --git a/infra/ops/ops_manager.py b/infra/ops/ops_manager.py deleted file mode 100644 index 39b1cef727f3959b148899cf753ed10d2259f56f..0000000000000000000000000000000000000000 --- a/infra/ops/ops_manager.py +++ /dev/null @@ -1,354 +0,0 @@ -#!/usr/bin/env python3 -""" -YAZ Care Platform - Unified Operations Manager -Consolidates all deployment, migration, and maintenance operations -Replaces scattered scripts across scripts/, migration/, deployment/ directories -""" - -import os -import sys -import argparse -import subprocess -import logging -from pathlib import Path -from typing import Dict, List, Optional -import yaml - -# Setup paths -PROJECT_ROOT = Path(__file__).parent.parent.resolve() -SRC_PATH = PROJECT_ROOT / "src" -if str(SRC_PATH) not in sys.path: - sys.path.insert(0, str(SRC_PATH)) - -# Setup logging -logging.basicConfig( - level=logging.INFO, - format="%(asctime)s - YAZ Ops - %(levelname)s - %(message)s" -) -logger = logging.getLogger("yaz_ops") - -class YazOperationsManager: - """Unified operations management for YAZ Care Platform""" - - def __init__(self): - self.project_root = PROJECT_ROOT - self.config_file = self.project_root / "config.yml" - self.config = self._load_config() - - def _load_config(self) -> Dict: - """Load consolidated configuration""" - try: - with open(self.config_file, 'r') as f: - return yaml.safe_load(f) - except FileNotFoundError: - logger.warning("Consolidated config not found, using defaults") - return {} - - def deploy(self, environment: str, target: str = "local") -> bool: - """Deploy YAZ Care Platform to specified environment and target""" - logger.info(f"πŸš€ Deploying to {environment} environment ({target} target)") - - try: - # Validate environment - if environment not in ["development", "staging", "production"]: - raise ValueError(f"Invalid environment: {environment}") - - # Select deployment method based on target - if target == "local": - return self._deploy_local(environment) - elif target == "docker": - return self._deploy_docker(environment) - elif target == "kubernetes": - return self._deploy_kubernetes(environment) - else: - raise ValueError(f"Invalid target: {target}") - - except Exception as e: - logger.error(f"❌ Deployment failed: {e}") - return False - - def _deploy_local(self, environment: str) -> bool: - """Deploy locally using Python server""" - logger.info("πŸ–₯️ Starting local deployment") - - # Install dependencies - subprocess.run([ - sys.executable, "-m", "pip", "install", "-r", "requirements.txt" - ], cwd=self.project_root) - - # Set environment variables - env = os.environ.copy() - env["YAZ_ENVIRONMENT"] = environment - - # Start server - cmd = [sys.executable, "main.py", "serve", "--debug"] if environment == "development" else [sys.executable, "main.py", "serve"] - - subprocess.Popen(cmd, cwd=self.project_root, env=env) - logger.info("βœ… Local deployment started") - return True - - def _deploy_docker(self, environment: str) -> bool: - """Deploy using Docker Compose""" - logger.info("🐳 Starting Docker deployment") - - compose_file = self.project_root / "docker-compose.unified.yml" - if not compose_file.exists(): - logger.error("❌ Unified Docker Compose file not found") - return False - - # Set environment profile - profile_map = { - "development": "development", - "staging": "staging", - "production": "production" - } - - profile = profile_map.get(environment, "development") - - try: - # Start services with appropriate profile - subprocess.run([ - "docker-compose", "-f", str(compose_file), - "--profile", profile, "up", "-d" - ], cwd=self.project_root, check=True) - - logger.info("βœ… Docker deployment completed") - return True - - except subprocess.CalledProcessError as e: - logger.error(f"❌ Docker deployment failed: {e}") - return False - - def _deploy_kubernetes(self, environment: str) -> bool: - """Deploy to Kubernetes cluster""" - logger.info("☸️ Starting Kubernetes deployment") - - # Apply Kubernetes manifests - k8s_dir = self.project_root / "infra" / "k8s" - if not k8s_dir.exists(): - logger.error("❌ Kubernetes manifests not found") - return False - - try: - # Apply all manifests - subprocess.run([ - "kubectl", "apply", "-f", str(k8s_dir) - ], check=True) - - logger.info("βœ… Kubernetes deployment completed") - return True - - except subprocess.CalledProcessError as e: - logger.error(f"❌ Kubernetes deployment failed: {e}") - return False - - def migrate_database(self, direction: str = "up") -> bool: - """Run database migrations""" - logger.info(f"πŸ—ƒοΈ Running database migrations ({direction})") - - try: - if direction == "up": - # Run migrations forward - from core.db.migrations import migration_manager - import asyncio - - async def run(): - result = await migration_manager.run_migrations() - return result["status"] == "success" - - return asyncio.run(run()) - - elif direction == "down": - # Rollback last migration - from core.db.migrations import migration_manager - import asyncio - - async def rollback(): - result = await migration_manager.rollback_last_migration() - return result["status"] == "success" - - return asyncio.run(rollback()) - - except ImportError: - logger.warning("⚠️ Migration system not available") - return True - except Exception as e: - logger.error(f"❌ Migration failed: {e}") - return False - - def health_check(self) -> bool: - """Comprehensive system health check""" - logger.info("πŸ” Running system health check") - - checks_passed = 0 - total_checks = 0 - - # Check Python environment - total_checks += 1 - if sys.version_info >= (3, 8): - logger.info("βœ… Python version: OK") - checks_passed += 1 - else: - logger.error("❌ Python version: Too old") - - # Check required files - total_checks += 1 - required_files = ["main.py", "requirements.txt", "src/factory.py"] - missing_files = [f for f in required_files if not (self.project_root / f).exists()] - - if not missing_files: - logger.info("βœ… Required files: OK") - checks_passed += 1 - else: - logger.error(f"❌ Missing files: {missing_files}") - - # Check database - total_checks += 1 - try: - from services.health import HealthService - health_service = HealthService() - if health_service.check_database(): - logger.info("βœ… Database: Connected") - checks_passed += 1 - else: - logger.error("❌ Database: Connection failed") - except ImportError: - logger.warning("⚠️ Health service not available") - checks_passed += 1 # Don't fail on import issues - - # Summary - success_rate = (checks_passed / total_checks) * 100 - logger.info(f"πŸ“Š Health check: {checks_passed}/{total_checks} passed ({success_rate:.1f}%)") - - return success_rate >= 80 - - def cleanup(self) -> bool: - """Clean up temporary files and optimize codebase""" - logger.info("🧹 Starting cleanup operations") - - try: - # Remove Python cache files - subprocess.run([ - "find", str(self.project_root), - "-name", "__pycache__", "-type", "d", "-exec", "rm", "-rf", "{}", "+" - ]) - - # Remove .pyc files - subprocess.run([ - "find", str(self.project_root), - "-name", "*.pyc", "-delete" - ]) - - # Clean logs (keep last 10 files) - logs_dir = self.project_root / "logs" - if logs_dir.exists(): - log_files = sorted(logs_dir.glob("*.log"), key=lambda x: x.stat().st_mtime, reverse=True) - for log_file in log_files[10:]: # Keep last 10, remove rest - log_file.unlink() - - logger.info("βœ… Cleanup completed") - return True - - except Exception as e: - logger.error(f"❌ Cleanup failed: {e}") - return False - - def backup(self, target: Optional[str] = None) -> bool: - """Create system backup""" - logger.info("πŸ’Ύ Creating system backup") - - import datetime - - backup_name = f"yaz_backup_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}" - backup_dir = self.project_root / "data" / "backups" / backup_name - backup_dir.mkdir(parents=True, exist_ok=True) - - try: - # Backup database - db_file = self.project_root / "yaz_care.db" - if db_file.exists(): - import shutil - shutil.copy2(db_file, backup_dir / "yaz_care.db") - - # Backup configuration - config_files = ["config.yml", ".env"] - for config_file in config_files: - source = self.project_root / config_file - if source.exists(): - shutil.copy2(source, backup_dir / config_file) - - # Backup data directory - data_dir = self.project_root / "data" - if data_dir.exists(): - shutil.copytree( - data_dir, backup_dir / "data", - ignore=shutil.ignore_patterns('backups', '__pycache__') - ) - - logger.info(f"βœ… Backup created: {backup_dir}") - return True - - except Exception as e: - logger.error(f"❌ Backup failed: {e}") - return False - - -def main(): - """Main CLI entry point""" - parser = argparse.ArgumentParser( - description="YAZ Care Platform - Unified Operations Manager", - formatter_class=argparse.RawDescriptionHelpFormatter, - epilog=""" -Examples: - python ops_manager.py deploy development local # Deploy locally for development - python ops_manager.py deploy production docker # Deploy to production with Docker - python ops_manager.py migrate up # Run database migrations - python ops_manager.py health # Check system health - python ops_manager.py cleanup # Clean temporary files - python ops_manager.py backup # Create system backup - """ - ) - - subparsers = parser.add_subparsers(dest="command", help="Available commands") - - # Deploy command - deploy_parser = subparsers.add_parser("deploy", help="Deploy application") - deploy_parser.add_argument("environment", choices=["development", "staging", "production"]) - deploy_parser.add_argument("target", choices=["local", "docker", "kubernetes"], default="local", nargs="?") - - # Migrate command - migrate_parser = subparsers.add_parser("migrate", help="Database migrations") - migrate_parser.add_argument("direction", choices=["up", "down"], default="up", nargs="?") - - # Simple commands - subparsers.add_parser("health", help="System health check") - subparsers.add_parser("cleanup", help="Clean temporary files") - subparsers.add_parser("backup", help="Create system backup") - - args = parser.parse_args() - - if not args.command: - parser.print_help() - return - - ops_manager = YazOperationsManager() - - # Execute commands - success = False - - if args.command == "deploy": - success = ops_manager.deploy(args.environment, args.target) - elif args.command == "migrate": - success = ops_manager.migrate_database(args.direction) - elif args.command == "health": - success = ops_manager.health_check() - elif args.command == "cleanup": - success = ops_manager.cleanup() - elif args.command == "backup": - success = ops_manager.backup() - - sys.exit(0 if success else 1) - - -if __name__ == "__main__": - main() \ No newline at end of file diff --git a/infra/ops/verify_canonical_model.py b/infra/ops/verify_canonical_model.py deleted file mode 100755 index 76b266f68e1dafefef69d2ceffef24cd9e4bc881..0000000000000000000000000000000000000000 --- a/infra/ops/verify_canonical_model.py +++ /dev/null @@ -1,160 +0,0 @@ -#!/usr/bin/env python3 -""" -YAZ Care Platform - Canonical Data Model Verification -Test the implemented data model and services -""" - -import sys -import os -import asyncio -import logging -from pathlib import Path - -# Add project root to Python path -project_root = Path(__file__).parent.parent -sys.path.insert(0, str(project_root)) - -from core.db.manager import db_manager, init_database -from core.db.repository import RepositoryFactory -from core.services.business import ServiceFactory -from core.models.canonical import TenantStatus, UserRole - -logging.basicConfig(level=logging.INFO) -logger = logging.getLogger(__name__) - -async def verify_canonical_model(): - """Verify the canonical data model implementation""" - - logger.info("πŸ”„ Verifying Canonical Data Model...") - - try: - # 1. Test database connectivity - logger.info("1️⃣ Testing database connectivity...") - health = db_manager.health_check() - logger.info(f" Database status: {health.get('status', 'unknown')}") - - if health.get('connectivity'): - logger.info(" βœ… Database connectivity: OK") - else: - logger.error(" ❌ Database connectivity: FAILED") - return False - - # 2. Test repository pattern - logger.info("2️⃣ Testing repository pattern...") - repo_factory = RepositoryFactory() - - # Test tenant repository - tenant_repo = repo_factory.tenant_repo() - tenant_count = tenant_repo.count() - logger.info(f" Tenant count: {tenant_count}") - - # Test with tenant context - if tenant_count > 0: - # Find demo tenant - demo_tenant = tenant_repo.get_by_slug('yaz-demo') - if demo_tenant: - logger.info(f" βœ… Found demo tenant: {demo_tenant.name}") - - # Test user repository with tenant context - user_repo = repo_factory.user_repo().set_tenant(demo_tenant.tenant_id) - user_count = user_repo.count() - logger.info(f" Users in demo tenant: {user_count}") - - if user_count > 0: - logger.info(" βœ… Repository pattern: OK") - else: - logger.warning(" ⚠️ No users found in demo tenant") - else: - logger.warning(" ⚠️ Demo tenant not found") - else: - logger.warning(" ⚠️ No tenants found - run data initialization first") - - # 3. Test service layer - logger.info("3️⃣ Testing service layer...") - service_factory = ServiceFactory() - - if tenant_count > 0 and demo_tenant: - # Get a user for context - user_repo = repo_factory.user_repo().set_tenant(demo_tenant.tenant_id) - users = user_repo.list(limit=1) - - if users: - test_user = users[0] - logger.info(f" Using test user: {test_user.full_name}") - - # Test case service - case_service = service_factory.case_service().set_context( - demo_tenant.tenant_id, test_user.id - ) - - # Count existing cases - case_repo = repo_factory.case_repo().set_tenant(demo_tenant.tenant_id) - case_count = case_repo.count() - logger.info(f" Existing cases: {case_count}") - - logger.info(" βœ… Service layer: OK") - else: - logger.warning(" ⚠️ No users available for service testing") - - # 4. Test model relationships - logger.info("4️⃣ Testing model relationships...") - - if tenant_count > 0 and demo_tenant: - case_repo = repo_factory.case_repo().set_tenant(demo_tenant.tenant_id) - cases = case_repo.list(limit=1, relationships=['decisions', 'tasks', 'documents']) - - if cases: - test_case = cases[0] - logger.info(f" Test case: {test_case.case_number}") - logger.info(f" Decisions: {len(test_case.decisions)}") - logger.info(f" Tasks: {len(test_case.tasks)}") - logger.info(f" Documents: {len(test_case.documents)}") - logger.info(" βœ… Model relationships: OK") - else: - logger.warning(" ⚠️ No cases found for relationship testing") - - # 5. Test full-text search (if available) - logger.info("5️⃣ Testing search capabilities...") - - if tenant_count > 0 and demo_tenant: - case_repo = repo_factory.case_repo().set_tenant(demo_tenant.tenant_id) - try: - # Try searching for "surgery" or "cardiac" - search_results = case_repo.search("surgery", limit=5) - logger.info(f" Search results for 'surgery': {len(search_results)}") - - if search_results: - logger.info(" βœ… Full-text search: OK") - else: - logger.info(" ℹ️ Full-text search: No results (may be empty)") - except Exception as e: - logger.warning(f" ⚠️ Full-text search error: {e}") - - logger.info("βœ… Canonical Data Model verification completed successfully!") - return True - - except Exception as e: - logger.error(f"❌ Verification failed: {e}") - import traceback - traceback.print_exc() - return False - -async def main(): - """Main verification function""" - - print("=" * 60) - print("YAZ Care Platform - Canonical Data Model Verification") - print("=" * 60) - - success = await verify_canonical_model() - - print("=" * 60) - if success: - print("βœ… VERIFICATION PASSED") - sys.exit(0) - else: - print("❌ VERIFICATION FAILED") - sys.exit(1) - -if __name__ == "__main__": - asyncio.run(main()) \ No newline at end of file diff --git a/infra/ops/verify_decision_engine.py b/infra/ops/verify_decision_engine.py deleted file mode 100755 index 7f6f3bc8d4b8e000800a0a659a1a8d4999a0197a..0000000000000000000000000000000000000000 --- a/infra/ops/verify_decision_engine.py +++ /dev/null @@ -1,321 +0,0 @@ -#!/usr/bin/env python3 -""" -YAZ Care Platform - Decision Engine Verification -Test the TOPSIS decision engine implementation -""" - -import sys -import os -import asyncio -import logging -from pathlib import Path - -# Add project root to Python path -project_root = Path(__file__).parent.parent.parent -sys.path.insert(0, str(project_root)) - -from core.decision.topsis import ( - TOPSISEngine, DecisionCriteria, DecisionAlternative, - CriteriaType, WeightingMethod, run_topsis_analysis -) -from core.decision.service import DecisionSupportService -from core.db.manager import get_db_session -from core.db.repository import RepositoryFactory - -logging.basicConfig(level=logging.INFO) -logger = logging.getLogger(__name__) - -async def verify_topsis_engine(): - """Verify TOPSIS engine implementation""" - - logger.info("πŸ”„ Verifying TOPSIS Decision Engine...") - - try: - # 1. Test basic TOPSIS functionality - logger.info("1️⃣ Testing basic TOPSIS analysis...") - - # Define test criteria - criteria_data = [ - { - 'id': 'cost', - 'name': 'Cost', - 'type': 'cost', - 'weight': 0.3, - 'description': 'Total cost of treatment' - }, - { - 'id': 'effectiveness', - 'name': 'Effectiveness', - 'type': 'benefit', - 'weight': 0.4, - 'description': 'Treatment effectiveness' - }, - { - 'id': 'safety', - 'name': 'Safety', - 'type': 'benefit', - 'weight': 0.3, - 'description': 'Safety profile' - } - ] - - # Define test alternatives - alternatives_data = [ - { - 'id': 'option_a', - 'name': 'Treatment A', - 'description': 'Conservative treatment', - 'values': { - 'cost': 1000, - 'effectiveness': 0.7, - 'safety': 0.9 - } - }, - { - 'id': 'option_b', - 'name': 'Treatment B', - 'description': 'Moderate intervention', - 'values': { - 'cost': 5000, - 'effectiveness': 0.85, - 'safety': 0.8 - } - }, - { - 'id': 'option_c', - 'name': 'Treatment C', - 'description': 'Aggressive treatment', - 'values': { - 'cost': 10000, - 'effectiveness': 0.95, - 'safety': 0.7 - } - } - ] - - # Run TOPSIS analysis - results, explanation = run_topsis_analysis( - criteria_data, alternatives_data, WeightingMethod.EXPERT - ) - - logger.info(f" Analysis completed with {len(results)} alternatives ranked") - logger.info(f" Best option: {results[0].alternative_name} (score: {results[0].score:.3f})") - logger.info(" βœ… Basic TOPSIS functionality: OK") - - # 2. Test different weighting methods - logger.info("2️⃣ Testing weighting methods...") - - weighting_methods = [WeightingMethod.EQUAL, WeightingMethod.ENTROPY, WeightingMethod.CRITIC] - - for method in weighting_methods: - try: - results_method, _ = run_topsis_analysis( - criteria_data, alternatives_data, method - ) - logger.info(f" {method.value}: {results_method[0].alternative_name} (score: {results_method[0].score:.3f})") - except Exception as e: - logger.warning(f" {method.value}: Failed - {e}") - - logger.info(" βœ… Weighting methods: OK") - - # 3. Test decision service integration - logger.info("3️⃣ Testing decision service integration...") - - session = get_db_session() - repo_factory = RepositoryFactory(session) - - # Check if demo tenant exists - tenant_repo = repo_factory.tenant_repo() - demo_tenant = tenant_repo.get_by_slug('yaz-demo') - - if demo_tenant: - user_repo = repo_factory.user_repo().set_tenant(demo_tenant.tenant_id) - users = user_repo.list(limit=1) - - if users: - decision_service = DecisionSupportService(session) - decision_service.set_context(demo_tenant.tenant_id, users[0].id) - logger.info(" Decision service configured with tenant context") - logger.info(" βœ… Service integration: OK") - else: - logger.warning(" ⚠️ No users found for service testing") - else: - logger.warning(" ⚠️ Demo tenant not found - run 'make db-init' first") - - session.close() - - # 4. Test edge cases - logger.info("4️⃣ Testing edge cases...") - - # Test with equal values - equal_alternatives = [ - { - 'id': 'equal_a', - 'name': 'Equal A', - 'values': {'cost': 100, 'effectiveness': 0.5, 'safety': 0.5} - }, - { - 'id': 'equal_b', - 'name': 'Equal B', - 'values': {'cost': 100, 'effectiveness': 0.5, 'safety': 0.5} - } - ] - - try: - equal_results, _ = run_topsis_analysis( - criteria_data, equal_alternatives, WeightingMethod.EXPERT - ) - logger.info(f" Equal values test: {len(equal_results)} results") - logger.info(" βœ… Edge cases: OK") - except Exception as e: - logger.warning(f" ⚠️ Edge case failed: {e}") - - # 5. Test explanation quality - logger.info("5️⃣ Testing explanation quality...") - - explanation_keys = [ - 'analysis_summary', 'criteria_analysis', 'ideal_solutions', - 'ranking_explanation', 'sensitivity_analysis', 'recommendations' - ] - - missing_keys = [key for key in explanation_keys if key not in explanation] - - if not missing_keys: - logger.info(" All explanation components present") - logger.info(f" Generated {len(explanation['recommendations'])} recommendations") - logger.info(" βœ… Explanation quality: OK") - else: - logger.warning(f" ⚠️ Missing explanation keys: {missing_keys}") - - # 6. Test mathematical correctness - logger.info("6️⃣ Testing mathematical correctness...") - - # Verify scores are between 0 and 1 - scores_valid = all(0 <= result.score <= 1 for result in results) - - # Verify ranking consistency - ranking_valid = all( - results[i].score >= results[i+1].score - for i in range(len(results)-1) - ) - - if scores_valid and ranking_valid: - logger.info(" Score ranges and ranking order correct") - logger.info(" βœ… Mathematical correctness: OK") - else: - logger.warning(" ⚠️ Mathematical validation failed") - - logger.info("βœ… TOPSIS Decision Engine verification completed successfully!") - return True - - except Exception as e: - logger.error(f"❌ Verification failed: {e}") - import traceback - traceback.print_exc() - return False - -async def demo_clinical_decision(): - """Demonstrate clinical decision making""" - - logger.info("\n" + "="*60) - logger.info("CLINICAL DECISION DEMO") - logger.info("="*60) - - # Sample cardiac treatment decision - treatments = [ - { - 'id': 'medication', - 'name': 'Medical Management', - 'values': { - 'success_rate': 0.75, - 'safety_score': 0.95, - 'cost': 5000, - 'recovery_days': 7 - } - }, - { - 'id': 'stenting', - 'name': 'Coronary Stenting', - 'values': { - 'success_rate': 0.90, - 'safety_score': 0.85, - 'cost': 25000, - 'recovery_days': 3 - } - }, - { - 'id': 'surgery', - 'name': 'Bypass Surgery', - 'values': { - 'success_rate': 0.95, - 'safety_score': 0.80, - 'cost': 50000, - 'recovery_days': 21 - } - } - ] - - criteria = [ - { - 'id': 'success_rate', - 'name': 'Success Rate', - 'type': 'benefit', - 'weight': 0.4 - }, - { - 'id': 'safety_score', - 'name': 'Safety Score', - 'type': 'benefit', - 'weight': 0.3 - }, - { - 'id': 'cost', - 'name': 'Treatment Cost', - 'type': 'cost', - 'weight': 0.2 - }, - { - 'id': 'recovery_days', - 'name': 'Recovery Time', - 'type': 'cost', - 'weight': 0.1 - } - ] - - results, explanation = run_topsis_analysis(criteria, treatments, WeightingMethod.EXPERT) - - logger.info("πŸ“Š Clinical Decision Results:") - for i, result in enumerate(results, 1): - logger.info(f" {i}. {result.alternative_name}: {result.score:.3f} ({result.score*100:.1f}%)") - - logger.info(f"\n🎯 Recommendation: {results[0].alternative_name}") - logger.info(f" Confidence: {results[0].score:.1%}") - - # Show key insights - if explanation['recommendations']: - logger.info(f"\nπŸ’‘ Key Insights:") - for rec in explanation['recommendations']: - logger.info(f" β€’ {rec}") - -async def main(): - """Main verification function""" - - print("=" * 60) - print("YAZ Care Platform - TOPSIS Decision Engine Verification") - print("=" * 60) - - success = await verify_topsis_engine() - - if success: - await demo_clinical_decision() - - print("=" * 60) - if success: - print("βœ… VERIFICATION PASSED") - sys.exit(0) - else: - print("❌ VERIFICATION FAILED") - sys.exit(1) - -if __name__ == "__main__": - asyncio.run(main()) \ No newline at end of file diff --git a/infra/ops/verify_env.py b/infra/ops/verify_env.py deleted file mode 100644 index 04b2ad936b4df06a3c015be3a8d5aa555d6176f9..0000000000000000000000000000000000000000 --- a/infra/ops/verify_env.py +++ /dev/null @@ -1,186 +0,0 @@ -#!/usr/bin/env python3 -""" -YAZ Care Platform - Environment Verification -Checks: docker, compose, python, node, openssl requirements -""" - -import sys -import subprocess -import shutil -from pathlib import Path -from typing import Dict, List, Tuple -import json - -def run_command(cmd: List[str]) -> Tuple[bool, str]: - """Run command and return success status and output""" - try: - result = subprocess.run( - cmd, - capture_output=True, - text=True, - timeout=30 - ) - return result.returncode == 0, result.stdout.strip() - except (subprocess.TimeoutExpired, FileNotFoundError) as e: - return False, str(e) - -def check_binary(name: str, cmd: List[str], min_version: str = None) -> Dict: - """Check if binary exists and optionally verify version""" - if not shutil.which(name): - return {"status": "missing", "message": f"{name} not found in PATH"} - - success, output = run_command(cmd) - if not success: - return {"status": "error", "message": f"Failed to run {name}: {output}"} - - return {"status": "ok", "version": output, "message": f"{name} available"} - -def verify_docker() -> Dict: - """Verify Docker installation and daemon""" - result = check_binary("docker", ["docker", "--version"]) - if result["status"] != "ok": - return result - - # Check if Docker daemon is running - success, output = run_command(["docker", "info"]) - if not success: - return {"status": "error", "message": "Docker daemon not running"} - - return {"status": "ok", "message": "Docker available and running"} - -def verify_compose() -> Dict: - """Verify Docker Compose availability""" - # Try docker compose (new) first - success, output = run_command(["docker", "compose", "version"]) - if success: - return {"status": "ok", "version": output, "message": "Docker Compose (new) available"} - - # Fallback to docker-compose (legacy) - return check_binary("docker-compose", ["docker-compose", "--version"]) - -def verify_python() -> Dict: - """Verify Python version and pip""" - result = check_binary("python3", ["python3", "--version"]) - if result["status"] != "ok": - return result - - # Check pip - pip_result = check_binary("pip", ["pip", "--version"]) - if pip_result["status"] != "ok": - pip_result = check_binary("pip3", ["pip3", "--version"]) - - return { - "status": "ok" if pip_result["status"] == "ok" else "warning", - "python_version": result["version"], - "pip_status": pip_result["status"], - "message": f"Python available, pip {pip_result['status']}" - } - -def verify_node() -> Dict: - """Verify Node.js (optional for UI builds)""" - result = check_binary("node", ["node", "--version"]) - if result["status"] == "missing": - return {"status": "optional", "message": "Node.js not found (optional for UI builds)"} - return result - -def verify_openssl() -> Dict: - """Verify OpenSSL for certificate generation""" - return check_binary("openssl", ["openssl", "version"]) - -def verify_system_resources() -> Dict: - """Check system resources""" - try: - import psutil - - # Memory (minimum 4GB recommended) - memory = psutil.virtual_memory() - memory_gb = memory.total / (1024**3) - - # Disk space (minimum 10GB free) - disk = psutil.disk_usage('/') - disk_free_gb = disk.free / (1024**3) - - status = "ok" - warnings = [] - - if memory_gb < 4: - warnings.append(f"Low memory: {memory_gb:.1f}GB (recommended: 4GB+)") - status = "warning" - - if disk_free_gb < 10: - warnings.append(f"Low disk space: {disk_free_gb:.1f}GB (recommended: 10GB+)") - status = "warning" - - return { - "status": status, - "memory_gb": f"{memory_gb:.1f}", - "disk_free_gb": f"{disk_free_gb:.1f}", - "warnings": warnings, - "message": f"Memory: {memory_gb:.1f}GB, Disk: {disk_free_gb:.1f}GB free" - } - except ImportError: - return {"status": "warning", "message": "psutil not available for resource check"} - -def main(): - """Run all environment verifications""" - print("πŸ” YAZ Care Platform - Environment Verification") - print("=" * 50) - - checks = [ - ("Docker", verify_docker), - ("Docker Compose", verify_compose), - ("Python", verify_python), - ("Node.js", verify_node), - ("OpenSSL", verify_openssl), - ("System Resources", verify_system_resources) - ] - - results = {} - all_passed = True - - for name, check_func in checks: - print(f"Checking {name}...", end=" ") - result = check_func() - results[name] = result - - if result["status"] == "ok": - print("βœ…") - elif result["status"] == "warning": - print("⚠️ ", result["message"]) - elif result["status"] == "optional": - print("βž–", result["message"]) - else: - print("❌", result["message"]) - all_passed = False - - print("\n" + "=" * 50) - - if all_passed: - print("βœ… Environment verification PASSED") - print("πŸš€ Ready to proceed with deployment") - else: - print("❌ Environment verification FAILED") - print("πŸ›‘ Fix issues before proceeding") - - # Show specific failures - for name, result in results.items(): - if result["status"] not in ["ok", "warning", "optional"]: - print(f" - {name}: {result['message']}") - - # Save detailed results - results_file = Path("logs/verification_env.json") - results_file.parent.mkdir(exist_ok=True) - - with open(results_file, "w") as f: - json.dump({ - "timestamp": subprocess.run(["date", "-Iseconds"], capture_output=True, text=True).stdout.strip(), - "status": "passed" if all_passed else "failed", - "results": results - }, f, indent=2) - - print(f"πŸ“ Detailed results saved to {results_file}") - - return 0 if all_passed else 1 - -if __name__ == "__main__": - sys.exit(main()) \ No newline at end of file diff --git a/infra/ops/verify_ports.py b/infra/ops/verify_ports.py deleted file mode 100644 index f19765c75a8ac8ceb770839b61d2af6397b0b8fb..0000000000000000000000000000000000000000 --- a/infra/ops/verify_ports.py +++ /dev/null @@ -1,192 +0,0 @@ -#!/usr/bin/env python3 -""" -YAZ Care Platform - Port Verification -Checks ports 80/443/5432/6379 availability and shows processes using them -""" - -import sys -import socket -import subprocess -from typing import Dict, List, Optional -import json -from pathlib import Path - -REQUIRED_PORTS = { - 80: "HTTP (Nginx)", - 443: "HTTPS (Nginx)", - 5432: "PostgreSQL", - 6379: "Redis/Valkey", - 8000: "YAZ Platform API", - 8080: "Admin Panel", - 3000: "Grafana", - 9090: "Prometheus" -} - -def is_port_in_use(host: str, port: int) -> bool: - """Check if port is in use""" - try: - with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: - sock.settimeout(1) - result = sock.connect_ex((host, port)) - return result == 0 - except Exception: - return False - -def get_process_using_port(port: int) -> Optional[Dict]: - """Get process information for port using lsof or netstat""" - try: - # Try lsof first (more detailed) - result = subprocess.run( - ["lsof", "-i", f":{port}", "-n", "-P"], - capture_output=True, - text=True, - timeout=5 - ) - - if result.returncode == 0 and result.stdout.strip(): - lines = result.stdout.strip().split('\n') - if len(lines) > 1: # Skip header - parts = lines[1].split() - if len(parts) >= 2: - return { - "command": parts[0], - "pid": parts[1], - "user": parts[2] if len(parts) > 2 else "unknown", - "method": "lsof" - } - except (subprocess.TimeoutExpired, FileNotFoundError): - pass - - try: - # Fallback to netstat - result = subprocess.run( - ["netstat", "-tulpn", "2>/dev/null"], - shell=True, - capture_output=True, - text=True, - timeout=5 - ) - - if result.returncode == 0: - for line in result.stdout.split('\n'): - if f":{port} " in line and "LISTEN" in line: - parts = line.split() - if len(parts) >= 7: - pid_program = parts[6] - if "/" in pid_program: - pid, program = pid_program.split("/", 1) - return { - "command": program, - "pid": pid, - "user": "unknown", - "method": "netstat" - } - except (subprocess.TimeoutExpired, FileNotFoundError): - pass - - return None - -def check_port(port: int, description: str) -> Dict: - """Check single port status""" - in_use = is_port_in_use("127.0.0.1", port) - - result = { - "port": port, - "description": description, - "in_use": in_use, - "status": "busy" if in_use else "free" - } - - if in_use: - process_info = get_process_using_port(port) - if process_info: - result["process"] = process_info - result["message"] = f"Port {port} is in use" - else: - result["message"] = f"Port {port} is available" - - return result - -def suggest_alternatives(busy_ports: List[int]) -> Dict[int, int]: - """Suggest alternative ports for busy ones""" - alternatives = {} - - for port in busy_ports: - # Find next available port - for alt_port in range(port + 1, port + 100): - if not is_port_in_use("127.0.0.1", alt_port): - alternatives[port] = alt_port - break - - return alternatives - -def main(): - """Run port verification""" - print("πŸ” YAZ Care Platform - Port Verification") - print("=" * 50) - - results = {} - busy_ports = [] - - for port, description in REQUIRED_PORTS.items(): - print(f"Checking port {port} ({description})...", end=" ") - result = check_port(port, description) - results[str(port)] = result - - if result["in_use"]: - print("❌ BUSY") - busy_ports.append(port) - - # Show process info - if "process" in result: - proc = result["process"] - print(f" Process: {proc['command']} (PID: {proc['pid']}, User: {proc['user']})") - else: - print("βœ… FREE") - - print("\n" + "=" * 50) - - if busy_ports: - print(f"❌ {len(busy_ports)} ports are busy: {', '.join(map(str, busy_ports))}") - print("\nπŸ”§ Suggested actions:") - - # Show process termination commands - for port_str, result in results.items(): - if result["in_use"] and "process" in result: - pid = result["process"]["pid"] - cmd = result["process"]["command"] - print(f" Port {port_str}: kill {pid} # Terminate {cmd}") - - # Show alternative ports - alternatives = suggest_alternatives(busy_ports) - if alternatives: - print("\nπŸ”„ Alternative ports:") - for original, alternative in alternatives.items(): - print(f" {original} β†’ {alternative}") - - print("\nπŸ›‘ PREFLIGHT FAILED - Fix port conflicts before proceeding") - exit_code = 1 - else: - print("βœ… All required ports are available") - print("πŸš€ Ready to proceed with deployment") - exit_code = 0 - - # Save results - results_file = Path("logs/verification_ports.json") - results_file.parent.mkdir(exist_ok=True) - - with open(results_file, "w") as f: - json.dump({ - "timestamp": subprocess.run(["date", "-Iseconds"], capture_output=True, text=True).stdout.strip(), - "status": "passed" if not busy_ports else "failed", - "busy_ports": busy_ports, - "results": results, - "alternatives": suggest_alternatives(busy_ports) if busy_ports else {} - }, f, indent=2) - - print(f"πŸ“ Detailed results saved to {results_file}") - - return exit_code - -if __name__ == "__main__": - sys.exit(main()) \ No newline at end of file diff --git a/infra/ops/verify_secrets.py b/infra/ops/verify_secrets.py deleted file mode 100644 index 5de1c36f81831f47036138149416d0dad7048358..0000000000000000000000000000000000000000 --- a/infra/ops/verify_secrets.py +++ /dev/null @@ -1,288 +0,0 @@ -#!/usr/bin/env python3 -""" -YAZ Care Platform - Secrets Verification -Checks .env files exist and validates required secrets are present and non-default -""" - -import sys -import os -from pathlib import Path -from typing import Dict, List, Set -import json -import re - -# Required environment variables for production -REQUIRED_SECRETS = { - "SECRET_KEY": { - "description": "Main application secret key", - "default_patterns": ["your-secret-key", "secret", "changeme", "default"], - "min_length": 32 - }, - "JWT_SECRET_KEY": { - "description": "JWT signing key", - "default_patterns": ["your-jwt-secret", "jwt-secret", "changeme"], - "min_length": 32 - }, - "DATABASE_URL": { - "description": "PostgreSQL connection string", - "default_patterns": ["postgresql://user:pass@localhost", "postgres://"], - "min_length": 20 - }, - "REDIS_URL": { - "description": "Redis/Valkey connection string", - "default_patterns": ["redis://localhost", "redis://127.0.0.1"], - "min_length": 10 - }, - "ENCRYPTION_KEY": { - "description": "Data encryption key (Fernet)", - "default_patterns": ["your-encryption-key", "encrypt-key"], - "min_length": 44 # Fernet key length - }, - "TOTP_SECRET": { - "description": "TOTP 2FA secret", - "default_patterns": ["totp-secret", "2fa-secret"], - "min_length": 16 - } -} - -# Optional but recommended secrets -OPTIONAL_SECRETS = { - "SENTRY_DSN": "Error tracking", - "SMTP_PASSWORD": "Email notifications", - "OPENAI_API_KEY": "AI features", - "WEBHOOK_SECRET": "Webhook validation" -} - -def load_env_file(file_path: Path) -> Dict[str, str]: - """Load environment variables from .env file""" - if not file_path.exists(): - return {} - - env_vars = {} - try: - with open(file_path, 'r') as f: - for line in f: - line = line.strip() - if line and not line.startswith('#') and '=' in line: - key, value = line.split('=', 1) - env_vars[key.strip()] = value.strip().strip('"\'') - except Exception as e: - print(f"Warning: Failed to parse {file_path}: {e}") - - return env_vars - -def check_secret_strength(key: str, value: str, config: Dict) -> Dict: - """Check if secret meets security requirements""" - result = { - "key": key, - "present": bool(value), - "status": "ok", - "issues": [] - } - - if not value: - result["status"] = "missing" - result["issues"].append("Secret is missing") - return result - - # Check length - if len(value) < config.get("min_length", 16): - result["status"] = "weak" - result["issues"].append(f"Too short (min: {config['min_length']})") - - # Check for default values - default_patterns = config.get("default_patterns", []) - for pattern in default_patterns: - if pattern.lower() in value.lower(): - result["status"] = "insecure" - result["issues"].append(f"Contains default pattern: {pattern}") - - # Check complexity for certain keys - if "SECRET_KEY" in key or "JWT" in key: - if not re.search(r'[A-Z]', value): - result["issues"].append("Missing uppercase letters") - if not re.search(r'[a-z]', value): - result["issues"].append("Missing lowercase letters") - if not re.search(r'[0-9]', value): - result["issues"].append("Missing numbers") - if not re.search(r'[^A-Za-z0-9]', value): - result["issues"].append("Missing special characters") - - if result["issues"] and result["status"] == "ok": - result["status"] = "warning" - - return result - -def verify_env_file(env_file: Path, env_name: str) -> Dict: - """Verify single environment file""" - if not env_file.exists(): - return { - "env": env_name, - "file": str(env_file), - "exists": False, - "status": "missing", - "message": f"Environment file {env_file} not found" - } - - env_vars = load_env_file(env_file) - secrets_check = {} - issues = [] - - # Check required secrets - for key, config in REQUIRED_SECRETS.items(): - value = env_vars.get(key, "") - check_result = check_secret_strength(key, value, config) - secrets_check[key] = check_result - - if check_result["status"] in ["missing", "insecure"]: - issues.append(f"{key}: {', '.join(check_result['issues'])}") - - # Overall status - if any(s["status"] == "missing" for s in secrets_check.values()): - status = "missing" - elif any(s["status"] == "insecure" for s in secrets_check.values()): - status = "insecure" - elif any(s["status"] == "weak" for s in secrets_check.values()): - status = "weak" - else: - status = "ok" - - return { - "env": env_name, - "file": str(env_file), - "exists": True, - "status": status, - "secrets": secrets_check, - "issues": issues, - "total_vars": len(env_vars), - "required_present": sum(1 for s in secrets_check.values() if s["present"]) - } - -def generate_secure_defaults() -> str: - """Generate secure default values for missing secrets""" - import secrets - import string - - defaults = [] - - for key, config in REQUIRED_SECRETS.items(): - if key == "ENCRYPTION_KEY": - # Generate Fernet key - from cryptography.fernet import Fernet - try: - secure_key = Fernet.generate_key().decode() - defaults.append(f'{key}="{secure_key}"') - except ImportError: - # Fallback if cryptography not available - secure_key = secrets.token_urlsafe(32) - defaults.append(f'{key}="{secure_key}"') - elif key in ["SECRET_KEY", "JWT_SECRET_KEY", "TOTP_SECRET"]: - # Generate random string - alphabet = string.ascii_letters + string.digits + "!@#$%^&*" - secure_key = ''.join(secrets.choice(alphabet) for _ in range(config["min_length"])) - defaults.append(f'{key}="{secure_key}"') - elif key == "DATABASE_URL": - defaults.append(f'{key}="postgresql://yazcare_user:CHANGE_DB_PASSWORD@localhost:5432/yaz_platform"') - elif key == "REDIS_URL": - defaults.append(f'{key}="redis://localhost:6379/0"') - - return "\n".join(defaults) - -def main(): - """Run secrets verification""" - print("πŸ” YAZ Care Platform - Secrets Verification") - print("=" * 50) - - # Define environment files to check - env_files = [ - (Path(".env"), "development"), - (Path(".env.local"), "local"), - (Path(".env.production"), "production"), - (Path(".env.staging"), "staging") - ] - - results = {} - all_secure = True - - for env_file, env_name in env_files: - print(f"Checking {env_name} environment ({env_file})...", end=" ") - - result = verify_env_file(env_file, env_name) - results[env_name] = result - - if not result["exists"]: - print("βž– NOT FOUND") - elif result["status"] == "ok": - print("βœ… SECURE") - elif result["status"] == "weak": - print("⚠️ WEAK") - all_secure = False - elif result["status"] == "insecure": - print("❌ INSECURE") - all_secure = False - else: - print("❌ MISSING SECRETS") - all_secure = False - - # Show issues - if result.get("issues"): - for issue in result["issues"][:3]: # Show first 3 issues - print(f" - {issue}") - if len(result["issues"]) > 3: - print(f" - ... and {len(result['issues']) - 3} more issues") - - print("\n" + "=" * 50) - - if all_secure: - print("βœ… Secrets verification PASSED") - print("πŸ”’ All secrets are properly configured") - else: - print("❌ Secrets verification FAILED") - print("πŸ›‘ Fix security issues before production deployment") - - # Generate secure defaults - print("\nπŸ”§ Generating secure defaults:") - secure_defaults = generate_secure_defaults() - - defaults_file = Path("secrets.env.example") - with open(defaults_file, "w") as f: - f.write("# Generated secure defaults - CUSTOMIZE BEFORE USE\n") - f.write("# DO NOT COMMIT THIS FILE TO GIT\n\n") - f.write(secure_defaults) - - print(f"πŸ“ Secure defaults written to {defaults_file}") - print("⚠️ CUSTOMIZE these values before using in production!") - - # Save results - results_file = Path("logs/verification_secrets.json") - results_file.parent.mkdir(exist_ok=True) - - with open(results_file, "w") as f: - # Remove actual secret values from logs - safe_results = {} - for env_name, result in results.items(): - safe_result = result.copy() - if "secrets" in safe_result: - safe_secrets = {} - for key, secret_info in safe_result["secrets"].items(): - safe_secrets[key] = { - "present": secret_info["present"], - "status": secret_info["status"], - "issues": secret_info["issues"] - } - safe_result["secrets"] = safe_secrets - safe_results[env_name] = safe_result - - json.dump({ - "timestamp": subprocess.run(["date", "-Iseconds"], capture_output=True, text=True).stdout.strip(), - "status": "passed" if all_secure else "failed", - "results": safe_results - }, f, indent=2) - - print(f"πŸ“ Detailed results saved to {results_file}") - - return 0 if all_secure else 1 - -if __name__ == "__main__": - import subprocess - sys.exit(main()) \ No newline at end of file diff --git a/infra/security/README.md b/infra/security/README.md deleted file mode 100644 index 02f576090cb1a53b22441a459dcb0bea88e7a3ef..0000000000000000000000000000000000000000 --- a/infra/security/README.md +++ /dev/null @@ -1,254 +0,0 @@ -# Security Infrastructure - -**Purpose**: Security configurations, secrets management, encryption, and compliance enforcement. - ---- - -## πŸ“ Structure - -``` -security/ -β”œβ”€β”€ secrets/ # Secrets management -β”‚ β”œβ”€β”€ vault-config.hcl # HashiCorp Vault -β”‚ └── sealed-secrets.yaml # Kubernetes sealed secrets -β”œβ”€β”€ tls/ # TLS certificates -β”‚ β”œβ”€β”€ certs/ # Certificate files -β”‚ └── ca/ # Certificate authority -β”œβ”€β”€ firewall/ # Firewall rules -β”‚ β”œβ”€β”€ iptables.rules # iptables configuration -β”‚ └── ufw.conf # UFW configuration -└── policies/ # Security policies - β”œβ”€β”€ password-policy.yaml - └── audit-policy.yaml -``` - ---- - -## πŸš€ Usage - -### 1. Secrets Management (Vault) - -```bash -# Start Vault -docker-compose up vault - -# Initialize -vault operator init -key-shares=5 -key-threshold=3 - -# Unseal -vault operator unseal -vault operator unseal -vault operator unseal - -# Store secret -vault kv put secret/yaz/db password="" - -# Retrieve secret -vault kv get secret/yaz/db -``` - -### 2. TLS Certificate Management - -```bash -# Generate self-signed cert (development) -openssl req -x509 -nodes -days 365 -newkey rsa:4096 \ - -keyout tls/certs/yaz-care.key \ - -out tls/certs/yaz-care.crt \ - -subj "/CN=localhost" - -# Production with Let's Encrypt -certbot certonly --nginx -d api.yaz-care.com - -# Auto-renewal -0 0 * * * certbot renew --quiet -``` - -### 3. Encryption at Rest - -```python -# src/core/security/encryption.py -from cryptography.fernet import Fernet - -class EncryptionService: - def __init__(self, key: bytes): - self.cipher = Fernet(key) - - def encrypt_phi(self, data: str, tenant_id: UUID) -> str: - """Encrypt PHI with tenant-specific key""" - tenant_key = self._get_tenant_key(tenant_id) - return self.cipher.encrypt(data.encode()).decode() - - def decrypt_phi(self, encrypted: str, tenant_id: UUID) -> str: - """Decrypt PHI""" - tenant_key = self._get_tenant_key(tenant_id) - return self.cipher.decrypt(encrypted.encode()).decode() -``` - ---- - -## πŸ” Security Standards - -### Password Policy - -```yaml -# policies/password-policy.yaml -password_requirements: - min_length: 12 - require_uppercase: true - require_lowercase: true - require_digits: true - require_special_chars: true - max_age_days: 90 - history_count: 5 # Can't reuse last 5 passwords - lockout_attempts: 5 - lockout_duration_minutes: 30 -``` - -### Audit Policy (HIPAA Compliance) - -```yaml -# policies/audit-policy.yaml -audit_events: - - patient_record_accessed - - phi_exported - - user_login - - user_logout - - password_changed - - role_assigned - - data_deleted - - report_generated - -retention: - duration_years: 7 # HIPAA requirement - storage: encrypted_s3 - backup: encrypted_glacier -``` - -### Firewall Rules - -```bash -# iptables.rules -*filter -:INPUT DROP [0:0] -:FORWARD DROP [0:0] -:OUTPUT ACCEPT [0:0] - -# Allow established connections --A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT - -# Allow SSH (rate limited) --A INPUT -p tcp --dport 22 -m recent --name SSH --set --A INPUT -p tcp --dport 22 -m recent --name SSH --update --seconds 60 --hitcount 4 -j DROP --A INPUT -p tcp --dport 22 -j ACCEPT - -# Allow HTTP/HTTPS --A INPUT -p tcp --dport 80 -j ACCEPT --A INPUT -p tcp --dport 443 -j ACCEPT - -# Allow PostgreSQL (internal only) --A INPUT -p tcp -s 10.0.0.0/8 --dport 5432 -j ACCEPT - -# Allow Redis (internal only) --A INPUT -p tcp -s 10.0.0.0/8 --dport 6379 -j ACCEPT - -# Drop all other input --A INPUT -j DROP - -COMMIT -``` - ---- - -## πŸ“Š Security Monitoring - -### Intrusion Detection - -```bash -# Install Fail2Ban -apt-get install fail2ban - -# Monitor SSH attempts -tail -f /var/log/fail2ban.log - -# Unban IP -fail2ban-client set sshd unbanip -``` - -### Vulnerability Scanning - -```bash -# Scan with Trivy -trivy image yaz-care:latest - -# Scan dependencies -safety check -r requirements.txt - -# Audit npm packages -npm audit --audit-level=moderate -``` - -### Security Headers - -```nginx -# nginx security headers -add_header X-Frame-Options "DENY" always; -add_header X-Content-Type-Options "nosniff" always; -add_header X-XSS-Protection "1; mode=block" always; -add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always; -add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline';" always; -add_header Referrer-Policy "strict-origin-when-cross-origin" always; -add_header Permissions-Policy "geolocation=(), microphone=(), camera=()" always; -``` - ---- - -## 🚨 Incident Response - -### Security Breach Protocol - -1. **Immediate Actions** (0-15 minutes): - ```bash - # Isolate affected systems - iptables -A INPUT -j DROP - - # Disable compromised user accounts - vault kv put secret/yaz/disabled_users user_id="" - - # Enable audit logging (verbose) - vault audit enable file file_path=/var/log/vault-audit.log - ``` - -2. **Investigation** (15-60 minutes): - - Review audit logs: `grep "unauthorized_access" logs/audit/*.log` - - Check access patterns: `psql -c "SELECT * FROM audit_logs WHERE created_at > NOW() - INTERVAL '1 hour'"` - - Identify compromised data - -3. **Containment** (1-4 hours): - - Rotate all secrets - - Force password resets - - Update firewall rules - - Patch vulnerabilities - -4. **Recovery** (4-24 hours): - - Restore from clean backup - - Validate data integrity - - Re-enable services incrementally - -5. **Post-Incident** (24+ hours): - - Document incident - - Update security policies - - Notify affected parties (HIPAA breach notification if PHI exposed) - ---- - -## πŸ“š Related Documentation - -- [Authentication](../../src/apps/auth/README.md) -- [Audit Logging](../../docs/architecture/AUDIT.md) -- [Compliance](../../docs/architecture/COMPLIANCE.md) -- [Incident Response](../../docs/07-operations/incident-response.md) - ---- - -**Last Updated**: January 2, 2026 -**Compliance**: HIPAA, GDPR, SOC 2, ISO 27001 diff --git a/infra/security/zap-config.yaml b/infra/security/zap-config.yaml deleted file mode 100644 index 10707a9383326630e6eb173d94d429b2ca0b135f..0000000000000000000000000000000000000000 --- a/infra/security/zap-config.yaml +++ /dev/null @@ -1,418 +0,0 @@ -# OWASP ZAP Scanner Configuration for YAZ Care Platform -# Sprint 36 Phase 1: Web application security testing -# -# Scans for OWASP Top 10: -# 1. Broken Access Control -# 2. Cryptographic Failures -# 3. Injection -# 4. Insecure Design -# 5. Security Misconfiguration -# 6. Vulnerable Components -# 7. Authentication Failures -# 8. Data Integrity Failures -# 9. Logging/Monitoring Failures -# 10. Server-Side Request Forgery (SSRF) - ---- -# ZAP API Scan Configuration -apiScan: - # Target API endpoints - target: "https://staging.yazcare.com" - - # OpenAPI/Swagger definition - apiDefinition: - format: "openapi" - url: "https://staging.yazcare.com/openapi.json" - - # Authentication configuration - authentication: - method: "bearer" - tokenEndpoint: "https://staging.yazcare.com/api/v1/auth/login" - credentials: - username: "${ZAP_TEST_USER}" - password: "${ZAP_TEST_PASSWORD}" - tokenPath: "access_token" - - # Scan policies - scanPolicy: - # Spider configuration (crawl the API) - spider: - maxDepth: 5 - maxChildren: 20 - maxDuration: 10 # minutes - acceptCookies: true - parseComments: true - parseRobotsTxt: true - parseSitemapXml: true - - # Active scan configuration - activeScan: - policy: "API-Scan" # Use API-specific scan policy - strength: "HIGH" - threshold: "MEDIUM" - maxRuleDuration: 5 # minutes per rule - maxScanDuration: 30 # minutes total - threadPerHost: 2 - - # Rules to enable - enabledRules: - - 40012 # Cross Site Scripting (Reflected) - - 40014 # Cross Site Scripting (Persistent) - - 40016 # Cross Site Scripting (DOM Based) - - 40018 # SQL Injection - - 40019 # SQL Injection (MySQL) - - 40020 # SQL Injection (PostgreSQL) - - 90019 # Server Side Code Injection - - 90020 # Remote OS Command Injection - - 40023 # Path Traversal - - 10095 # Backup File Disclosure - - 10098 # Cross-Domain Misconfiguration - - 10202 # Absence of Anti-CSRF Tokens - - 10040 # Secure Pages Include Mixed Content - - 10055 # CSP Scanner - - 10096 # Timestamp Disclosure - - 10021 # X-Content-Type-Options Header Missing - - 10020 # X-Frame-Options Header Missing - - 10035 # Strict-Transport-Security Header Missing - - 10063 # Feature Policy Header Not Set - - 10037 # Server Leaks Information via "X-Powered-By" - - # Rules to disable (false positives) - disabledRules: - - 10015 # Re-examine Cache-control Directives (too many false positives) - - 10027 # Information Disclosure - Suspicious Comments (noisy for commented code) - - # Context configuration - context: - name: "YAZ Care API" - includePaths: - - "https://staging.yazcare.com/api/v1/.*" - - "https://staging.yazcare.com/health" - - "https://staging.yazcare.com/metrics" - excludePaths: - - "https://staging.yazcare.com/static/.*" - - "https://staging.yazcare.com/docs/.*" - - "https://staging.yazcare.com/admin/.*" # Admin endpoints need separate scanning - ---- -# Baseline Scan Configuration (fast, CI/CD friendly) -baselineScan: - target: "https://staging.yazcare.com" - - # Quick scan settings - scanPolicy: - spider: - maxDepth: 2 - maxChildren: 10 - maxDuration: 3 # minutes - - activeScan: - enabled: false # Baseline scan is passive only - - # Passive scan rules - passiveScan: - - 10009 # In Page Banner Information Leak - - 10010 # Cookie No HttpOnly Flag - - 10011 # Cookie Without Secure Flag - - 10015 # Incomplete or No Cache-control and Pragma HTTP Header Set - - 10017 # Cross-Domain JavaScript Source File Inclusion - - 10019 # Content-Type Header Missing - - 10020 # X-Frame-Options Header Missing - - 10021 # X-Content-Type-Options Header Missing - - 10023 # Information Disclosure - Debug Error Messages - - 10024 # Information Disclosure - Sensitive Information in URL - - 10025 # Information Disclosure - Sensitive Information in HTTP Referrer Header - - 10026 # HTTP Parameter Override - - 10027 # Information Disclosure - Suspicious Comments - - 10028 # Open Redirect - - 10029 # Cookie Poisoning - - 10030 # User Controllable Charset - - 10031 # User Controllable HTML Element Attribute (Potential XSS) - - 10032 # Viewstate Scanner - - 10033 # Directory Browsing - - 10034 # Heartbleed OpenSSL Vulnerability - - 10035 # Strict-Transport-Security Header Missing - - 10036 # HTTP Server Response Header - - 10037 # Server Leaks Information via "X-Powered-By" HTTP Response Header Field(s) - - 10038 # Content Security Policy (CSP) Header Not Set - - 10039 # X-Backend-Server Header Information Leak - - 10040 # Secure Pages Include Mixed Content - - 10041 # HTTP to HTTPS Insecure Transition in Form Post - - 10042 # HTTPS to HTTP Insecure Transition in Form Post - - 10043 # User Controllable JavaScript Event (XSS) - - 10044 # Big Redirect Detected (Potential Sensitive Information Leak) - - 10045 # Source Code Disclosure - /WEB-INF folder - - 10048 # Remote Code Execution - Shell Shock - - 10050 # Retrieved from Cache - - 10052 # X-ChromeLogger-Data (XCOLD) Header Information Leak - - 10054 # Cookie Without SameSite Attribute - - 10055 # CSP Scanner (Multiple Checks) - - 10056 # X-Debug-Token Information Leak - - 10057 # Username Hash Found - - 10061 # X-AspNet-Version Response Header - - 10062 # PII Scanner - - 10063 # Feature Policy Header Not Set - - 10095 # Backup File Disclosure - - 10096 # Timestamp Disclosure - - 10097 # Hash Disclosure - - 10098 # Cross-Domain Misconfiguration - - 10099 # Source Code Disclosure - - 10105 # Weak Authentication Method - - 10108 # Reverse Tabnabbing - - 10109 # Modern Web Application - - 10110 # Dangerous JS Functions - - # Alert thresholds - alertThreshold: - fail: - high: 0 # Fail if any high severity alerts - medium: 5 # Fail if more than 5 medium severity alerts - warn: - medium: 1 # Warn if any medium severity alerts - low: 10 # Warn if more than 10 low severity alerts - ---- -# Full Scan Configuration (comprehensive, scheduled) -fullScan: - target: "https://staging.yazcare.com" - - # Comprehensive spider - scanPolicy: - spider: - maxDepth: 10 - maxChildren: 50 - maxDuration: 30 # minutes - subtreeOnly: false - acceptCookies: true - parseComments: true - parseGit: true - parseSVN: true - parseRobotsTxt: true - parseSitemapXml: true - - # Aggressive active scan - activeScan: - policy: "Default Policy" - strength: "INSANE" # Maximum thoroughness - threshold: "LOW" # Report everything - maxRuleDuration: 10 # minutes per rule - maxScanDuration: 120 # 2 hours - threadPerHost: 4 - delayInMs: 0 - inScopeOnly: true - - # AJAX Spider (for SPAs) - ajaxSpider: - enabled: true - maxCrawlDepth: 10 - maxCrawlStates: 100 - maxDuration: 30 # minutes - numberOfBrowsers: 2 - clickDefaultElems: true - clickElemsOnce: false - eventWait: 1000 # ms - reloadWait: 1000 # ms - - # Technology detection - techDetection: - enabled: true - categories: - - "Language" - - "OS" - - "Framework" - - "Library" - - "Web Server" - - "Database" - - # Report configuration - reports: - formats: - - "HTML" - - "JSON" - - "XML" - - "MD" # Markdown - outputDir: "/zap/reports" - includeRiskCodes: - - 0 # Informational - - 1 # Low - - 2 # Medium - - 3 # High - excludeRiskCodes: [] - ---- -# Healthcare-Specific Security Checks -healthcareChecks: - # HIPAA compliance checks - hipaa: - - name: "PHI Exposure in Logs" - description: "Check for patient identifiers in error messages and logs" - pattern: "\\b(SSN|MRN|DOB|patient_id)\\b" - severity: "HIGH" - - - name: "Audit Trail Verification" - description: "Verify all PHI access is logged" - endpoints: - - "/api/v1/patients/*" - - "/api/v1/clinica/*" - - "/api/v1/labo/*" - requiredHeaders: - - "X-Audit-Token" - severity: "HIGH" - - - name: "Session Timeout" - description: "Verify session timeout <= 15 minutes" - check: "cookie_max_age" - maxSeconds: 900 - severity: "MEDIUM" - - - name: "Password Complexity" - description: "Verify password requirements meet HIPAA standards" - endpoint: "/api/v1/auth/register" - requirements: - minLength: 12 - requireUppercase: true - requireLowercase: true - requireDigits: true - requireSpecial: true - severity: "HIGH" - - # OWASP API Security Top 10 - apiSecurity: - - name: "Broken Object Level Authorization" - description: "Test for unauthorized access to resources" - testCases: - - endpoint: "/api/v1/patients/{id}" - method: "GET" - testDifferentTenantId: true - expectedStatus: 404 - - - name: "Broken User Authentication" - description: "Test for weak authentication mechanisms" - testCases: - - endpoint: "/api/v1/auth/login" - attacks: - - "brute_force" - - "credential_stuffing" - - "weak_passwords" - - - name: "Excessive Data Exposure" - description: "Check for sensitive data in API responses" - patterns: - - "password" - - "secret" - - "token" - - "api_key" - - "ssn" - - "credit_card" - - - name: "Rate Limiting" - description: "Verify rate limiting on all endpoints" - testCases: - - endpoint: "/api/v1/auth/login" - requestsPerMinute: 100 - expectedStatus: 429 - - - name: "Mass Assignment" - description: "Test for mass assignment vulnerabilities" - testCases: - - endpoint: "/api/v1/users/{id}" - method: "PATCH" - injectFields: - - "is_admin" - - "role" - - "permissions" - expectedBehavior: "reject" - ---- -# ZAP Docker Configuration -docker: - image: "ghcr.io/zaproxy/zaproxy:stable" - - # Baseline scan command - baselineCommand: > - zap-baseline.py - -t ${TARGET_URL} - -c zap-config.yaml - -r baseline-report.html - -J baseline-report.json - -w baseline-report.md - -l WARN - -z "-config api.disablekey=true" - - # Full scan command - fullScanCommand: > - zap-full-scan.py - -t ${TARGET_URL} - -c zap-config.yaml - -r full-report.html - -J full-report.json - -w full-report.md - -l INFO - -z "-config api.disablekey=true" - - # API scan command - apiScanCommand: > - zap-api-scan.py - -t ${TARGET_URL}/openapi.json - -f openapi - -c zap-config.yaml - -r api-report.html - -J api-report.json - -w api-report.md - -l INFO - -z "-config api.disablekey=true" - ---- -# CI/CD Integration -cicd: - # GitHub Actions - githubActions: - triggerOn: - - push - - pull_request - - schedule # Daily at 2 AM UTC - - jobs: - - name: "zap-baseline" - scanType: "baseline" - continueOnError: false - artifactRetention: 30 # days - - - name: "zap-full-scan" - scanType: "full" - schedule: "0 2 * * *" # Daily at 2 AM - continueOnError: true - artifactRetention: 90 # days - - # Quality gates - qualityGates: - baseline: - maxHighAlerts: 0 - maxMediumAlerts: 5 - maxLowAlerts: 20 - failBuild: true - - full: - maxHighAlerts: 0 - maxMediumAlerts: 10 - maxLowAlerts: 50 - failBuild: false # Don't block builds, but notify - - # Notifications - notifications: - slack: - enabled: true - webhook: "${SLACK_WEBHOOK_URL}" - channel: "#security-alerts" - notifyOn: - - "high_severity_found" - - "scan_failed" - - email: - enabled: true - recipients: - - "security@yazcare.com" - - "devops@yazcare.com" - notifyOn: - - "critical_severity_found" - - "compliance_violation" diff --git a/render.yaml b/render.yaml deleted file mode 100644 index 15930eaad8133ad5789c64c0d23d7307e1270f2f..0000000000000000000000000000000000000000 --- a/render.yaml +++ /dev/null @@ -1,24 +0,0 @@ -# YAZ Platform β€” Render Blueprint -# Auto-deploy from GitHub, zero config, free tier -# Docs: https://render.com/docs/blueprint-spec - -services: - - type: web - name: yaz - runtime: docker - dockerfilePath: ./infra/docker/Dockerfile - region: frankfurt - plan: free - healthCheckPath: /health - autoDeploy: true - envVars: - - key: ENVIRONMENT - value: production - - key: YAZ_PORT - value: "8000" - - key: PYTHONPATH - value: "/app/src:/app" - - key: SECRET_KEY - generateValue: true - - key: JWT_SECRET_KEY - generateValue: true diff --git a/scripts/deployment/deploy.sh b/scripts/deployment/deploy.sh deleted file mode 100755 index 6d17d179df355752f22d3ee792adc1c97c355310..0000000000000000000000000000000000000000 --- a/scripts/deployment/deploy.sh +++ /dev/null @@ -1,460 +0,0 @@ -#!/usr/bin/env bash -# ═══════════════════════════════════════════════════════════════════════ -# YAZ Platform β€” Universal Zero-Cost Deployment Orchestrator -# ═══════════════════════════════════════════════════════════════════════ -# -# Deploys YAZ to always-on free hosting so you DON'T need your PC 24/7. -# -# STRATEGY (ranked by reliability): -# 1. Koyeb β€” Free tier: 1 nano instance, auto-sleep, Docker deploy -# 2. Render β€” Free tier: 750h/month, auto-deploy from GitHub -# 3. Fly.io β€” Free tier: 3 shared VMs, 256MB RAM each -# 4. Railway β€” Free tier: $5/month credit (trial, then pay-as-go) -# 5. Local β€” Cloudflare Tunnel (only while PC is on) -# -# Usage: -# ./deploy.sh # Interactive menu -# ./deploy.sh koyeb # Deploy to Koyeb -# ./deploy.sh render # Deploy to Render -# ./deploy.sh fly # Deploy to Fly.io -# ./deploy.sh local # Local + Cloudflare Tunnel -# ./deploy.sh status # Check all deployments -# ./deploy.sh backup # Backup DB to GitHub -# -# Prerequisites: -# - Git repo pushed to GitHub (βœ… done) -# - Docker installed (for Fly.io) -# - Free accounts on target platforms -# -# ═══════════════════════════════════════════════════════════════════════ -set -euo pipefail - -# ─── Config ─────────────────────────────────────────────────────────── -YAZ_ROOT="$(cd "$(dirname "$0")/../.." && pwd)" -YAZ_PORT="${YAZ_PORT:-8000}" -GITHUB_REPO="${GITHUB_REPO:-Elanass/yaz}" -APP_NAME="${APP_NAME:-yaz-platform}" -DEPLOY_LOG="$YAZ_ROOT/logs/deploy.log" - -# Colors -G='\033[0;32m' Y='\033[1;33m' R='\033[0;31m' C='\033[0;36m' B='\033[1m' N='\033[0m' -DIM='\033[2m' - -mkdir -p "$YAZ_ROOT/logs" - -log() { echo -e "$(date '+%H:%M:%S') $*" | tee -a "$DEPLOY_LOG"; } -ok() { log "${G}βœ… $*${N}"; } -warn(){ log "${Y}⚠️ $*${N}"; } -err() { log "${R}❌ $*${N}"; } -hdr() { echo -e "\n${C}═══ $* ═══${N}"; } - -# ═══════════════════════════════════════════════════════════════════════ -# 1. KOYEB β€” Best Free Option (always-on, Docker, auto-deploy) -# ═══════════════════════════════════════════════════════════════════════ -deploy_koyeb() { - hdr "KOYEB DEPLOYMENT" - echo -e "${DIM}Free: 1 nano instance (512MB RAM, 0.1 vCPU), auto-sleep after 5min idle${N}" - echo -e "${DIM}Wake: ~30s cold start on first request${N}\n" - - # Check koyeb CLI - if ! command -v koyeb &>/dev/null; then - echo -e "${Y}Installing Koyeb CLI...${N}" - curl -fsSL https://raw.githubusercontent.com/koyeb/koyeb-cli/master/install.sh | sh - export PATH="$HOME/.koyeb/bin:$PATH" - fi - - # Check auth - if ! koyeb whoami &>/dev/null 2>&1; then - echo -e "${Y}πŸ“‹ Setup steps:${N}" - echo -e " 1. Go to ${C}https://app.koyeb.com${N} β†’ Sign up (free, no card)" - echo -e " 2. Settings β†’ API β†’ Create token" - echo -e " 3. Run: ${C}koyeb login${N}" - echo "" - read -rp "Press Enter after completing setup..." - koyeb login - fi - - ok "Authenticated with Koyeb" - - # Deploy from GitHub (auto-builds Dockerfile) - echo -e "${C}πŸš€ Deploying from GitHub: $GITHUB_REPO${N}" - - koyeb app init "$APP_NAME" 2>/dev/null || true - - koyeb service create "$APP_NAME/web" \ - --git "github.com/$GITHUB_REPO" \ - --git-branch master \ - --git-builder docker \ - --git-docker-dockerfile infra/docker/Dockerfile \ - --ports "8000:http" \ - --routes "/:8000" \ - --instance-type free \ - --regions fra \ - --env "ENVIRONMENT=production" \ - --env "YAZ_PORT=8000" \ - --checks '8000:http:/health' \ - 2>/dev/null || \ - koyeb service update "$APP_NAME/web" \ - --git "github.com/$GITHUB_REPO" \ - --git-branch master \ - --git-builder docker \ - --git-docker-dockerfile infra/docker/Dockerfile \ - 2>/dev/null - - echo "" - ok "Deployed to Koyeb!" - echo -e " ${C}🌐 https://${APP_NAME}-.koyeb.app${N}" - echo -e " ${DIM}Dashboard: https://app.koyeb.com${N}" - echo -e " ${DIM}Auto-deploys on every git push to master${N}" - koyeb app get "$APP_NAME" 2>/dev/null || true -} - -# ═══════════════════════════════════════════════════════════════════════ -# 2. RENDER β€” Second Best (auto-deploy from GitHub, free SSL) -# ═══════════════════════════════════════════════════════════════════════ -deploy_render() { - hdr "RENDER DEPLOYMENT" - echo -e "${DIM}Free: 750h/month, auto-deploy from GitHub, spins down after 15min idle${N}" - echo -e "${DIM}Wake: ~30-60s cold start${N}\n" - - # Create render.yaml blueprint if not exists - local render_yaml="$YAZ_ROOT/render.yaml" - if [[ ! -f "$render_yaml" ]]; then - cat > "$render_yaml" << 'RENDERYAML' -# YAZ Platform β€” Render Blueprint -# Auto-deploy from GitHub, zero config -services: - - type: web - name: yaz-platform - runtime: docker - dockerfilePath: ./infra/docker/Dockerfile - region: frankfurt - plan: free - healthCheckPath: /health - envVars: - - key: ENVIRONMENT - value: production - - key: YAZ_PORT - value: "8000" - - key: PYTHONPATH - value: "/app/src:/app" -RENDERYAML - ok "Created render.yaml" - fi - - echo -e "${Y}πŸ“‹ Deploy steps:${N}" - echo -e " 1. Go to ${C}https://render.com${N} β†’ Sign up with GitHub (free)" - echo -e " 2. Click ${B}New β†’ Blueprint${N}" - echo -e " 3. Connect repo: ${C}$GITHUB_REPO${N}" - echo -e " 4. Render auto-detects render.yaml β†’ Click ${B}Apply${N}" - echo "" - echo -e " ${G}That's it! Auto-deploys on every push.${N}" - echo -e " ${C}🌐 https://yaz-platform.onrender.com${N}" - echo "" - - # Commit render.yaml if new - if git -C "$YAZ_ROOT" diff --name-only | grep -q "render.yaml"; then - read -rp "Commit & push render.yaml? [Y/n] " yn - if [[ "${yn:-Y}" =~ ^[Yy]$ ]]; then - git -C "$YAZ_ROOT" add render.yaml - git -C "$YAZ_ROOT" commit -m "deploy: add Render blueprint for free hosting" - git -C "$YAZ_ROOT" push origin master - ok "Pushed render.yaml to GitHub" - fi - fi -} - -# ═══════════════════════════════════════════════════════════════════════ -# 3. FLY.IO β€” Most Flexible (3 free VMs, persistent volumes) -# ═══════════════════════════════════════════════════════════════════════ -deploy_fly() { - hdr "FLY.IO DEPLOYMENT" - echo -e "${DIM}Free: 3 shared VMs (256MB each), 3GB persistent volume, auto-stop${N}" - echo -e "${DIM}Best for: persistent SQLite DB (volume mount)${N}\n" - - # Check flyctl - if ! command -v flyctl &>/dev/null && ! command -v fly &>/dev/null; then - echo -e "${Y}Installing Fly CLI...${N}" - curl -L https://fly.io/install.sh | sh - export PATH="$HOME/.fly/bin:$PATH" - fi - - local FLY="fly" - command -v flyctl &>/dev/null && FLY="flyctl" - - # Check auth - if ! $FLY auth whoami &>/dev/null 2>&1; then - echo -e "${Y}πŸ“‹ Sign up at ${C}https://fly.io${N} (free, card required for verification only)" - $FLY auth login - fi - - ok "Authenticated with Fly.io" - - # Create fly.toml if not exists - local fly_toml="$YAZ_ROOT/fly.toml" - if [[ ! -f "$fly_toml" ]]; then - cat > "$fly_toml" << 'FLYTOML' -# YAZ Platform β€” Fly.io Configuration -app = "yaz-platform" -primary_region = "cdg" # Paris - -[build] - dockerfile = "infra/docker/Dockerfile" - -[env] - ENVIRONMENT = "production" - YAZ_PORT = "8000" - PYTHONPATH = "/app/src:/app" - -[http_service] - internal_port = 8000 - force_https = true - auto_stop_machines = true # Sleep when idle (saves free hours) - auto_start_machines = true # Wake on request - min_machines_running = 0 # Allow full sleep - [http_service.concurrency] - type = "requests" - hard_limit = 250 - soft_limit = 200 - -[[vm]] - memory = "256mb" - cpu_kind = "shared" - cpus = 1 - -[mounts] - source = "yaz_data" - destination = "/app/data" - initial_size = 1 # 1GB free - -[[checks]] - grace_period = "30s" - interval = "30s" - method = "GET" - path = "/health" - port = 8000 - timeout = "5s" - type = "http" -FLYTOML - ok "Created fly.toml" - fi - - # Launch or deploy - if ! $FLY apps list 2>/dev/null | grep -q "$APP_NAME"; then - echo -e "${C}πŸš€ Launching new Fly app...${N}" - $FLY launch --copy-config --no-deploy --name "$APP_NAME" --region cdg - - # Create persistent volume for SQLite DB - echo -e "${C}πŸ“¦ Creating persistent volume for database...${N}" - $FLY volumes create yaz_data --region cdg --size 1 --yes - fi - - echo -e "${C}πŸš€ Deploying to Fly.io...${N}" - $FLY deploy - - echo "" - ok "Deployed to Fly.io!" - $FLY status - echo -e "\n ${C}🌐 https://${APP_NAME}.fly.dev${N}" - echo -e " ${DIM}Auto-sleeps when idle, wakes on request (~2-5s)${N}" - echo -e " ${DIM}SQLite persisted on volume β€” survives redeploys${N}" -} - -# ═══════════════════════════════════════════════════════════════════════ -# 4. LOCAL β€” Cloudflare Tunnel (only while PC is on) -# ═══════════════════════════════════════════════════════════════════════ -deploy_local() { - hdr "LOCAL DEPLOYMENT (Cloudflare Tunnel)" - echo -e "${DIM}Free: HTTPS URL via Cloudflare, only works while PC is on${N}\n" - - # Ensure server is running - if ! curl -sf -o /dev/null --max-time 2 "http://localhost:$YAZ_PORT/"; then - echo -e "${Y}Starting YAZ server...${N}" - cd "$YAZ_ROOT" - source .venv/bin/activate 2>/dev/null || true - nohup python3 main.py serve --host 0.0.0.0 --port "$YAZ_PORT" \ - > "$YAZ_ROOT/logs/server.log" 2>&1 & - echo "$!" > /tmp/yaz-server.pid - - # Wait for startup - for _ in $(seq 1 15); do - sleep 1 - curl -sf -o /dev/null --max-time 2 "http://localhost:$YAZ_PORT/" && break - done - fi - - # Delegate to existing tunnel script - bash "$YAZ_ROOT/scripts/deployment/deploy_free.sh" start -} - -# ═══════════════════════════════════════════════════════════════════════ -# 5. STATUS β€” Check all deployments -# ═══════════════════════════════════════════════════════════════════════ -show_status() { - hdr "YAZ DEPLOYMENT STATUS" - - echo -e "\n${B}Local:${N}" - if curl -sf -o /dev/null --max-time 2 "http://localhost:$YAZ_PORT/"; then - echo -e " Server: ${G}● Running${N} (port $YAZ_PORT)" - else - echo -e " Server: ${R}● Stopped${N}" - fi - if [[ -f /tmp/yaz-tunnel.pid ]] && kill -0 "$(cat /tmp/yaz-tunnel.pid)" 2>/dev/null; then - echo -e " Tunnel: ${G}● Running${N}" - [[ -f /tmp/yaz-tunnel-url.txt ]] && echo -e " URL: ${C}$(cat /tmp/yaz-tunnel-url.txt)${N}" - else - echo -e " Tunnel: ${DIM}β—‹ Not running${N}" - fi - - echo -e "\n${B}Cloud (always-on):${N}" - - # Koyeb - if command -v koyeb &>/dev/null && koyeb whoami &>/dev/null 2>&1; then - local koyeb_status - koyeb_status=$(koyeb app get "$APP_NAME" --output json 2>/dev/null | grep -o '"status":"[^"]*"' | head -1 || echo "") - if [[ -n "$koyeb_status" ]]; then - echo -e " Koyeb: ${G}● Deployed${N} ($koyeb_status)" - else - echo -e " Koyeb: ${DIM}β—‹ Not deployed${N}" - fi - else - echo -e " Koyeb: ${DIM}β—‹ CLI not installed${N}" - fi - - # Fly.io - if command -v fly &>/dev/null || command -v flyctl &>/dev/null; then - local FLY="fly" - command -v flyctl &>/dev/null && FLY="flyctl" - if $FLY auth whoami &>/dev/null 2>&1; then - if $FLY status -a "$APP_NAME" &>/dev/null 2>&1; then - echo -e " Fly.io: ${G}● Deployed${N} (https://${APP_NAME}.fly.dev)" - else - echo -e " Fly.io: ${DIM}β—‹ Not deployed${N}" - fi - else - echo -e " Fly.io: ${DIM}β—‹ Not authenticated${N}" - fi - else - echo -e " Fly.io: ${DIM}β—‹ CLI not installed${N}" - fi - - # Render (check via API or just show link) - echo -e " Render: ${DIM}Check at https://dashboard.render.com${N}" - - echo -e "\n${B}Git:${N}" - local branch commit - branch=$(git -C "$YAZ_ROOT" branch --show-current 2>/dev/null || echo "?") - commit=$(git -C "$YAZ_ROOT" log --oneline -1 2>/dev/null || echo "?") - echo -e " Branch: ${C}$branch${N}" - echo -e " Latest: ${DIM}$commit${N}" - echo -e " Remote: ${C}https://github.com/$GITHUB_REPO${N}" -} - -# ═══════════════════════════════════════════════════════════════════════ -# 6. BACKUP β€” DB backup to GitHub (zero-cost persistence) -# ═══════════════════════════════════════════════════════════════════════ -backup_db() { - hdr "DATABASE BACKUP" - - local db_file="$YAZ_ROOT/data/databases/yaz_care.db" - local backup_dir="$YAZ_ROOT/data/databases/backups" - local timestamp - timestamp=$(date '+%Y%m%d_%H%M%S') - - mkdir -p "$backup_dir" - - if [[ -f "$db_file" ]]; then - local backup_file="$backup_dir/yaz_care_${timestamp}.db" - - # SQLite safe backup (handles WAL mode) - sqlite3 "$db_file" ".backup '$backup_file'" 2>/dev/null || cp "$db_file" "$backup_file" - - # Compress - gzip -9 "$backup_file" - local size - size=$(du -h "${backup_file}.gz" | cut -f1) - ok "Backup: ${backup_file}.gz ($size)" - - # Keep only last 5 backups - ls -t "$backup_dir"/*.gz 2>/dev/null | tail -n +6 | xargs rm -f 2>/dev/null || true - - # Optionally push to GitHub - read -rp "Push backup to GitHub? [Y/n] " yn - if [[ "${yn:-Y}" =~ ^[Yy]$ ]]; then - git -C "$YAZ_ROOT" add "$backup_dir/" - git -C "$YAZ_ROOT" commit -m "backup: database snapshot $timestamp" - git -C "$YAZ_ROOT" push origin master - ok "Backup pushed to GitHub" - fi - else - warn "No database found at $db_file" - fi -} - -# ═══════════════════════════════════════════════════════════════════════ -# 7. INTERACTIVE MENU -# ═══════════════════════════════════════════════════════════════════════ -show_menu() { - echo -e "${C}" - echo " ╔═══════════════════════════════════════════════════════╗" - echo " β•‘ YAZ Platform β€” Deploy Anywhere β•‘" - echo " β•‘ Zero Cost Β· Always On Β· Your Data β•‘" - echo " ╠═══════════════════════════════════════════════════════╣" - echo " β•‘ β•‘" - echo " β•‘ CLOUD (always-on, free): β•‘" - echo " β•‘ 1) Koyeb β€” Docker deploy, auto-sleep/wake β•‘" - echo " β•‘ 2) Render β€” GitHub auto-deploy, 750h free β•‘" - echo " β•‘ 3) Fly.io β€” Persistent volume for SQLite DB β•‘" - echo " β•‘ β•‘" - echo " β•‘ LOCAL (while PC is on): β•‘" - echo " β•‘ 4) Local β€” Cloudflare Tunnel (instant HTTPS) β•‘" - echo " β•‘ β•‘" - echo " β•‘ MANAGE: β•‘" - echo " β•‘ 5) Status β€” Check all deployments β•‘" - echo " β•‘ 6) Backup β€” Backup database to GitHub β•‘" - echo " β•‘ q) Quit β•‘" - echo " β•‘ β•‘" - echo " β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•" - echo -e "${N}" - - read -rp " Choose [1-6/q]: " choice - case "$choice" in - 1|koyeb) deploy_koyeb ;; - 2|render) deploy_render ;; - 3|fly) deploy_fly ;; - 4|local) deploy_local ;; - 5|status) show_status ;; - 6|backup) backup_db ;; - q|Q) echo -e "${G}πŸ‘‹ Bye${N}"; exit 0 ;; - *) err "Invalid choice"; show_menu ;; - esac -} - -# ═══════════════════════════════════════════════════════════════════════ -# MAIN -# ═══════════════════════════════════════════════════════════════════════ -main() { - case "${1:-}" in - koyeb) deploy_koyeb ;; - render) deploy_render ;; - fly) deploy_fly ;; - local) deploy_local ;; - status) show_status ;; - backup) backup_db ;; - help|-h|--help) - echo "Usage: $0 [koyeb|render|fly|local|status|backup|help]" - echo "" - echo " koyeb Deploy to Koyeb (free Docker hosting)" - echo " render Deploy to Render (free GitHub auto-deploy)" - echo " fly Deploy to Fly.io (free with persistent volume)" - echo " local Local server + Cloudflare Tunnel" - echo " status Check all deployments" - echo " backup Backup SQLite database" - echo " help Show this help" - ;; - "") show_menu ;; - *) err "Unknown command: $1"; echo "Run '$0 help' for usage"; exit 1 ;; - esac -} - -main "$@" diff --git a/scripts/deployment/deploy_free.sh b/scripts/deployment/deploy_free.sh deleted file mode 100755 index 2c0be88b6c03d441539673f39d1569ffb21a657f..0000000000000000000000000000000000000000 --- a/scripts/deployment/deploy_free.sh +++ /dev/null @@ -1,96 +0,0 @@ -#!/usr/bin/env bash -# YAZ Platform β€” Zero-Cost Deploy (Cloudflare Tunnel) -# Usage: ./deploy_free.sh [start|stop|status] -set -euo pipefail - -YAZ_PORT="${YAZ_PORT:-8000}" -YAZ_ROOT="$(cd "$(dirname "$0")/../.." && pwd)" -CLOUDFLARED="$HOME/.local/bin/cloudflared" -PID_FILE="/tmp/yaz-tunnel.pid" -URL_FILE="/tmp/yaz-tunnel-url.txt" -LOG_FILE="$YAZ_ROOT/logs/tunnel.log" - -G='\033[0;32m' Y='\033[1;33m' R='\033[0;31m' C='\033[0;36m' N='\033[0m' - -ensure_cloudflared() { - [[ -x "$CLOUDFLARED" ]] && return 0 - echo -e "${Y}⬇ Installing cloudflared...${N}" - mkdir -p ~/.local/bin - curl -fsSL -o "$CLOUDFLARED" \ - https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64 - chmod +x "$CLOUDFLARED" - echo -e "${G}βœ… $($CLOUDFLARED --version)${N}" -} - -stop_tunnel() { - if [[ -f "$PID_FILE" ]]; then - PID=$(cat "$PID_FILE") - kill "$PID" 2>/dev/null && echo -e "${G}βœ… Tunnel stopped (PID $PID)${N}" \ - || echo -e "${Y}Already stopped${N}" - rm -f "$PID_FILE" "$URL_FILE" - else - pkill -f "cloudflared tunnel" 2>/dev/null \ - && echo -e "${G}βœ… Tunnel stopped${N}" \ - || echo -e "${Y}No tunnel running${N}" - fi -} - -show_status() { - echo -e "${C}═══ YAZ Deploy Status ═══${N}" - if curl -sf -o /dev/null --max-time 2 "http://localhost:$YAZ_PORT/"; then - echo -e " Server: ${G}● Running${N} (port $YAZ_PORT)" - else - echo -e " Server: ${R}● Stopped${N}" - fi - if [[ -f "$PID_FILE" ]] && kill -0 "$(cat "$PID_FILE")" 2>/dev/null; then - echo -e " Tunnel: ${G}● Running${N} (PID $(cat "$PID_FILE"))" - [[ -f "$URL_FILE" ]] && echo -e " URL: ${C}$(cat "$URL_FILE")${N}" - else - echo -e " Tunnel: ${R}● Stopped${N}" - fi -} - -start_tunnel() { - ensure_cloudflared - - if ! curl -sf -o /dev/null --max-time 2 "http://localhost:$YAZ_PORT/"; then - echo -e "${R}❌ YAZ not running on port $YAZ_PORT${N}" - echo -e "${Y} Start first: python3 main.py serve${N}" - exit 1 - fi - - stop_tunnel 2>/dev/null || true - mkdir -p "$(dirname "$LOG_FILE")" - - echo -e "${C}πŸš€ Starting Cloudflare Tunnel (free, no account)...${N}" - $CLOUDFLARED tunnel --url "http://localhost:$YAZ_PORT" \ - --logfile "$LOG_FILE" --no-autoupdate 2>&1 & - echo "$!" > "$PID_FILE" - - echo -e "${Y}⏳ Waiting for URL...${N}" - for _ in $(seq 1 30); do - sleep 1 - URL=$(grep -oP 'https://[a-z0-9-]+\.trycloudflare\.com' "$LOG_FILE" 2>/dev/null | head -1 || true) - if [[ -n "$URL" ]]; then - echo "$URL" > "$URL_FILE" - echo "" - echo -e "${G} βœ… YAZ is LIVE:${N}" - echo -e "${C} 🌐 $URL${N}" - echo -e " HTTPS: auto Β· DDoS: Cloudflare Β· Cost: \$0" - echo -e " Stop: ${Y}./deploy_free.sh stop${N}" - echo "" - return 0 - fi - done - - echo -e "${R}❌ Timeout. Check: $LOG_FILE${N}" - tail -10 "$LOG_FILE" - return 1 -} - -case "${1:-start}" in - start) start_tunnel ;; - stop) stop_tunnel ;; - status) show_status ;; - *) echo "Usage: $0 [start|stop|status]" ;; -esac diff --git a/scripts/deployment/deploy_hf_spaces.sh b/scripts/deployment/deploy_hf_spaces.sh deleted file mode 100755 index 1e04187bf27c5c48358e22883814129f27b193b7..0000000000000000000000000000000000000000 --- a/scripts/deployment/deploy_hf_spaces.sh +++ /dev/null @@ -1,201 +0,0 @@ -#!/bin/bash -# ═══════════════════════════════════════════════════════════════ -# YAZ Platform β€” Deploy to Hugging Face Spaces -# -# Clones the GitHub repo into a HF Spaces repo with the -# correct Dockerfile and README YAML front matter. -# -# Usage: -# ./scripts/deployment/deploy_hf_spaces.sh -# -# Prerequisites: -# 1. pip install huggingface_hub -# 2. huggingface-cli login (get token from https://huggingface.co/settings/tokens) -# 3. git lfs install (for large files) -# ═══════════════════════════════════════════════════════════════ -set -euo pipefail - -HF_USERNAME="${1:-Elanass}" -SPACE_NAME="yaz" -SPACE_ID="${HF_USERNAME}/${SPACE_NAME}" -REPO_URL="https://huggingface.co/spaces/${SPACE_ID}" -WORK_DIR=$(mktemp -d) -PROJECT_ROOT="$(cd "$(dirname "$0")/../.." && pwd)" - -echo "╔══════════════════════════════════════════╗" -echo "β•‘ πŸ€— YAZ β†’ Hugging Face Spaces Deploy β•‘" -echo "╠══════════════════════════════════════════╣" -echo "β•‘ Space: ${SPACE_ID}" -echo "β•‘ URL: https://${HF_USERNAME}-${SPACE_NAME}.hf.space" -echo "β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•" -echo "" - -# ─── Step 1: Check prerequisites ──────────────────────────── -echo "πŸ” Checking prerequisites..." -if ! command -v git &>/dev/null; then - echo "❌ git not found. Install git first." - exit 1 -fi - -if ! pip show huggingface_hub &>/dev/null 2>&1; then - echo "⚠️ huggingface_hub not installed. Installing..." - pip install --quiet huggingface_hub -fi - -# ─── Step 2: Create/clone HF Space ────────────────────────── -echo "" -echo "πŸ“¦ Setting up HF Space repo..." - -# Try to create the space first (will fail if it already exists β€” that's OK) -python3 -c " -from huggingface_hub import HfApi -api = HfApi() -try: - api.create_repo( - repo_id='${SPACE_ID}', - repo_type='space', - space_sdk='docker', - exist_ok=True, - private=False, - ) - print('βœ… Space created/confirmed: ${SPACE_ID}') -except Exception as e: - print(f'⚠️ Space creation note: {e}') -" 2>/dev/null || echo "⚠️ Could not auto-create space. Create it manually at https://huggingface.co/new-space" - -# Clone the HF Space repo -echo "πŸ“₯ Cloning HF Space repo to ${WORK_DIR}..." -cd "$WORK_DIR" -git clone "https://huggingface.co/spaces/${SPACE_ID}" hf-space 2>/dev/null || { - mkdir hf-space && cd hf-space && git init - git remote add origin "https://huggingface.co/spaces/${SPACE_ID}" -} -cd hf-space - -# ─── Step 3: Copy project files ───────────────────────────── -echo "" -echo "πŸ“‹ Copying YAZ project files..." - -# Clean existing files (except .git) -find . -maxdepth 1 -not -name '.git' -not -name '.' -exec rm -rf {} + - -# Copy everything from project, excluding unnecessary files -rsync -a --progress \ - --exclude='.git' \ - --exclude='.venv' \ - --exclude='__pycache__' \ - --exclude='.pytest_cache' \ - --exclude='.mypy_cache' \ - --exclude='node_modules' \ - --exclude='.env' \ - --exclude='*.pyc' \ - --exclude='.DS_Store' \ - --exclude='logs/' \ - --exclude='storage/' \ - "${PROJECT_ROOT}/" ./ - -# ─── Step 4: Create HF Spaces README (YAML front matter) ──── -echo "" -echo "πŸ“ Creating HF Spaces README.md..." - -cat > README.md << 'HFREADME' ---- -title: YAZ -emoji: πŸ₯ -colorFrom: blue -colorTo: purple -sdk: docker -app_port: 7860 -pinned: true -license: agpl-3.0 -short_description: "Digital Intelligence Platform β€” Create, deploy, and orchestrate intelligent tools across any domain" -tags: - - healthcare - - intelligence-platform - - fastapi - - multi-tenant ---- - -# YAZ β€” Digital Intelligence Platform - -> **Create, deploy, sell, and orchestrate intelligent tools across any domain.** - -πŸ₯ 14 Domain Engines Β· 24 Service Pillars Β· Multi-Tenant Β· Real-Time - -**Built by Dr. Anass Elamrani** - -## Engines - -| Engine | Domain | Description | -|--------|--------|-------------| -| πŸ”ͺ Surgio | Surgery | Operative protocols, WHO checklists, outcome tracking | -| πŸ₯ Clinica | Clinical | Encounters, NEWS2 scoring, pathways | -| πŸ”¬ Labo | Laboratory | Westgard QC, specimen tracking, results | -| πŸ’Š Pharma | Pharmacy | Prescriptions, drug interactions, DEA compliance | -| 🏨 Hospi | Hospitality | Bed management, accommodation, ADT feeds | -| πŸ’° Banko | Finance | Payments, cost tracking, accounting | -| πŸ›‘οΈ Insura | Insurance | Claims, coverage validation, reimbursement | -| 🚚 Movio | Mobility | Transport, referral logistics, fleet tracking | -| πŸ“¦ Stoka | Resources | Inventory, supply chain, equipment | -| πŸŽ“ Educa | Education | Training, ACGME milestones, competency | -| 🌍 Campo | Field Ops | Community encounters, GPS logistics | -| 🏭 Fabrica | Manufacturing | Batch QC, GMP compliance | -| πŸ“‹ Trena | Training | Staff credentialing, skill tracking | -| 🏠 Casa | Accommodation | Room management, reservations | - -## Architecture - -``` -Platform (24 Pillars) β†’ Engines (14 domains) β†’ Intelligences (packaged expertise) -``` - -[Full docs on GitHub](https://github.com/Elanass/yaz) -HFREADME - -# ─── Step 5: Use root Dockerfile (already created) ────────── -echo "🐳 Verifying Dockerfile..." -if [ ! -f "Dockerfile" ]; then - echo "❌ Root Dockerfile not found! Create it first." - exit 1 -fi -echo "βœ… Dockerfile ready (port 7860, uid 1000)" - -# ─── Step 6: Create .gitattributes for LFS ────────────────── -cat > .gitattributes << 'EOF' -*.db filter=lfs diff=lfs merge=lfs -text -*.sqlite filter=lfs diff=lfs merge=lfs -text -*.bin filter=lfs diff=lfs merge=lfs -text -*.pkl filter=lfs diff=lfs merge=lfs -text -EOF - -# ─── Step 7: Push to HF Spaces ────────────────────────────── -echo "" -echo "πŸš€ Pushing to Hugging Face Spaces..." - -git add -A -git commit -m "deploy: YAZ Platform to Hugging Face Spaces" --allow-empty - -git push origin main 2>/dev/null || git push origin master 2>/dev/null || { - echo "⚠️ Push failed. You may need to:" - echo " 1. Run: huggingface-cli login" - echo " 2. Create the space at: https://huggingface.co/new-space" - echo " 3. Try manual push from: ${WORK_DIR}/hf-space" - exit 1 -} - -# ─── Step 8: Cleanup & summary ─────────────────────────────── -echo "" -echo "╔══════════════════════════════════════════════════════╗" -echo "β•‘ βœ… DEPLOYED SUCCESSFULLY! β•‘" -echo "╠══════════════════════════════════════════════════════╣" -echo "β•‘ β•‘" -echo "β•‘ 🌐 Live URL: https://${HF_USERNAME}-${SPACE_NAME}.hf.space β•‘" -echo "β•‘ πŸ“Š Space: https://huggingface.co/spaces/${SPACE_ID} β•‘" -echo "β•‘ β•‘" -echo "β•‘ ⏳ First build takes ~3-5 minutes β•‘" -echo "β•‘ πŸ“¦ Subsequent deploys: ~1-2 minutes β•‘" -echo "β•‘ β•‘" -echo "β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•" - -# Cleanup temp dir -rm -rf "$WORK_DIR" diff --git a/scripts/deployment/setup_local.sh b/scripts/deployment/setup_local.sh deleted file mode 100755 index 5f162e0251f5ddcfdb75f7d906626432a23ff5f9..0000000000000000000000000000000000000000 --- a/scripts/deployment/setup_local.sh +++ /dev/null @@ -1,245 +0,0 @@ -#!/usr/bin/env bash -# ═══════════════════════════════════════════════════════════════════════ -# YAZ Platform β€” Local Auto-Start Setup -# ═══════════════════════════════════════════════════════════════════════ -# -# Installs systemd user services so YAZ starts automatically when you -# log in, and optionally opens a Cloudflare Tunnel for external access. -# -# Usage: -# ./setup_local.sh install # Install services -# ./setup_local.sh uninstall # Remove services -# ./setup_local.sh status # Check status -# ./setup_local.sh logs # View logs -# -# What it does: -# 1. yaz-server.service β€” Starts YAZ on login, restarts on crash -# 2. yaz-tunnel.service β€” Optional Cloudflare Tunnel for HTTPS -# -# ═══════════════════════════════════════════════════════════════════════ -set -euo pipefail - -YAZ_ROOT="$(cd "$(dirname "$0")/../.." && pwd)" -YAZ_PORT="${YAZ_PORT:-8000}" -VENV="$YAZ_ROOT/.venv" -SERVICE_DIR="$HOME/.config/systemd/user" - -G='\033[0;32m' Y='\033[1;33m' R='\033[0;31m' C='\033[0;36m' N='\033[0m' - -ok() { echo -e "${G}βœ… $*${N}"; } -warn() { echo -e "${Y}⚠️ $*${N}"; } -err() { echo -e "${R}❌ $*${N}"; } - -# ─── Install ────────────────────────────────────────────────────────── -install_services() { - echo -e "${C}═══ Installing YAZ Local Services ═══${N}\n" - - # Verify venv exists - if [[ ! -f "$VENV/bin/python3" ]]; then - err "Virtual environment not found at $VENV" - echo " Run: python3 -m venv .venv && source .venv/bin/activate && pip install -r requirements.txt" - exit 1 - fi - - mkdir -p "$SERVICE_DIR" - - # ── Service 1: YAZ Server ── - cat > "$SERVICE_DIR/yaz-server.service" << EOF -[Unit] -Description=YAZ Platform β€” Healthcare Intelligence Server -After=network-online.target -Wants=network-online.target - -[Service] -Type=simple -WorkingDirectory=$YAZ_ROOT -Environment=PYTHONPATH=$YAZ_ROOT/src:$YAZ_ROOT -Environment=ENVIRONMENT=development -Environment=YAZ_PORT=$YAZ_PORT -ExecStart=$VENV/bin/python3 main.py serve --host 0.0.0.0 --port $YAZ_PORT -Restart=on-failure -RestartSec=5 -StartLimitBurst=5 -StartLimitIntervalSec=60 - -# Logging -StandardOutput=append:$YAZ_ROOT/logs/server.log -StandardError=append:$YAZ_ROOT/logs/server-error.log - -# Graceful shutdown -TimeoutStopSec=15 -KillMode=mixed -KillSignal=SIGINT - -[Install] -WantedBy=default.target -EOF - ok "Created yaz-server.service" - - # ── Service 2: Cloudflare Tunnel (optional) ── - local CLOUDFLARED="$HOME/.local/bin/cloudflared" - cat > "$SERVICE_DIR/yaz-tunnel.service" << EOF -[Unit] -Description=YAZ Platform β€” Cloudflare Tunnel (HTTPS Access) -After=yaz-server.service -Requires=yaz-server.service -# Wait for server to be ready -ExecStartPre=/bin/bash -c 'for i in \$(seq 1 30); do curl -sf http://localhost:$YAZ_PORT/health && exit 0; sleep 1; done; exit 1' - -[Service] -Type=simple -ExecStart=$CLOUDFLARED tunnel --url http://localhost:$YAZ_PORT --no-autoupdate -Restart=on-failure -RestartSec=10 -StartLimitBurst=3 -StartLimitIntervalSec=120 - -StandardOutput=append:$YAZ_ROOT/logs/tunnel.log -StandardError=append:$YAZ_ROOT/logs/tunnel-error.log - -TimeoutStopSec=10 - -[Install] -WantedBy=default.target -EOF - ok "Created yaz-tunnel.service" - - # ── Timer: Daily DB Backup ── - cat > "$SERVICE_DIR/yaz-backup.service" << EOF -[Unit] -Description=YAZ Platform β€” Daily Database Backup - -[Service] -Type=oneshot -WorkingDirectory=$YAZ_ROOT -ExecStart=/bin/bash -c 'mkdir -p data/databases/backups && sqlite3 data/databases/yaz_care.db ".backup data/databases/backups/yaz_care_\$(date +%%Y%%m%%d).db" && gzip -f data/databases/backups/yaz_care_\$(date +%%Y%%m%%d).db && find data/databases/backups -name "*.gz" -mtime +7 -delete' -EOF - - cat > "$SERVICE_DIR/yaz-backup.timer" << EOF -[Unit] -Description=YAZ Platform β€” Daily Backup Timer - -[Timer] -OnCalendar=*-*-* 02:00:00 -Persistent=true - -[Install] -WantedBy=timers.target -EOF - ok "Created yaz-backup.timer (daily at 2 AM)" - - # ── Enable services ── - systemctl --user daemon-reload - systemctl --user enable yaz-server.service - ok "Enabled yaz-server (auto-start on login)" - - # Enable lingering so services run even when not logged in - if command -v loginctl &>/dev/null; then - loginctl enable-linger "$USER" 2>/dev/null || true - ok "Enabled user linger (services run without active session)" - fi - - echo "" - echo -e "${Y}Optional services:${N}" - read -rp " Enable Cloudflare Tunnel? [y/N] " yn_tunnel - if [[ "${yn_tunnel:-n}" =~ ^[Yy]$ ]]; then - # Ensure cloudflared is installed - if [[ ! -x "$CLOUDFLARED" ]]; then - echo -e "${Y}Installing cloudflared...${N}" - mkdir -p ~/.local/bin - curl -fsSL -o "$CLOUDFLARED" \ - https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64 - chmod +x "$CLOUDFLARED" - fi - systemctl --user enable yaz-tunnel.service - ok "Enabled Cloudflare Tunnel (auto-start after server)" - fi - - read -rp " Enable daily DB backup? [Y/n] " yn_backup - if [[ "${yn_backup:-Y}" =~ ^[Yy]$ ]]; then - systemctl --user enable yaz-backup.timer - systemctl --user start yaz-backup.timer - ok "Enabled daily backup timer" - fi - - echo "" - echo -e "${G}═══ Installation Complete ═══${N}" - echo -e " Start now: ${C}systemctl --user start yaz-server${N}" - echo -e " View logs: ${C}journalctl --user -u yaz-server -f${N}" - echo -e " Check status: ${C}$0 status${N}" - echo "" - - read -rp "Start YAZ now? [Y/n] " yn_start - if [[ "${yn_start:-Y}" =~ ^[Yy]$ ]]; then - systemctl --user start yaz-server - sleep 2 - show_status - fi -} - -# ─── Uninstall ──────────────────────────────────────────────────────── -uninstall_services() { - echo -e "${Y}Removing YAZ services...${N}" - - for svc in yaz-server yaz-tunnel; do - systemctl --user stop "$svc" 2>/dev/null || true - systemctl --user disable "$svc" 2>/dev/null || true - rm -f "$SERVICE_DIR/$svc.service" - done - - systemctl --user stop yaz-backup.timer 2>/dev/null || true - systemctl --user disable yaz-backup.timer 2>/dev/null || true - rm -f "$SERVICE_DIR/yaz-backup.service" "$SERVICE_DIR/yaz-backup.timer" - - systemctl --user daemon-reload - ok "All YAZ services removed" -} - -# ─── Status ─────────────────────────────────────────────────────────── -show_status() { - echo -e "${C}═══ YAZ Local Services ═══${N}\n" - - for svc in yaz-server yaz-tunnel; do - local status - status=$(systemctl --user is-active "$svc" 2>/dev/null || echo "inactive") - if [[ "$status" == "active" ]]; then - echo -e " $svc: ${G}● active${N}" - else - echo -e " $svc: ${R}β—‹ $status${N}" - fi - done - - local timer_status - timer_status=$(systemctl --user is-active yaz-backup.timer 2>/dev/null || echo "inactive") - echo -e " yaz-backup: ${timer_status == "active" && echo "${G}● active" || echo "${R}β—‹ $timer_status"}${N}" - - echo "" - if curl -sf -o /dev/null --max-time 2 "http://localhost:$YAZ_PORT/health"; then - echo -e " HTTP: ${G}http://localhost:$YAZ_PORT${N} βœ“" - else - echo -e " HTTP: ${R}Not responding${N}" - fi - - if [[ -f "$YAZ_ROOT/logs/tunnel.log" ]]; then - local url - url=$(grep -oP 'https://[a-z0-9-]+\.trycloudflare\.com' "$YAZ_ROOT/logs/tunnel.log" 2>/dev/null | tail -1 || true) - [[ -n "$url" ]] && echo -e " Tunnel: ${C}$url${N}" - fi -} - -# ─── Logs ───────────────────────────────────────────────────────────── -show_logs() { - echo -e "${C}═══ YAZ Server Logs (Ctrl+C to stop) ═══${N}\n" - journalctl --user -u yaz-server -f --no-hostname 2>/dev/null || \ - tail -f "$YAZ_ROOT/logs/server.log" 2>/dev/null || \ - echo "No logs available yet" -} - -# ─── Main ───────────────────────────────────────────────────────────── -case "${1:-install}" in - install) install_services ;; - uninstall) uninstall_services ;; - status) show_status ;; - logs) show_logs ;; - *) echo "Usage: $0 [install|uninstall|status|logs]" ;; -esac