System Initialization

PadawanForge includes a comprehensive system initialization process that ensures all components are properly started and ready for use.

Overview

The system initialization process automatically starts when the first request is made to the application. It initializes all critical components including:

  • Base Chat System: Durable Object for global chat functionality
  • Room Manager: Durable Object for room management
  • AI Services: Cloudflare Workers AI integration
  • Database: D1 database connections
  • Workflows: Background processing workflows

Components

SystemInitializer Service

The core initialization logic is handled by the SystemInitializer class in src/lib/services/SystemInitializer.ts.

Key Features:

  • Component-by-component initialization
  • Health checks for each component
  • Error handling and recovery
  • Status tracking and reporting

Automatic Initialization

The system automatically initializes on the first request via middleware in src/middleware/system-init.ts.

Process:

  1. First request triggers initialization
  2. Each component is tested and initialized
  3. Status is tracked globally
  4. Subsequent requests use cached status

Manual Initialization

You can manually trigger system initialization using the API endpoints:

Initialize All Components

POST /api/system/init

Initialize Specific Components

POST /api/system/init
Content-Type: application/json

{
  "components": ["baseChat", "roomManager"]
}
POST /api/system/startup

API Endpoints

System Status

GET /api/system/init

Response:

{
  "healthy": true,
  "status": {
    "baseChat": true,
    "roomManager": true,
    "aiServices": true,
    "database": true,
    "workflows": true,
    "lastInitTime": "2024-01-01T00:00:00.000Z",
    "errors": []
  },
  "errors": [],
  "timestamp": "2024-01-01T00:00:00.000Z"
}

Health Check

GET /api/health

Response:

{
  "status": "healthy",
  "timestamp": "2024-01-01T00:00:00.000Z",
  "responseTime": "45ms",
  "system": {
    "initialized": true,
    "healthy": true,
    "components": {
      "database": true,
      "ai": true,
      "chatLobby": true,
      "roomManager": true,
      "workflows": true
    },
    "status": { ... },
    "errors": []
  },
  "environment": {
    "nodeEnv": "development",
    "platform": "cloudflare-workers"
  }
}

Base Chat Initialization

The base chat system is a critical component that provides global chat functionality.

Initialization Process

  1. Durable Object Creation: Creates a ChatLobby Durable Object with ID ‘base-chat’
  2. Health Check: Tests the Durable Object by calling its health endpoint
  3. Status Tracking: Updates system status based on initialization result

Configuration

The base chat uses the following configuration:

  • Durable Object ID: ‘base-chat’
  • Health Endpoint: /health
  • WebSocket Endpoint: /websocket

Testing

Test base chat initialization specifically:

POST /api/system/init
Content-Type: application/json

{
  "components": ["baseChat"]
}

Error Handling

Component Failures

If a component fails to initialize:

  • The error is logged and tracked
  • Other components continue initialization
  • The system reports partial success (HTTP 207)
  • Health checks will show the failed component

Recovery

To recover from initialization failures:

  1. Check the error logs
  2. Verify component dependencies
  3. Re-initialize specific components
  4. Monitor health endpoint for status

Monitoring

Health Monitoring

Monitor system health using the health endpoint:

curl http://localhost:4321/api/health

Log Monitoring

Watch for initialization logs:

🔄 [SystemInit] Starting system initialization...
✅ [SystemInit] System initialization completed: 5 successful, 0 failed
⚠️ [SystemInit] Some components failed to initialize: [component: error]
❌ [SystemInit] System initialization failed: [error]

Testing Script

Use the provided test script:

node scripts/init-system.js

Troubleshooting

Common Issues

Durable Object Not Available

Error: CHAT_LOBBY Durable Object not available Solution: Check wrangler.jsonc configuration and ensure Durable Objects are properly bound

Health Check Failed

Error: Health check failed with status 500 Solution: Check Durable Object implementation and ensure health endpoints are working

Database Connection Failed

Error: Database connection test failed Solution: Verify D1 database configuration and connectivity

AI Service Unavailable

Error: AI service not available Solution: Check Cloudflare Workers AI configuration

Debug Steps

  1. Check system status: GET /api/system/init
  2. Review health endpoint: GET /api/health
  3. Test individual components
  4. Check application logs
  5. Verify environment configuration

Best Practices

Production Deployment

  1. Pre-initialization: Call startup endpoint during deployment
  2. Health Checks: Monitor health endpoint for system status
  3. Error Alerting: Set up alerts for initialization failures
  4. Graceful Degradation: Handle partial initialization gracefully

Development

  1. Local Testing: Use test script for local development
  2. Component Isolation: Test individual components
  3. Error Simulation: Test error handling scenarios
  4. Performance Monitoring: Monitor initialization times

Configuration

  1. Environment Variables: Ensure all required environment variables are set
  2. Durable Object Bindings: Verify wrangler.jsonc configuration
  3. Database Migrations: Ensure database schema is up to date
  4. AI Service Keys: Verify AI service configuration

Integration

Frontend Integration

The system status is available in Astro pages via locals.systemStatus:

---
const { systemStatus } = Astro.locals;
---

<div class="system-status">
  <p>System Initialized: {systemStatus?.initialized ? '✅' : '❌'}</p>
  <p>System Healthy: {systemStatus?.healthy ? '✅' : '❌'}</p>
</div>

API Integration

Check system status before making critical API calls:

const healthResponse = await fetch('/api/health');
const healthData = await healthResponse.json();

if (!healthData.system.healthy) {
  console.warn('System not healthy:', healthData.system.errors);
}

This system initialization process ensures PadawanForge starts reliably and provides clear visibility into the health and status of all critical components.

PadawanForge v1.4.1