Configuration Files
Overview
This document describes the various configuration files used across the Chainr platform and their purposes.
Docker Configuration
Dockerfile (Core Service)
FROM python:3.11-slim
# Set environment variables
ENV PYTHONUNBUFFERED=1
ENV PYTHONDONTWRITEBYTECODE=1
# Install system dependencies
RUN apt-get update && apt-get install -y \
gcc \
postgresql-client \
&& rm -rf /var/lib/apt/lists/*
# Create app user
RUN useradd --create-home --shell /bin/bash app
# Set work directory
WORKDIR /app
# Install Python dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Copy application code
COPY --chown=app:app . .
# Switch to non-root user
USER app
# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
CMD curl -f http://localhost:8000/health || exit 1
# Expose port
EXPOSE 8000
# Run application
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
docker-compose.yml
services:
nginx:
image: nginx:stable-alpine
ports:
- "8000:80"
redis:
image: redis:7-alpine
svc-auth:
build: ./svc-auth
svc-bff:
build: ./svc-bff
fe-core:
build:
context: ./fe
args:
APP: core
fe-public:
build:
context: ./fe
args:
APP: public
svc-core:
build:
context: ./svc-core
target: dev
ports:
- "8080:8080"
depends_on:
postgres-core:
condition: service_healthy
svc-ai:
build:
context: ./svc-ai
target: dev
ports:
- "5000:5000"
depends_on:
postgres-ai:
condition: service_healthy
postgres-core:
image: postgres:16-alpine
ports:
- "5432:5432"
postgres-ai:
image: postgres:16-alpine
ports:
- "5433:5432"
volumes:
postgres_data:
postgres_ai_data:
redis_data:
Notes:
This excerpt mirrors the active
modules/docker-compose.ymlstructure at a high level.Current dedicated databases exist for
svc-coreandsvc-ai.Dedicated databases for
svc-authandsvc-bffare planned but not yet present in Compose.
Application Configuration
Pydantic Settings (settings.py)
from pydantic import BaseSettings, validator
from typing import List, Optional
import os
class DatabaseSettings(BaseSettings):
url: str
pool_size: int = 10
max_overflow: int = 20
pool_timeout: int = 30
echo: bool = False
@validator('url')
def validate_database_url(cls, v):
if not v.startswith('postgresql://'):
raise ValueError('Only PostgreSQL is supported')
return v
class RedisSettings(BaseSettings):
url: str = "redis://localhost:6379/0"
pool_size: int = 10
decode_responses: bool = True
class SecuritySettings(BaseSettings):
jwt_secret_key: str
jwt_algorithm: str = "HS256"
jwt_access_token_expire_minutes: int = 15
jwt_refresh_token_expire_days: int = 30
bcrypt_rounds: int = 12
cors_origins: List[str] = ["http://localhost:3000"]
cors_allow_credentials: bool = True
class FileStorageSettings(BaseSettings):
max_file_size: int = 104857600 # 100MB
allowed_file_types: List[str] = ["pdf", "doc", "docx", "txt", "md", "csv", "xlsx"]
upload_path: str = "/app/uploads"
storage_type: str = "local" # local, s3, azure
class AISettings(BaseSettings):
service_url: str = "http://svc-ai:5000"
request_timeout: int = 30
max_concurrent_requests: int = 10
class MonitoringSettings(BaseSettings):
sentry_dsn: Optional[str] = None
prometheus_port: int = 9090
log_level: str = "INFO"
log_format: str = "json"
class Settings(BaseSettings):
# Environment
environment: str = "development"
debug: bool = False
testing: bool = False
# Server
host: str = "0.0.0.0"
port: int = 8000
workers: int = 1
# Feature flags
enable_ai_features: bool = True
enable_analytics: bool = False
enable_notifications: bool = True
# Nested settings
database: DatabaseSettings
redis: RedisSettings
security: SecuritySettings
file_storage: FileStorageSettings
ai: AISettings
monitoring: MonitoringSettings
class Config:
env_nested_delimiter = "__"
case_sensitive = False
# Global settings instance
settings = Settings()
Nginx Configuration
nginx.conf
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log notice;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
use epoll;
multi_accept on;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
# Logging
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
# Performance
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
client_max_body_size 100M;
# Gzip compression
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_types
text/plain
text/css
text/xml
text/javascript
application/javascript
application/xml+rss
application/json;
# Security headers
add_header X-Frame-Options DENY;
add_header X-Content-Type-Options nosniff;
add_header X-XSS-Protection "1; mode=block";
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
# Rate limiting
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
limit_req_zone $binary_remote_addr zone=auth:10m rate=5r/m;
# Include server configurations
include /etc/nginx/conf.d/*.conf;
}
conf.d/default.conf
upstream core_backend {
server svc-core:8080;
}
upstream auth_backend {
server svc-auth:3000;
}
upstream ai_backend {
server svc-ai:5000;
}
# Frontend
server {
listen 80;
server_name localhost;
root /usr/share/nginx/html;
index index.html;
# Security
add_header X-Frame-Options DENY;
add_header X-Content-Type-Options nosniff;
# API proxy
location /api/ {
proxy_pass http://core_backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# Rate limiting
limit_req zone=api burst=20 nodelay;
}
# Auth proxy
location /auth/ {
proxy_pass http://auth_backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
# Stricter rate limiting for auth
limit_req zone=auth burst=5 nodelay;
}
# AI proxy
location /ai/ {
proxy_pass http://ai_backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
# Static files with caching
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
# SPA fallback
location / {
try_files $uri $uri/ /index.html;
}
}
CI/CD Configuration
GitHub Actions (.github/workflows/ci.yml)
name: CI/CD Pipeline
on:
push:
branches: [main, develop]
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
services:
postgres:
image: postgres:15
env:
POSTGRES_PASSWORD: postgres
options: >-
--health-cmd pg_isready
--health-interval 10s
--health-timeout 5s
--health-retries 5
redis:
image: redis:7
steps:
- uses: actions/checkout@v3
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: "3.11"
- name: Install dependencies
run: |
pip install -r requirements.txt
pip install -r requirements-dev.txt
- name: Run tests
run: pytest --cov=app --cov-report=xml
env:
DATABASE_URL: postgresql://postgres:postgres@localhost:5432/test
REDIS_URL: redis://localhost:6379/0
- name: Upload coverage
uses: codecov/codecov-action@v3
build-and-push:
needs: test
runs-on: ubuntu-latest
if: github.ref == 'refs/heads/main'
steps:
- name: Build and push Docker image
uses: docker/build-push-action@v4
with:
context: .
push: true
tags: registry.chainr.com/core:${{ github.sha }}
Monitoring Configuration
Prometheus (prometheus.yml)
global:
scrape_interval: 15s
evaluation_interval: 15s
rule_files:
- "alert_rules.yml"
alerting:
alertmanagers:
- static_configs:
- targets:
- alertmanager:9093
scrape_configs:
- job_name: "chainr-core"
static_configs:
- targets: ["svc-core:8080"]
metrics_path: "/metrics"
scrape_interval: 15s
- job_name: "chainr-auth"
static_configs:
- targets: ["svc-auth:3000"]
metrics_path: "/metrics"
- job_name: "chainr-ai"
static_configs:
- targets: ["svc-ai:5000"]
metrics_path: "/metrics"
- job_name: "nginx"
static_configs:
- targets: ["nginx:9113"]
Alert Rules (alert_rules.yml)
groups:
- name: chainr
rules:
- alert: HighErrorRate
expr: rate(http_requests_total{status=~"5.."}[5m]) / rate(http_requests_total[5m]) > 0.05
for: 5m
labels:
severity: critical
annotations:
summary: "High error rate on {{ $labels.service }}"
- alert: ServiceDown
expr: up == 0
for: 1m
labels:
severity: critical
annotations:
summary: "Service {{ $labels.job }} is down"
Development Configuration
VS Code Settings (.vscode/settings.json)
{
"python.defaultInterpreterPath": "./venv/bin/python",
"python.linting.enabled": true,
"python.linting.pylintEnabled": true,
"python.linting.flake8Enabled": true,
"python.formatting.provider": "black",
"python.testing.pytestEnabled": true,
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.organizeImports": true
},
"files.associations": {
"*.env": "properties"
}
}
Pre-commit Hooks (.pre-commit-config.yaml)
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-yaml
- id: check-added-large-files
- repo: https://github.com/psf/black
rev: 23.3.0
hooks:
- id: black
- repo: https://github.com/pycqa/flake8
rev: 6.0.0
hooks:
- id: flake8
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.3.0
hooks:
- id: mypy
additional_dependencies: [types-all]
These configuration files provide a solid foundation for development, deployment, and operations of the Chainr platform.