Skip to main content

repti-ops Service

Operations and administrative functionality
Service Type: Operations & Administration Service
Port: 8006
Database: repti_ops_db
Status: Planned
Team Owner: Operations Team

Purpose & Responsibilities

repti-ops provides the operational backbone for ReptiDex, handling administration, compliance, integrations, and system monitoring to ensure platform reliability and regulatory compliance.

Core Responsibilities

Administrative Tools

  • Admin dashboard and control panels
  • User and organization management
  • Content moderation and review
  • System configuration management
  • Feature flag and rollout control

Audit & Compliance

  • Complete audit logging and trails
  • GDPR and CCPA compliance tools
  • Data export and deletion workflows
  • Regulatory reporting and documentation
  • SOC2 compliance framework

System Monitoring

  • Application performance monitoring
  • System health and alerting
  • Business metrics and dashboards
  • SLA monitoring and reporting
  • Incident response coordination

Third-Party Integrations

  • External API management
  • Webhook handling and processing
  • Data synchronization pipelines
  • Partner marketplace integrations
  • Legacy system migrations

API Endpoints

Administrative Dashboard

GET    /admin/dashboard                 # Main admin dashboard
GET    /admin/users                     # User management
PUT    /admin/users/{user_id}/status    # Update user status
GET    /admin/organizations             # Organization overview
PUT    /admin/organizations/{org_id}/settings # Update org settings
GET    /admin/content/reports           # Content moderation queue
POST   /admin/content/moderate          # Moderate content
GET    /admin/system/config             # System configuration
PUT    /admin/system/config             # Update system settings

User & Organization Management

GET    /admin/users/search              # Search users
POST   /admin/users/impersonate         # Admin impersonation
GET    /admin/users/{user_id}/activity  # User activity logs
POST   /admin/users/{user_id}/suspend   # Suspend user account
POST   /admin/users/{user_id}/verify    # Verify user account
GET    /admin/organizations/{org_id}/members # Org member management
POST   /admin/organizations/merge       # Merge organizations
GET    /admin/billing/subscriptions     # Billing overview

Audit & Compliance

GET    /audit/logs                      # Audit log retrieval
POST   /audit/export                    # Export audit data
GET    /compliance/gdpr/requests        # GDPR data requests
POST   /compliance/gdpr/export          # Export user data
POST   /compliance/gdpr/delete          # Delete user data
GET    /compliance/reports              # Compliance reports
POST   /compliance/soc2/evidence        # SOC2 evidence collection
GET    /audit/trail/{entity_id}         # Entity audit trail

System Monitoring

GET    /monitoring/health               # System health overview
GET    /monitoring/services             # Service status dashboard
GET    /monitoring/metrics              # Key performance metrics
POST   /monitoring/alerts               # Create custom alerts
GET    /monitoring/incidents            # Incident management
POST   /monitoring/incidents            # Create incident
PUT    /monitoring/incidents/{id}/resolve # Resolve incident
GET    /monitoring/sla                  # SLA compliance tracking

Integration Management

GET    /integrations                    # List active integrations
POST   /integrations/configure          # Setup new integration
PUT    /integrations/{integration_id}   # Update integration settings
DELETE /integrations/{integration_id}   # Remove integration
POST   /integrations/sync               # Trigger data sync
GET    /integrations/{id}/logs          # Integration activity logs
POST   /webhooks/register               # Register webhook endpoint
GET    /webhooks/deliveries             # Webhook delivery status

Database Schema

Core Tables

-- Admin users and permissions
CREATE TABLE admin_users (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID UNIQUE NOT NULL, -- References repti-core users
    admin_level VARCHAR(20) NOT NULL, -- 'support', 'admin', 'super_admin'
    permissions JSONB DEFAULT '[]',
    created_by UUID,
    is_active BOOLEAN DEFAULT TRUE,
    last_login_at TIMESTAMP WITH TIME ZONE,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Admin actions log
CREATE TABLE admin_actions (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    admin_user_id UUID REFERENCES admin_users(id),
    action_type VARCHAR(100) NOT NULL,
    target_entity_type VARCHAR(50),
    target_entity_id UUID,
    action_details JSONB DEFAULT '{}',
    ip_address INET,
    user_agent TEXT,
    performed_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Content moderation queue
CREATE TABLE moderation_queue (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    content_type VARCHAR(50) NOT NULL, -- 'post', 'listing', 'profile', 'image'
    content_id UUID NOT NULL,
    reported_by UUID,
    report_reason VARCHAR(100),
    report_details TEXT,
    status VARCHAR(20) DEFAULT 'pending',
    assigned_to UUID REFERENCES admin_users(id),
    reviewed_by UUID REFERENCES admin_users(id),
    review_notes TEXT,
    resolution VARCHAR(50),
    priority INTEGER DEFAULT 5,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    reviewed_at TIMESTAMP WITH TIME ZONE
);
-- Comprehensive audit log
CREATE TABLE audit_logs (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    event_id UUID UNIQUE NOT NULL DEFAULT gen_random_uuid(),
    service_name VARCHAR(50) NOT NULL,
    event_type VARCHAR(100) NOT NULL,
    entity_type VARCHAR(50),
    entity_id UUID,
    user_id UUID,
    organization_id UUID,
    event_data JSONB NOT NULL,
    metadata JSONB DEFAULT '{}',
    ip_address INET,
    user_agent TEXT,
    timestamp TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    correlation_id UUID
);

-- GDPR data requests
CREATE TABLE gdpr_requests (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID NOT NULL,
    request_type VARCHAR(20) NOT NULL, -- 'export', 'delete', 'rectification'
    request_details JSONB DEFAULT '{}',
    status VARCHAR(20) DEFAULT 'pending',
    requested_by UUID NOT NULL,
    processed_by UUID REFERENCES admin_users(id),
    completion_date TIMESTAMP WITH TIME ZONE,
    export_file_id UUID, -- Reference to generated export file
    verification_token VARCHAR(255),
    notes TEXT,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Compliance evidence collection
CREATE TABLE compliance_evidence (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    compliance_framework VARCHAR(50) NOT NULL, -- 'SOC2', 'GDPR', 'CCPA'
    control_id VARCHAR(100) NOT NULL,
    evidence_type VARCHAR(50) NOT NULL,
    description TEXT NOT NULL,
    evidence_data JSONB DEFAULT '{}',
    file_attachments JSONB DEFAULT '[]',
    collected_by UUID REFERENCES admin_users(id),
    review_status VARCHAR(20) DEFAULT 'pending',
    reviewed_by UUID REFERENCES admin_users(id),
    review_notes TEXT,
    collection_period_start DATE,
    collection_period_end DATE,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
-- System health metrics
CREATE TABLE system_metrics (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    service_name VARCHAR(50) NOT NULL,
    metric_name VARCHAR(100) NOT NULL,
    metric_value DECIMAL(12,4) NOT NULL,
    metric_unit VARCHAR(20),
    tags JSONB DEFAULT '{}',
    timestamp TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Service status tracking
CREATE TABLE service_status (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    service_name VARCHAR(50) UNIQUE NOT NULL,
    status VARCHAR(20) NOT NULL, -- 'healthy', 'degraded', 'down'
    health_score DECIMAL(3,2) DEFAULT 1.0,
    last_check_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    response_time_ms INTEGER,
    error_rate DECIMAL(5,4) DEFAULT 0.0,
    uptime_percentage DECIMAL(5,2) DEFAULT 100.0,
    metadata JSONB DEFAULT '{}',
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Incident management
CREATE TABLE incidents (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    incident_number VARCHAR(50) UNIQUE NOT NULL,
    title VARCHAR(255) NOT NULL,
    description TEXT,
    severity VARCHAR(20) NOT NULL, -- 'low', 'medium', 'high', 'critical'
    status VARCHAR(20) DEFAULT 'open',
    affected_services VARCHAR(255)[] DEFAULT '{}',
    reported_by UUID,
    assigned_to UUID REFERENCES admin_users(id),
    root_cause TEXT,
    resolution TEXT,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    resolved_at TIMESTAMP WITH TIME ZONE,
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- SLA tracking
CREATE TABLE sla_metrics (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    service_name VARCHAR(50) NOT NULL,
    metric_type VARCHAR(50) NOT NULL, -- 'uptime', 'response_time', 'availability'
    target_value DECIMAL(8,4) NOT NULL,
    actual_value DECIMAL(8,4) NOT NULL,
    compliance_percentage DECIMAL(5,2),
    measurement_period_start TIMESTAMP WITH TIME ZONE NOT NULL,
    measurement_period_end TIMESTAMP WITH TIME ZONE NOT NULL,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
-- Third-party integrations
CREATE TABLE integrations (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    name VARCHAR(100) NOT NULL,
    integration_type VARCHAR(50) NOT NULL, -- 'webhook', 'api', 'data_sync'
    provider VARCHAR(100) NOT NULL,
    configuration JSONB NOT NULL,
    credentials_encrypted TEXT, -- Encrypted API keys/secrets
    status VARCHAR(20) DEFAULT 'active',
    last_sync_at TIMESTAMP WITH TIME ZONE,
    sync_frequency VARCHAR(50), -- 'hourly', 'daily', 'weekly', 'manual'
    error_count INTEGER DEFAULT 0,
    last_error TEXT,
    created_by UUID REFERENCES admin_users(id),
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Integration activity logs
CREATE TABLE integration_logs (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    integration_id UUID REFERENCES integrations(id) ON DELETE CASCADE,
    operation VARCHAR(100) NOT NULL,
    status VARCHAR(20) NOT NULL, -- 'success', 'failure', 'partial'
    records_processed INTEGER DEFAULT 0,
    records_failed INTEGER DEFAULT 0,
    execution_time_ms INTEGER,
    error_details JSONB,
    log_data JSONB DEFAULT '{}',
    started_at TIMESTAMP WITH TIME ZONE NOT NULL,
    completed_at TIMESTAMP WITH TIME ZONE
);

-- Webhook endpoints and deliveries
CREATE TABLE webhook_endpoints (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    organization_id UUID,
    url VARCHAR(500) NOT NULL,
    events VARCHAR(100)[] NOT NULL,
    secret_key VARCHAR(255),
    is_active BOOLEAN DEFAULT TRUE,
    retry_config JSONB DEFAULT '{}',
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

CREATE TABLE webhook_deliveries (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    endpoint_id UUID REFERENCES webhook_endpoints(id) ON DELETE CASCADE,
    event_type VARCHAR(100) NOT NULL,
    payload JSONB NOT NULL,
    status VARCHAR(20) DEFAULT 'pending',
    response_status_code INTEGER,
    response_body TEXT,
    attempt_count INTEGER DEFAULT 0,
    max_attempts INTEGER DEFAULT 3,
    next_retry_at TIMESTAMP WITH TIME ZONE,
    delivered_at TIMESTAMP WITH TIME ZONE,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

Event Publishing & Subscriptions

Published Events

Administrative Events:
  • admin.action.performed - Admin action executed
  • admin.user.created - New admin user added
  • admin.content.moderated - Content moderation decision
  • admin.system.configured - System configuration changed
Audit Events:
  • audit.logged - Event recorded in audit log
  • audit.export.requested - Audit data export initiated
  • compliance.request.created - GDPR/CCPA request received
  • compliance.evidence.collected - Compliance evidence gathered
Monitoring Events:
  • monitoring.alert.triggered - System alert fired
  • monitoring.incident.created - New incident reported
  • monitoring.service.down - Service availability issue
  • monitoring.sla.violated - SLA threshold breached
Integration Events:
  • integration.sync.started - Data sync initiated
  • integration.sync.completed - Sync finished successfully
  • integration.error.occurred - Integration failure
  • webhook.delivered - Webhook successfully sent

Event Subscriptions

repti-ops subscribes to ALL service events for:
  • Audit Logging: Complete system audit trail
  • System Monitoring: Service health and performance tracking
  • Compliance Tracking: User action monitoring for GDPR/CCPA
  • Business Intelligence: Platform usage and analytics

Administrative Features

User Management Dashboard

async def get_admin_dashboard_data(admin_user_id: UUID):
    """
    Generate comprehensive admin dashboard with key metrics
    """
    dashboard_data = {
        "user_metrics": {
            "total_users": await count_total_users(),
            "active_users_30d": await count_active_users(days=30),
            "new_registrations_7d": await count_new_users(days=7),
            "suspended_users": await count_suspended_users()
        },
        "organization_metrics": {
            "total_organizations": await count_organizations(),
            "active_subscriptions": await count_active_subscriptions(),
            "trial_organizations": await count_trial_organizations(),
            "overdue_payments": await count_overdue_payments()
        },
        "content_metrics": {
            "pending_moderation": await count_pending_moderation(),
            "animals_created_7d": await count_animals_created(days=7),
            "listings_created_7d": await count_listings_created(days=7),
            "community_posts_7d": await count_posts_created(days=7)
        },
        "system_health": {
            "services_status": await get_all_service_status(),
            "critical_alerts": await get_critical_alerts(),
            "sla_compliance": await get_sla_compliance_summary(),
            "recent_incidents": await get_recent_incidents(limit=5)
        }
    }
    
    # Log admin dashboard access
    await log_admin_action(
        admin_user_id, 
        "dashboard.accessed", 
        metadata={"timestamp": datetime.utcnow()}
    )
    
    return dashboard_data

GDPR Compliance Engine

async def process_gdpr_request(request_id: UUID):
    """
    Process GDPR data export or deletion request
    """
    request = await get_gdpr_request(request_id)
    
    if request.request_type == "export":
        # Collect user data from all services
        user_data = {}
        
        # Core user data
        user_data["profile"] = await fetch_user_profile(request.user_id)
        user_data["authentication"] = await fetch_auth_data(request.user_id)
        
        # Animal and breeding data
        user_data["animals"] = await fetch_user_animals(request.user_id)
        user_data["breeding_records"] = await fetch_breeding_records(request.user_id)
        
        # Commerce data
        user_data["marketplace_activity"] = await fetch_commerce_data(request.user_id)
        user_data["transactions"] = await fetch_transaction_history(request.user_id)
        
        # Community data
        user_data["forum_posts"] = await fetch_community_posts(request.user_id)
        user_data["notifications"] = await fetch_notification_history(request.user_id)
        
        # Generate export file
        export_file = await generate_gdpr_export(user_data)
        
        # Update request status
        await update_gdpr_request(request_id, {
            "status": "completed",
            "export_file_id": export_file.id,
            "completion_date": datetime.utcnow()
        })
        
        # Send notification to user
        await send_gdpr_completion_notification(request.user_id, export_file.download_url)
    
    elif request.request_type == "delete":
        # Orchestrate data deletion across all services
        deletion_tasks = [
            delete_user_profile_data(request.user_id),
            delete_user_animals(request.user_id),
            delete_user_commerce_data(request.user_id),
            delete_user_community_data(request.user_id),
            anonymize_user_audit_logs(request.user_id)
        ]
        
        await asyncio.gather(*deletion_tasks)
        
        # Mark request as completed
        await update_gdpr_request(request_id, {
            "status": "completed",
            "completion_date": datetime.utcnow()
        })

System Monitoring & Alerting

Health Check Orchestration

async def monitor_system_health():
    """
    Comprehensive system health monitoring
    """
    services = ["repti-core", "repti-animal", "repti-commerce", 
               "repti-media", "repti-community", "repti-ops"]
    
    health_results = []
    
    for service in services:
        try:
            # Health check each service
            response = await check_service_health(service)
            
            health_data = {
                "service": service,
                "status": "healthy" if response.status_code == 200 else "degraded",
                "response_time_ms": response.response_time,
                "checks": response.checks,
                "timestamp": datetime.utcnow()
            }
            
            # Update service status
            await update_service_status(service, health_data)
            
            # Check for SLA violations
            await check_sla_compliance(service, health_data)
            
            health_results.append(health_data)
            
        except Exception as e:
            # Service is down
            health_data = {
                "service": service,
                "status": "down",
                "error": str(e),
                "timestamp": datetime.utcnow()
            }
            
            await update_service_status(service, health_data)
            await trigger_service_down_alert(service, str(e))
            
            health_results.append(health_data)
    
    # Calculate overall system health score
    overall_health = calculate_system_health_score(health_results)
    await update_system_metrics("overall_health", overall_health)
    
    return health_results

Performance & Scaling

Audit Log Management

  • Efficient Storage: Optimized storage for high-volume audit logs
  • Fast Retrieval: Indexed queries for audit trail searches
  • Data Retention: Automated archival and cleanup policies
  • Real-time Ingestion: High-throughput event processing

Monitoring Optimization

  • Metric Aggregation: Efficient time-series data storage
  • Alert Deduplication: Prevent alert spam and fatigue
  • Dashboard Caching: Fast admin dashboard loading
  • Incident Correlation: Automated incident detection and grouping

Integration Points

Internal Dependencies

  • repti-core: Authentication, events, system access
  • All Services: Audit logging, health monitoring, admin operations

External Services

  • Grafana: Application performance monitoring
  • CloudWatch: Infrastructure monitoring and logs
  • Email Services: Admin notifications and alerts
  • External APIs: Partner integrations and data sync

Security & Access Control

Admin Security

  • Role-Based Access: Granular admin permission system
  • Action Logging: Complete audit trail of admin actions
  • IP Restrictions: Admin access control by IP address
  • Multi-Factor Authentication: Required for admin accounts

Data Protection

  • Encrypted Storage: Sensitive configuration and credentials
  • Access Auditing: All data access logged and monitored
  • Compliance Controls: GDPR/CCPA automated compliance
  • Backup Security: Encrypted backups with access controls

Monitoring & Key Metrics

Operational Metrics

  • System Uptime: Service availability and reliability
  • Performance Metrics: Response times and throughput
  • Error Rates: System error tracking and analysis
  • Capacity Utilization: Resource usage and scaling needs

Business Metrics

  • User Growth: Registration and activation trends
  • Revenue Metrics: Subscription and payment tracking
  • Feature Adoption: Platform feature usage analytics
  • Support Metrics: Issue resolution and user satisfaction

Compliance Metrics

  • Audit Coverage: Complete event logging verification
  • Data Requests: GDPR/CCPA request processing times
  • Security Incidents: Security event tracking and response
  • Compliance Score: Overall regulatory compliance health

repti-ops serves as the operational foundation that keeps ReptiDex running smoothly, secure, and compliant while providing administrators with the tools they need to manage and monitor the entire platform.