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:
- First request triggers initialization
- Each component is tested and initialized
- Status is tracked globally
- 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"]
}
System Startup (Recommended)
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
- Durable Object Creation: Creates a ChatLobby Durable Object with ID ‘base-chat’
- Health Check: Tests the Durable Object by calling its health endpoint
- 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:
- Check the error logs
- Verify component dependencies
- Re-initialize specific components
- 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
- Check system status:
GET /api/system/init - Review health endpoint:
GET /api/health - Test individual components
- Check application logs
- Verify environment configuration
Best Practices
Production Deployment
- Pre-initialization: Call startup endpoint during deployment
- Health Checks: Monitor health endpoint for system status
- Error Alerting: Set up alerts for initialization failures
- Graceful Degradation: Handle partial initialization gracefully
Development
- Local Testing: Use test script for local development
- Component Isolation: Test individual components
- Error Simulation: Test error handling scenarios
- Performance Monitoring: Monitor initialization times
Configuration
- Environment Variables: Ensure all required environment variables are set
- Durable Object Bindings: Verify wrangler.jsonc configuration
- Database Migrations: Ensure database schema is up to date
- 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.