This document explains the architecture and organization of the Deploy Center server.
The project follows a layered architecture pattern:
┌─────────────────────────────────────────┐
│ HTTP Request │
└─────────────────┬───────────────────────┘
│
┌─────────────────▼───────────────────────┐
│ Routes Layer │
│ (URL mapping & middleware chaining) │
└─────────────────┬───────────────────────┘
│
┌─────────────────▼───────────────────────┐
│ Controllers Layer │
│ (Request/Response handling) │
└─────────────────┬───────────────────────┘
│
┌─────────────────▼───────────────────────┐
│ Services Layer │
│ (Business logic & orchestration) │
└─────────────────┬───────────────────────┘
│
┌─────────────────▼───────────────────────┐
│ Models Layer │
│ (Data access & ORM) │
└─────────────────┬───────────────────────┘
│
┌─────────────────▼───────────────────────┐
│ Database │
│ (MariaDB) │
└─────────────────────────────────────────┘
server/
├── src/
│ ├── Config/ # Application configuration
│ ├── Controllers/ # HTTP request handlers
│ ├── Database/ # Database connection & setup
│ ├── Middleware/ # Express middlewares
│ ├── Models/ # Database models (Sequelize)
│ ├── Routes/ # API route definitions
│ ├── Services/ # Business logic layer
│ ├── Types/ # TypeScript type definitions
│ ├── Utils/ # Utility functions & helpers
│ ├── App.ts # Express application setup
│ ├── Server.ts # Server initialization
│ └── index.ts # Application entry point
├── logs/ # Application logs (auto-generated)
├── deployments/ # Deployment workspaces (auto-generated)
├── .env # Environment variables (create from .env.example)
├── .env.example # Environment template
├── .eslintrc.json # ESLint configuration
├── .prettierrc.json # Prettier configuration
├── .gitignore # Git ignore rules
├── jest.config.js # Jest testing configuration
├── nodemon.json # Nodemon configuration
├── tsconfig.json # TypeScript compiler options
├── package.json # Dependencies and scripts
├── README.md # Main documentation
├── QUICK_START.md # Quick start guide
└── PROJECT_STRUCTURE.md # This file
Purpose: Centralized configuration management
Files:
AppConfig.ts- Singleton configuration class
Responsibilities:
- Load environment variables
- Provide default values
- Validate configuration
- Expose configuration to other layers
Example:
const config = AppConfig.GetInstance();
console.log(config.Port); // 3000Purpose: Database schema and ORM models
Files:
User.ts- User authentication modelProject.ts- Project configuration modelDeployment.ts- Deployment tracking modelDeploymentStep.ts- Pipeline step execution modelAuditLog.ts- Audit trail modelindex.ts- Model associations and exports
Responsibilities:
- Define database schema
- Manage relationships between entities
- Provide data validation
- Expose Sequelize ORM interface
Key Features:
- All fields use PascalCase
- Timestamps (CreatedAt, UpdatedAt)
- Soft deletes support
- Foreign key relationships
Purpose: TypeScript type definitions and interfaces
Files:
ICommon.ts- Common types, enums, interfacesIDatabase.ts- Database-specific types
Responsibilities:
- Define interfaces for data structures
- Enum definitions
- Type safety across application
- API response types
Example:
export enum EUserRole {
Admin = 'admin',
Developer = 'developer',
Viewer = 'viewer',
}
export interface IApiResponse<T = any> {
Success: boolean;
Message: string;
Data?: T;
Error?: string;
Code: number;
}Purpose: Reusable utility functions and helpers
Files:
Logger.ts- Winston logging singletonPasswordHelper.ts- Password hashing (bcrypt)EncryptionHelper.ts- AES-256-GCM encryptionResponseHelper.ts- Standardized API responses
Responsibilities:
- Logging functionality
- Cryptographic operations
- Data transformation
- Common helper functions
Purpose: Database connection management
Files:
DatabaseConnection.ts- Sequelize connection singleton
Responsibilities:
- Initialize database connection
- Connection pooling
- Test connectivity
- Sync models (development)
Features:
- Singleton pattern
- Connection testing
- Graceful shutdown
- Auto-reconnect
Purpose: Business logic and orchestration
Files:
AuthService.ts- Authentication & JWTProjectService.ts- Project CRUD operationsDeploymentService.ts- Deployment orchestrationPipelineService.ts- Pipeline execution engineQueueService.ts- Deployment queue managementNotificationService.ts- Multi-platform notificationsWebhookService.ts- Webhook verification & processing
Responsibilities:
- Implement business rules
- Orchestrate complex operations
- Interact with models
- Handle business exceptions
Architecture:
- Service classes (not singletons, except QueueService)
- Dependency injection ready
- Comprehensive error handling
- Detailed logging
Example:
const authService = new AuthService();
const result = await authService.Login({ Username, Password });Purpose: HTTP request/response handling
Files:
AuthController.ts- Authentication endpointsProjectController.ts- Project management endpointsDeploymentController.ts- Deployment endpointsWebhookController.ts- Webhook endpoints
Responsibilities:
- Parse request data
- Call appropriate services
- Format responses
- Handle HTTP-specific errors
Pattern:
public GetAll = async (req: Request, res: Response): Promise<void> => {
try {
const data = await this.Service.GetAll();
ResponseHelper.Success(res, 'Success', data);
} catch (error) {
ResponseHelper.Error(res, error.message);
}
};Purpose: Request processing pipeline
Files:
AuthMiddleware.ts- JWT authenticationRoleMiddleware.ts- Role-based authorizationValidationMiddleware.ts- Request validation (Joi)RateLimiterMiddleware.ts- Rate limitingErrorHandlerMiddleware.ts- Global error handlingRequestLoggerMiddleware.ts- Request logging
Responsibilities:
- Authenticate requests
- Authorize access
- Validate input
- Prevent abuse
- Log requests
- Handle errors
Usage:
router.get('/',
authMiddleware.Authenticate,
roleMiddleware.RequireAdmin,
rateLimiter.ApiLimiter,
controller.GetAll
);Purpose: API endpoint definitions
Files:
AuthRoutes.ts- Authentication routesProjectRoutes.ts- Project routesDeploymentRoutes.ts- Deployment routesWebhookRoutes.ts- Webhook routesindex.ts- Route aggregation
Responsibilities:
- Define URL patterns
- Map URLs to controllers
- Chain middleware
- Group related endpoints
Structure:
/api
/auth
POST /register
POST /login
GET /profile
/projects
GET /
POST /
GET /:id
PUT /:id
DELETE /:id
/deployments
GET /:id
POST /:id/retry
Files:
App.ts- Express app configurationServer.ts- Server initializationindex.ts- Entry point
Responsibilities:
- Configure Express middleware
- Initialize routes
- Setup error handling
- Start HTTP server
- Graceful shutdown
AppConfig- Single configuration instanceLogger- Single logger instanceDatabaseConnection- Single DB connectionQueueService- Single queue manager
- Models abstract database access
- Services use models for data operations
- Separation of data access from business logic
- Business logic separated from controllers
- Reusable across different interfaces
- Testable independently
- Services accept dependencies
- Easy to mock for testing
- Loose coupling
- Response formatting
- Error handling
- Middleware creation
- Classes:
AuthService,UserController - Interfaces:
IUser,IApiResponse - Types:
EUserRole,EDeploymentStatus - Class properties:
User.Id,Project.Name - Class methods:
GetAll(),CreateUser()
- Variables:
const userId = 1 - Function parameters:
function login(username, password) - Private methods:
private validateInput()
- Constants:
const MAX_RETRIES = 3 - Environment variables:
process.env.DB_HOST
Example: Creating a deployment via webhook
1. GitHub sends webhook
↓
2. WebhookRoutes receives POST /webhook/github/:projectName
↓
3. RateLimiterMiddleware checks rate limit
↓
4. WebhookController.HandleGitHubWebhook()
↓
5. WebhookService.VerifyGitHubSignature()
↓
6. WebhookService.ProcessGitHubWebhook()
↓
7. WebhookService.ShouldTriggerDeployment()
↓
8. DeploymentService.CreateDeployment()
↓
9. QueueService.Add() - Add to queue
↓
10. QueueService.ProcessQueue() - Execute when ready
↓
11. DeploymentService.ExecuteDeployment()
↓
12. PipelineService.ExecutePipeline()
↓
13. NotificationService.SendDeploymentNotification()
↓
14. Response sent back to GitHub
-
Service Layer
- Catches and logs errors
- Throws business exceptions
- Detailed error context
-
Controller Layer
- Catches service errors
- Formats error responses
- HTTP status codes
-
Middleware Layer
- Global error handler
- Uncaught exception handler
- 404 handler
{
"Success": false,
"Message": "User-friendly message",
"Error": "Technical error details",
"Code": 400
}-
Authentication
- JWT with RS256/HS256
- Token refresh mechanism
- Password hashing (bcrypt, 12 rounds)
-
Authorization
- Role-based access control
- Middleware enforcement
- Resource-level permissions
-
Input Validation
- Joi schemas
- Sanitization
- Type checking
-
Rate Limiting
- Per-endpoint limits
- IP-based tracking
- Sliding window
-
Security Headers
- Helmet.js
- CORS configuration
- XSS protection
-
Encryption
- AES-256-GCM for sensitive data
- HMAC for webhook signatures
- SSL/TLS for transport
- Test individual functions
- Mock dependencies
- Services and utilities
- Test API endpoints
- Database interactions
- End-to-end flows
src/
Controllers/
AuthController.ts
AuthController.test.ts
Services/
AuthService.ts
AuthService.test.ts
-
Database
- Connection pooling
- Indexed queries
- Eager/lazy loading
-
Caching
- In-memory caching ready
- Redis integration ready
-
Compression
- Response compression
- Gzip enabled
-
Rate Limiting
- Prevent abuse
- Resource protection
-
Horizontal Scaling
- Stateless design
- Session in JWT
- Ready for load balancing
-
Queue System
- Prevents concurrent deployments
- Priority-based processing
- Extensible to Redis/RabbitMQ
-
Logging
- Structured logging
- Log rotation
- Ready for centralized logging
-
Monitoring
- Health check endpoint
- Metrics ready
- Error tracking ready
-
New Model
- Create in
Models/ - Define relationships in
Models/index.ts - Update types in
Types/
- Create in
-
New Service
- Create in
Services/ - Implement business logic
- Use existing models
- Create in
-
New Endpoint
- Create controller in
Controllers/ - Create routes in
Routes/ - Add to
Routes/index.ts
- Create controller in
-
New Middleware
- Create in
Middleware/ - Apply in routes or
App.ts
- Create in
- Always use PascalCase for classes, interfaces, properties, methods
- Always log important operations and errors
- Always validate input at controller level
- Always handle errors gracefully
- Always use TypeScript strict mode
- Always follow SOLID principles
- Always test new features
- Always document complex logic
-
Import errors
- Check tsconfig paths
- Verify file exists
- Check circular dependencies
-
Database errors
- Check model definitions
- Verify relationships
- Check migrations
-
Type errors
- Update interface definitions
- Check type imports
- Verify type compatibility
When contributing to this project:
- Follow the existing architecture
- Maintain PascalCase naming
- Add appropriate logging
- Include error handling
- Write tests
- Update documentation
- Follow ESLint rules