Files
rxminder/config
William Valentin bf36f14eab fix(config): resolve circular import in unified config
- Replace direct logger import with dynamic import pattern
- Add withLogger utility to handle async logger initialization
- Prevent module loading issues during configuration bootstrap
- Maintain logging functionality while avoiding circular dependencies
2025-10-16 13:16:25 -07:00
..

Unified Configuration System

This directory contains the unified configuration system for the RxMinder application. The unified config provides a single source of truth for all application settings across different environments and deployment targets.

Overview

The unified configuration system serves as the single source of truth for all application configuration. It reads from your .env file for environment-specific overrides and provides a centralized, type-safe, and environment-aware configuration system.

Key Benefits

  • 🎯 Single Source of Truth: Unified config with .env file overrides
  • 🔒 Type Safety: Full TypeScript support with interfaces
  • 🌍 Environment Aware: Reads from .env file for environment-specific settings
  • 🚀 Auto-Generation: Generates all necessary config files automatically
  • 🔄 Simplified Architecture: Clean, maintainable configuration management
  • 📝 Self-Documenting: Clear structure with validation and debugging tools

File Structure

config/
├── README.md                    # This documentation
├── unified.config.ts           # Single source of truth configuration
└── generated/                 # Auto-generated configs
    ├── development.config.ts
    ├── staging.config.ts
    └── production.config.ts

Quick Start

1. Using the Unified Config

import { unifiedConfig, isProduction, featureFlags } from './config/unified.config';

// Access configuration
const dbUrl = unifiedConfig.database.url;
const appName = unifiedConfig.app.name;

// Use convenience exports
if (isProduction()) {
  // Production-specific logic
}

if (featureFlags.enableOAuth) {
  // OAuth-enabled logic
}

2. Environment Variables (.env file)

The system reads from your .env file as the primary source for environment-specific overrides:

# .env file - Primary configuration source
APP_NAME=rxminder
NODE_ENV=production
VITE_COUCHDB_URL=http://rxminder-couchdb-service:5984
VITE_COUCHDB_USER=admin
VITE_COUCHDB_PASSWORD=your-secure-password

# Container configuration
CONTAINER_REGISTRY=your-registry.com
CONTAINER_REPOSITORY=your-org/app

3. Generating Config Files

Generate configuration files for all environments:

# Generate for all environments
make generate-config

# Generate for specific environment
make generate-config-prod

# Validate configuration
make validate-config

# Debug current config
make config-debug

Configuration Structure

Application Settings

app: {
  name: string; // Application name
  version: string; // Version number
  environment: Environment; // Current environment
  baseUrl: string; // Base application URL
  port: number; // Server port
}

Database Configuration

database: {
  url: string; // Database connection URL
  username: string; // Database username
  password: string; // Database password
  name: string; // Database name
  useMock: boolean; // Use mock database for testing
  connectionTimeout: number;
  retryAttempts: number;
}

Kubernetes Configuration

kubernetes: {
  namespace: string; // K8s namespace
  ingressHost: string; // Ingress hostname
  replicas: {
    frontend: number; // Frontend replica count
    database: number; // Database replica count
  }
  resources: {
    frontend: ResourceLimits;
    database: ResourceLimits;
  }
}

Feature Flags

features: {
  enableEmailVerification: boolean;
  enableOAuth: boolean;
  enableAdminInterface: boolean;
  enableMonitoring: boolean;
  debugMode: boolean;
}

Environment Overrides

The system supports environment-specific overrides:

Development

  • Debug mode enabled
  • Lower resource limits
  • Console logging for emails
  • Hot reload enabled

Staging

  • Monitoring enabled
  • Production-like settings
  • Staging URLs
  • Moderate resource limits

Production

  • Security features enabled
  • Higher resource limits
  • Performance optimizations
  • Monitoring and metrics enabled

Environment Variables Reference

Core Application

  • APP_NAME - Application name (default: RxMinder)
  • APP_VERSION - Version number (default: 1.0.0)
  • APP_BASE_URL - Base URL (default: http://localhost:5173)
  • NODE_ENV - Environment (development/staging/production/test)

Database

  • VITE_COUCHDB_URL - CouchDB URL
  • VITE_COUCHDB_USER - CouchDB username
  • VITE_COUCHDB_PASSWORD - CouchDB password
  • USE_MOCK_DB - Use mock database (default: false)

Container & Deployment

  • CONTAINER_REGISTRY - Container registry URL
  • CONTAINER_REPOSITORY - Repository name
  • CONTAINER_TAG - Container tag
  • INGRESS_HOST - Kubernetes ingress host
  • STORAGE_CLASS - Kubernetes storage class
  • STORAGE_SIZE - Storage size (default: 1Gi)

Email Configuration

  • VITE_MAILGUN_API_KEY - Mailgun API key
  • VITE_MAILGUN_DOMAIN - Mailgun domain
  • VITE_MAILGUN_FROM_NAME - From name (default: RxMinder)
  • VITE_MAILGUN_FROM_EMAIL - From email address

OAuth Configuration

  • VITE_GOOGLE_CLIENT_ID - Google OAuth client ID
  • VITE_GITHUB_CLIENT_ID - GitHub OAuth client ID

Feature Flags

  • ENABLE_EMAIL_VERIFICATION - Enable email verification (default: true)
  • ENABLE_OAUTH - Enable OAuth (default: true)
  • ENABLE_ADMIN_INTERFACE - Enable admin interface (default: true)
  • ENABLE_MONITORING - Enable monitoring (default: false)
  • DEBUG_MODE - Enable debug mode (default: false)

Security & Performance

  • JWT_SECRET - JWT signing secret
  • LOG_LEVEL - Logging level (debug/info/warn/error)
  • CACHE_TTL - Cache timeout in seconds
  • REQUEST_TIMEOUT - Request timeout in milliseconds

Generated Files

The unified config system generates several files:

1. Environment Files

  • .env.development - Development environment variables
  • .env.staging - Staging environment variables
  • .env.production - Production environment variables

2. Kubernetes Configuration

  • k8s-kustomize/overlays/{env}/config.env - Kubernetes config for each environment
  • k8s-kustomize/overlays/{env}/kustomization.yaml - Updated kustomization files

3. Docker Configuration

  • docker/.env.{environment} - Docker-specific environment files

4. Vite Configuration

  • .env.vite.{environment} - Vite-specific variables

5. TypeScript Exports

  • config/generated/{environment}.config.ts - Type-safe config exports

Scripts

Generation Scripts

# Generate unified configuration
bun scripts/generate-unified-config.ts

# Generate for specific environment
bun scripts/generate-unified-config.ts production

# Generate for all environments
bun scripts/generate-unified-config.ts --all

# Dry run (preview changes)
bun scripts/generate-unified-config.ts --dry-run

# Verbose output
bun scripts/generate-unified-config.ts --verbose

Migration Scripts

# Generate configuration for all environments
bun scripts/generate-unified-config.ts --all

# Generate for specific environment
bun scripts/generate-unified-config.ts production

# Validate configuration
bun scripts/generate-unified-config.ts --dry-run

Working with the Configuration System

1. Basic Usage

Access configuration in your application:

import { unifiedConfig } from './config/unified.config';

const appName = unifiedConfig.app.name;
const dbUrl = unifiedConfig.database.url;

2. Environment Overrides

Add variables to your .env file:

APP_NAME=my-app
VITE_COUCHDB_URL=http://localhost:5984

3. Generate Configs

make generate-config

4. Test Application

make dev

5. Deploy

make deploy-prod-quick

Best Practices

1. Environment Variables

  • Use VITE_ prefix for frontend-accessible variables
  • Keep sensitive data in environment variables, not in code
  • Use meaningful defaults for non-sensitive configuration

2. Configuration Updates

  • Always regenerate config files after changing unified config
  • Test configuration changes in development first
  • Use the validation features to catch issues early

3. Secrets Management

  • Never commit secrets to version control
  • Use environment variables for all sensitive data
  • Consider using external secret management in production

4. Environment Consistency

  • Keep environment-specific overrides minimal
  • Document any environment-specific requirements
  • Test deployments in staging before production

Troubleshooting

Configuration Not Loading

  1. Check that NODE_ENV is set correctly
  2. Verify environment variables are accessible
  3. Run make config-debug to see current configuration
  4. Check for TypeScript compilation errors

Missing Environment Variables

  1. Check if variables are defined in .env file
  2. Verify variable names match the expected format
  3. Use make validate-config to identify missing required variables

Kubernetes Deployment Issues

  1. Regenerate Kubernetes configs: make generate-config-prod
  2. Check that namespace exists: kubectl get namespaces
  3. Verify config maps: kubectl get configmaps -n {namespace}

Build/Runtime Errors

  1. Ensure all VITE_ prefixed variables are available at build time
  2. Check Vite configuration for proper variable injection
  3. Verify TypeScript types are consistent

Development

Adding New Configuration

  1. Update the UnifiedConfig interface in unified.config.ts
  2. Add default values to defaultConfig
  3. Add environment-specific overrides if needed
  4. Update environment variable loading in loadFromEnvironment
  5. Regenerate configuration files

Adding New Environment

  1. Add environment to Environment type
  2. Add environment-specific config to environmentConfigs
  3. Update generation scripts to handle new environment
  4. Create Kubernetes overlay directory structure

Security Considerations

  • JWT secrets must be changed in production
  • Database passwords should be strong and unique
  • API keys should be rotated regularly
  • Use HTTPS in production environments
  • Enable security headers in production

Performance Considerations

  • Cache timeouts should be appropriate for your use case
  • Resource limits should match your infrastructure
  • Monitor application performance in different environments
  • Adjust replica counts based on load requirements

Support

For questions or issues with the unified configuration system:

  1. Check this documentation first
  2. Run diagnostic commands:
    • make config-check - Health check of entire config system
    • make config-debug - Show current configuration values
  3. Review generated configuration files
  4. Check .env file for environment-specific overrides
  5. Check application logs for configuration-related errors

Configuration Priority

The unified config uses this priority order:

  1. .env file (highest priority) - Environment-specific overrides
  2. Environment configs (medium priority) - Built-in environment defaults
  3. Default values (lowest priority) - Fallback defaults in unified.config.ts

The unified configuration system provides a robust, scalable, and maintainable approach to application configuration management with .env file integration.