Skip to main content

repti-core Service

Foundation service that supports all other domains
Service Type: Foundation/Core Service
Port: 8001
Database: repti_core_db
Status: Active Development
Team Owner: Platform Team

Purpose & Responsibilities

repti-core serves as the foundational service for the entire ReptiDex platform, providing essential infrastructure capabilities that all other services depend on.

Core Responsibilities

Authentication & Authorization

  • Identity & access management (users, organizations, sessions)
  • JWT token generation and validation
  • Role-based access control (RBAC)
  • API key management for service integration
  • Multi-factor authentication support

Configuration Management

  • Application configuration management
  • Feature flags and A/B testing
  • Environment-specific settings
  • Service configuration distribution
  • Real-time configuration updates

Event Orchestration

  • Event bus coordination and routing
  • Async processing job scheduling
  • Event publishing and subscription management
  • Cross-service event correlation
  • Event sourcing for audit trails

Billing & Subscriptions

  • Subscription lifecycle management
  • Payment processing coordination (Stripe/PayPal)
  • Invoice generation and tracking
  • Usage-based billing calculations
  • Dunning and retry logic

Telemetry & Monitoring

  • Application telemetry collection
  • Performance metrics aggregation
  • User behavior analytics
  • System health monitoring
  • Custom business metrics tracking

API Endpoints

Authentication Endpoints

POST   /auth/login              # User authentication
POST   /auth/logout             # Session termination
POST   /auth/register           # User registration
GET    /auth/me                 # Current user profile
POST   /auth/refresh            # Token refresh
POST   /auth/forgot-password    # Password reset initiation
POST   /auth/reset-password     # Password reset completion

Vivarium (Organization) Management

GET    /vivariums               # List user vivariums
POST   /vivariums               # Create new vivarium
GET    /vivariums/{vivarium_id} # Vivarium details
PUT    /vivariums/{vivarium_id} # Update vivarium
POST   /vivariums/{vivarium_id}/members     # Add vivarium member
PUT    /vivariums/{vivarium_id}/members/{user_id}  # Update member role
DELETE /vivariums/{vivarium_id}/members/{user_id}  # Remove member
GET    /vivariums/{vivarium_id}/roles       # List available roles

Configuration Endpoints

GET    /config/features         # Feature flag retrieval
GET    /config/app              # Application configuration
PUT    /config/features/{flag}  # Update feature flag (admin)

Billing Endpoints

GET    /billing/subscriptions   # Subscription management
POST   /billing/subscriptions   # Create subscription
GET    /billing/invoices        # Invoice history
POST   /billing/payment-methods # Add payment method

Event Management

POST   /events/publish          # Event publishing
GET    /events/health           # Event system health
GET    /events/metrics          # Event processing metrics

Database Schema

Core Tables

-- Users table
CREATE TABLE users (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    email VARCHAR(255) UNIQUE NOT NULL,
    password_hash VARCHAR(255) NOT NULL,
    first_name VARCHAR(100),
    last_name VARCHAR(100),
    email_verified BOOLEAN DEFAULT FALSE,
    is_active BOOLEAN DEFAULT TRUE,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- User sessions
CREATE TABLE user_sessions (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID REFERENCES users(id) ON DELETE CASCADE,
    token_hash VARCHAR(255) NOT NULL,
    expires_at TIMESTAMP WITH TIME ZONE NOT NULL,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- API keys for service integration
CREATE TABLE api_keys (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID REFERENCES users(id) ON DELETE CASCADE,
    name VARCHAR(100) NOT NULL,
    key_hash VARCHAR(255) NOT NULL,
    permissions JSONB DEFAULT '[]',
    last_used_at TIMESTAMP WITH TIME ZONE,
    expires_at TIMESTAMP WITH TIME ZONE,
    is_active BOOLEAN DEFAULT TRUE,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

Vivarium Role Definitions

reptidex uses husbandry-themed role names that map to traditional RBAC permissions:
  • Keeper (Viewer): Read-only access to animals, pedigrees, and clutches
  • Handler (Editor): Can add/update animals, pairings, clutches, and media
  • Curator (Admin): Manages vivarium data and members, cannot change billing
  • Herpetologist (Owner): Full rights including deleting vivarium and managing subscriptions

Database Schema

-- Vivarium role enumeration
CREATE TYPE vivarium_role_enum AS ENUM (
    'keeper',        -- Read-only access (Viewer)
    'handler',       -- Editor permissions
    'curator',       -- Admin permissions  
    'herpetologist'  -- Owner permissions
);

-- Vivariums (Organizations)
CREATE TABLE vivariums (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    name VARCHAR(255) NOT NULL,
    slug VARCHAR(100) UNIQUE NOT NULL,
    description TEXT,
    settings JSONB DEFAULT '{}',
    subscription_tier VARCHAR(50) DEFAULT 'free',
    owner_id UUID REFERENCES users(id) NOT NULL,
    is_active BOOLEAN DEFAULT TRUE,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Vivarium memberships with roles
CREATE TABLE vivarium_members (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    vivarium_id UUID REFERENCES vivariums(id) ON DELETE CASCADE,
    user_id UUID REFERENCES users(id) ON DELETE CASCADE,
    role vivarium_role_enum NOT NULL DEFAULT 'keeper',
    permissions JSONB DEFAULT '{}',
    invited_by UUID REFERENCES users(id),
    joined_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    UNIQUE(vivarium_id, user_id)
);

-- Role change audit log
CREATE TABLE vivarium_role_audit (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    vivarium_id UUID REFERENCES vivariums(id) ON DELETE CASCADE,
    target_user_id UUID REFERENCES users(id) ON DELETE CASCADE,
    changed_by_user_id UUID REFERENCES users(id) ON DELETE CASCADE,
    old_role vivarium_role_enum,
    new_role vivarium_role_enum NOT NULL,
    reason TEXT,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Role permissions matrix
CREATE TABLE role_permissions (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    role vivarium_role_enum NOT NULL,
    resource VARCHAR(50) NOT NULL,
    action VARCHAR(30) NOT NULL,
    allowed BOOLEAN DEFAULT FALSE,
    conditions JSONB DEFAULT '{}',
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
-- Feature flags
CREATE TABLE feature_flags (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    name VARCHAR(100) UNIQUE NOT NULL,
    description TEXT,
    is_enabled BOOLEAN DEFAULT FALSE,
    rollout_percentage INTEGER DEFAULT 0,
    conditions JSONB DEFAULT '{}',
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Application configuration
CREATE TABLE app_config (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    key VARCHAR(100) UNIQUE NOT NULL,
    value JSONB NOT NULL,
    environment VARCHAR(50) DEFAULT 'production',
    description TEXT,
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

Event Publishing & Subscriptions

Published Events

Authentication Events:
  • auth.user.created - New user registration
  • auth.user.updated - User profile changes
  • auth.session.started - User login
  • auth.session.ended - User logout
  • auth.password.changed - Password updates
Organization Events:
  • org.created - New organization created
  • org.updated - Organization details changed
  • org.member.added - New member joined
  • org.member.removed - Member left organization
  • org.member.role.changed - Member role updated
Configuration Events:
  • config.updated - Configuration changes
  • config.feature.toggled - Feature flag changes
Billing Events:
  • billing.subscription.created - New subscription
  • billing.subscription.updated - Subscription changes
  • billing.invoice.created - Invoice generation
  • billing.payment.succeeded - Successful payment
  • billing.payment.failed - Failed payment

Event Subscriptions

repti-core subscribes to events from all services for:
  • Telemetry Collection: Aggregating metrics from all services
  • Audit Logging: Recording all system events for compliance
  • System Health: Monitoring service health and performance
  • Usage Tracking: Calculating usage for billing purposes

External Dependencies

Payment Processing

  • Stripe: Primary payment processor
  • PayPal: Alternative payment method
  • Webhooks: Payment status updates and subscription events

Infrastructure

  • AWS KMS: Encryption key management
  • AWS SNS/SQS: Event infrastructure
  • Redis: Session storage and caching

Optional Integrations

  • OAuth Providers: Google, GitHub SSO
  • Email Providers: Transactional email via integrations

Security Implementation

Authentication Security

  • JWT Tokens: RS256 signatures with KMS-backed keys
  • Refresh Token Rotation: Enhanced security for long-lived sessions
  • Rate Limiting: Protection against brute force attacks
  • Password Security: bcrypt hashing with configurable rounds

Authorization Framework

  • Row-Level Security: Organization-scoped data access
  • Role-Based Access Control: Flexible permission system
  • API Key Management: Service-to-service authentication
  • Audit Logging: Complete access logs for compliance

Performance & Scaling

Caching Strategy

  • Session Cache: Redis for active user sessions
  • Configuration Cache: In-memory caching with TTL
  • Feature Flag Cache: Fast feature flag evaluation
  • JWT Validation Cache: Cached public key validation

Database Optimization

  • Connection Pooling: Efficient database connections
  • Query Optimization: Indexed queries for performance
  • Read Replicas: Scaling read operations
  • Partitioning: Large table optimization strategies

Monitoring & Observability

Key Metrics

  • Authentication Rate: Login success/failure rates
  • API Response Times: Service performance tracking
  • Event Processing: Event publication and consumption rates
  • Database Performance: Query performance and connection health

Health Checks

GET /health         # Basic service health
GET /health/deep    # Database and dependency checks
GET /metrics        # Prometheus metrics for Grafana

Alerting

  • Authentication Failures: High failure rate alerts
  • Database Performance: Slow query detection
  • Event Processing: Queue backup alerts
  • External Service: Dependency failure notifications

Development Guidelines

Code Standards

  • FastAPI Framework: Python 3.11+ with type hints
  • Pydantic Models: Request/response validation
  • Alembic Migrations: Database schema management
  • pytest Testing: Comprehensive test coverage

Deployment

  • Docker Container: Containerized deployment
  • Environment Variables: Configuration via env vars
  • Health Checks: Container health monitoring
  • Rolling Updates: Zero-downtime deployments

repti-core is the foundational service that enables all other ReptiDex services. Its reliability and performance are critical to the entire platform’s operation.