Files
pos-system/services/_template_nodejs/ARCHITECTURE.vi.md
Ho Ngoc Hai 4e595d0746 feat(docs): Remove outdated service templates and enhance Vietnamese architecture documentation
- Deleted obsolete service architecture templates in both English and Vietnamese to streamline content.
- Updated the Vietnamese architecture documentation with improved Mermaid diagrams for better visual clarity.
- Enhanced color coding in diagrams to improve readability and consistency across documentation.
- Added a new section detailing visual indicators for better understanding of architecture components.
2026-01-10 21:00:02 +07:00

18 KiB

Kiến Trúc Template Dịch Vụ

Tài liệu này mô tả kiến trúc của một microservice đơn lẻ được xây dựng từ template này và cách nó tích hợp với nền tảng microservices GoodGo.

Tổng quan

Template này cung cấp foundation hoàn chỉnh, production-ready để xây dựng các microservice riêng lẻ với:

  • Bảo mật: Xác thực, phân quyền, validation đầu vào, và security headers
  • Khả năng quan sát: Logging toàn diện, metrics, tracing, và health checks
  • Quản lý dữ liệu: Repository pattern, database migrations, và seeding
  • Tài liệu API: OpenAPI/Swagger documentation với giao diện tương tác
  • Xử lý lỗi: Structured error responses với HTTP status codes phù hợp
  • Hỗ trợ Docker: Multi-stage builds và tối ưu hóa production

Bối cảnh Quan trọng: Template này đại diện cho một microservice đơn lẻ. Để triển khai và điều phối ở cấp độ nền tảng, các service được đăng ký trong deployments/local/docker-compose.yml và định tuyến qua Traefik API Gateway được cấu hình trong infra/traefik/.


Phần 1: Kiến Trúc Service Đơn Lẻ (Nội bộ)

Phần này mô tả kiến trúc nội bộ của một microservice đơn lẻ được xây dựng từ template này.

Các Thành Phần Nội Bộ Service

graph TD
    Request[HTTP Request] -->|Từ Traefik| Middleware[Chuỗi Middleware]
    
    subgraph SingleService[Ranh Giới Service Đơn Lẻ]
        Middleware --> Correlation[Correlation ID Middleware]
        Correlation --> Auth[Authentication Middleware]
        Auth --> Validation[Validation Middleware]
        Validation --> Error[Error Handler]
        Error --> Logger[Request Logger]
        Logger --> Metrics[Metrics Collector]
        
        Metrics --> Router[Lớp Router]
        Router --> Controller[Lớp Controller]
        Controller --> Service[Lớp Service]
        Service --> Repository[Lớp Repository]
        
        Repository --> Database[(PostgreSQL)]
        Service --> Cache[(Redis)]
        
        Service -.->|Trạng thái Health| Health[Health Checks]
        Service -.->|Tài liệu API| OpenAPI[OpenAPI/Swagger]
    end
    
    Service -.->|Metrics| Prometheus[Prometheus]
    Service -.->|Traces| Jaeger[Jaeger]
    
    style Correlation fill:#e1f5fe
    style Auth fill:#f3e5f5
    style Validation fill:#e8f5e8
    style Error fill:#fff3e0
    style Logger fill:#f3e5f5
    style Metrics fill:#e8f5e8

Kiến Trúc Phân Lớp

Chuỗi Middleware

Chuỗi middleware xử lý mọi request đến theo thứ tự:

  1. Correlation Middleware: Tạo/truyền correlation và request IDs
  2. Authentication Middleware: Xác thực JWT tokens (tùy chọn cho public routes)
  3. Validation Middleware: Làm sạch và validate dữ liệu đầu vào với Zod schemas
  4. Error Handler: Bắt và format lỗi thành structured responses
  5. Logger Middleware: Ghi log request/response với correlation IDs
  6. Metrics Middleware: Thu thập Prometheus metrics (duration, status, payload size)

Lớp Controller

  • Xử lý HTTP requests và responses
  • Điều phối các lời gọi service layer
  • Format API responses
  • Bọc async handlers để truyền lỗi

Lớp Service

  • Chứa business logic thuần túy
  • Độc lập với HTTP transport
  • Điều phối các lời gọi repository
  • Triển khai caching strategies
  • Throw domain-specific errors

Lớp Repository

  • Trừu tượng hóa database operations
  • Sử dụng Prisma ORM cho type-safe queries
  • Triển khai repository pattern
  • Cung cấp error handling nhất quán
  • Hỗ trợ transactions

Luồng Xử Lý Request

  1. Đầu vào Request:

    • Client gửi HTTP request đến ingress/load balancer
    • Request bao gồm correlation ID header tùy chọn (x-correlation-id)
  2. Correlation Middleware:

    • Tạo hoặc truyền correlation ID để tracing request
    • Thêm request ID để định danh request duy nhất
    • Đặt correlation headers trên response
  3. Security Middleware:

    • Authentication: Xác thực JWT tokens (tùy chọn cho public routes)
    • Authorization: Kiểm tra user roles và permissions
    • Rate Limiting: Ngăn chặn lạm dụng với Redis-backed rate limiting
    • Helmet: Bảo mật HTTP headers
  4. Validation Middleware:

    • Làm sạch input data (trimming, normalization)
    • Validate request data sử dụng Zod schemas
    • Trả về structured validation errors
  5. Router & Controller:

    • Định tuyến request đến controller phù hợp
    • Controller điều phối thực thi business logic
    • Input validation và response formatting
  6. Lớp Service:

    • Chứa business logic thuần túy
    • Độc lập với HTTP transport layer
    • Điều phối data access và external service calls
  7. Lớp Repository:

    • Triển khai repository pattern cho data access
    • Trừu tượng hóa database operations với Prisma ORM
    • Cung cấp error handling nhất quán
  8. Response & Observability:

    • Format structured JSON responses
    • Ghi lại comprehensive metrics (duration, errors, payload sizes)
    • Log với correlation IDs cho distributed tracing
    • Gửi traces đến Jaeger nếu được bật

Mẫu Kiến Trúc

Mẫu Repository

// Base repository với common CRUD operations
class BaseRepository<T, CreateInput, UpdateInput> {
  async findById(id: string): Promise<T | null>
  async create(data: CreateInput): Promise<T>
  async update(id: string, data: UpdateInput): Promise<T>
  // ... thêm các methods phổ biến
}

// Repository cụ thể extends base
class FeatureRepository extends BaseRepository<Feature, CreateFeatureInput, UpdateFeatureInput> {
  async findByName(name: string): Promise<Feature | null>
  async findByTags(tags: string[]): Promise<Feature[]>
  // ... feature-specific methods
}

Chuỗi Middleware

// Request processing pipeline
app.use(correlationMiddleware());        // Thêm correlation IDs
app.use(authenticate());                 // JWT validation
app.use(authorize('admin'));             // Role checking
app.use(validateDto(schema));            // Input validation
app.use(errorHandler);                   // Error handling

Xử Lý Lỗi

// Custom error classes
class NotFoundError extends HttpError {
  constructor(resource: string) {
    super(`${resource} not found`, 404, 'NOT_FOUND');
  }
}

// Sử dụng trong services
if (!feature) {
  throw new NotFoundError('Feature');
}

Tiêm Phụ Thuộc

// Constructor injection cho testability
export class FeatureService {
  constructor(private repository: IRepository<Feature>) {}

  async create(data: CreateFeatureInput): Promise<Feature> {
    return this.repository.create(data);
  }
}

Thực Tiễn Tốt

Tổ Chức Code

  • Separation of Concerns: Ranh giới rõ ràng giữa các lớp (Controller → Service → Repository)
  • Single Responsibility: Mỗi class/method có một mục đích rõ ràng
  • Dependency Injection: Constructor injection để testability tốt hơn
  • Error Boundaries: Xử lý lỗi phù hợp ở mỗi lớp

Bảo Mật

  • Input Validation: Tất cả inputs được validate với Zod schemas
  • Authentication: JWT tokens với expiration phù hợp
  • Authorization: Role-based access control (RBAC)
  • Rate Limiting: Distributed rate limiting với Redis
  • Security Headers: Helmet.js cho HTTP security headers

Khả Năng Quan Sát

  • Structured Logging: Format log nhất quán với correlation IDs
  • Metrics: Comprehensive Prometheus metrics
  • Tracing: Distributed tracing với Jaeger
  • Health Checks: Liveness và readiness probes
  • Correlation IDs: Request tracing qua service boundaries

Xử Lý Lỗi

  • Custom Error Classes: Error types cụ thể cho các scenarios khác nhau
  • HTTP Status Mapping: Status codes phù hợp cho các error types khác nhau
  • Structured Responses: Format error response nhất quán
  • Operational Errors: Phân biệt rõ ràng giữa programming và operational errors

Kiểm Thử

  • Unit Tests: Test các functions và classes riêng lẻ
  • Integration Tests: Test tương tác giữa các components
  • E2E Tests: Test chu trình request/response hoàn chỉnh
  • Test Utilities: Shared test helpers và mocks
  • Coverage Goals: Mục tiêu >70% code coverage

Docker & Triển Khai

  • Multi-stage Builds: Tối ưu cho production image size
  • Security: Non-root users, minimal attack surface
  • Health Checks: Container health monitoring
  • Compose Files: Development, testing, và production configurations
  • Resource Limits: CPU và memory constraints phù hợp

Quản Lý Cấu Hình

Biến Môi Trường

  • Typed Configuration: Zod schemas cho env validation
  • Default Values: Defaults hợp lý cho development
  • Override Support: .env.local ghi đè .env
  • Documentation: Tài liệu biến môi trường toàn diện

Feature Flags

  • Runtime Configuration: Database-backed feature flags
  • Admin Control: Admin API cho feature management
  • Gradual Rollout: Bật/tắt features không cần deployment
  • Audit Trail: Theo dõi feature flag changes

Thiết Kế API

Quy Ước RESTful

  • Resource Naming: Danh từ số nhiều cho resource endpoints
  • HTTP Methods: GET, POST, PUT, DELETE, PATCH phù hợp
  • Status Codes: HTTP status codes phù hợp cho tất cả responses
  • Content Negotiation: JSON responses với content-type phù hợp

Định Dạng Phản hồi

{
  "success": true,
  "data": { ... },
  "message": "Hoạt động hoàn thành thành công",
  "timestamp": "2024-01-01T00:00:00.000Z"
}

Phản hồi Lỗi

{
  "success": false,
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Validation thất bại",
    "details": [...]
  },
  "timestamp": "2024-01-01T00:00:00.000Z"
}

Quy Trình Phát Triển

Phát Triển Cục Bộ

  1. Setup Infrastructure: docker-compose up -d
  2. Install Dependencies: pnpm install
  3. Database Setup: pnpm prisma migrate dev && pnpm prisma db seed
  4. Start Development: pnpm dev
  5. Run Tests: pnpm test

Chiến Lược Kiểm Thử

  1. Unit Tests: Test các functions và classes riêng lẻ
  2. Integration Tests: Test middleware chains và service interactions
  3. E2E Tests: Test complete API workflows
  4. Performance Tests: Load testing và performance validation

Pipeline Triển Khai

  1. Linting: Code quality checks với ESLint và Prettier
  2. Testing: Full test suite execution (unit, integration, E2E)
  3. Security Scanning: Dependency audit, SAST, và container scanning
  4. Build: Multi-stage Docker image creation với security scanning
  5. Deploy: Container orchestration deployment với health checks
  6. Verification: Automated post-deployment health và performance verification

Phần 2: Tích Hợp Nền Tảng (Ngoại vi)

Phần này mô tả cách một service được xây dựng từ template này tích hợp với nền tảng microservices GoodGo.

Kiến Trúc Nền Tảng

graph TD
    Client[Client / Browser] --> Traefik[Traefik API Gateway]
    
    subgraph Platform[Nền Tảng Microservices GoodGo]
        Traefik --> AuthService[Auth Service]
        Traefik --> YourService[Service Của Bạn từ Template]
        Traefik --> OtherServices[Các Services Khác...]
        
        YourService --> SharedDB[(PostgreSQL Chung)]
        YourService --> SharedRedis[(Redis Chung)]
        
        AuthService -.->|JWT Validation| YourService
        YourService -.->|Inter-Service Calls| OtherServices
    end
    
    subgraph Observability[Observability Stack]
        Prometheus[Prometheus]
        Grafana[Grafana]
        Jaeger[Jaeger]
        Loki[Loki]
    end
    
    YourService -.->|Metrics| Prometheus
    YourService -.->|Traces| Jaeger
    YourService -.->|Logs| Loki
    Prometheus --> Grafana
    
    style Traefik fill:#ffecb3
    style YourService fill:#e1f5fe

Service Discovery & Đăng Ký

Các service được đăng ký với Traefik qua Docker labels trong deployments/local/docker-compose.yml:

services:
  your-service:
    build:
      context: ../..
      dockerfile: services/your-service/Dockerfile
    labels:
      # Bật Traefik cho service này
      - "traefik.enable=true"
      
      # Định nghĩa routing rule
      - "traefik.http.routers.your-service.rule=PathPrefix(`/api/v1/your-service`)"
      
      # Chỉ định service port
      - "traefik.http.services.your-service.loadbalancer.server.port=5002"
      
      # Cấu hình health check
      - "traefik.http.services.your-service.loadbalancer.healthcheck.path=/health/live"
      - "traefik.http.services.your-service.loadbalancer.healthcheck.interval=10s"

Hạ Tầng Chung

Traefik API Gateway (infra/traefik/)

  • Vị trí: infra/traefik/ - Cấu hình cấp độ nền tảng
  • Static Config: traefik.yml - Entry points, providers, API dashboard
  • Dynamic Config: dynamic/middlewares.yml, dynamic/routes.yml
  • Tính năng: Load balancing, rate limiting, SSL/TLS, CORS, security headers

PostgreSQL Database

  • Shared hoặc Isolated: Có thể là shared database với schema isolation hoặc databases riêng biệt
  • Connection: Qua biến môi trường DATABASE_URL
  • Migrations: Quản lý per-service với Prisma

Redis Cache

  • Shared Instance: Redis instance chung cho tất cả services
  • Connection: Qua REDIS_URL hoặc REDIS_HOST/REDIS_PORT
  • Use Cases: Caching, rate limiting, session storage

Observability Stack (infra/observability/)

  • Prometheus: Thu thập metrics từ tất cả services
  • Grafana: Visualization và dashboards
  • Jaeger: Distributed tracing
  • Loki: Log aggregation

Giao Tiếp Giữa Các Service

HTTP/REST Communication

Services giao tiếp qua HTTP thông qua Traefik hoặc direct service-to-service calls:

// Ví dụ: Gọi service khác
const response = await fetch('http://auth-service:5001/api/v1/users/validate', {
  headers: {
    'Authorization': `Bearer ${token}`,
    'X-Correlation-ID': correlationId
  }
});

Authentication Flow

  1. Client xác thực với Auth Service
  2. Auth Service phát hành JWT token
  3. Client bao gồm JWT trong requests đến các services khác
  4. Services validate JWT sử dụng @goodgo/auth-sdk
  5. Services trích xuất user info từ validated token

Phần 3: Bối Cảnh Triển Khai

Phần này giải thích cách triển khai một service được xây dựng từ template này lên nền tảng.

Thêm Service Vào Nền Tảng

Bước 1: Tạo Service từ Template

# Sử dụng create-service script
./scripts/utils/create-service.sh my-new-service

# Hoặc copy template thủ công
cp -r services/_template services/my-new-service

Bước 2: Đăng Ký trong deployments/local/docker-compose.yml

Thêm service của bạn vào platform compose file:

services:
  my-new-service:
    build:
      context: ../..
      dockerfile: services/my-new-service/Dockerfile
    container_name: my-new-service-local
    environment:
      - NODE_ENV=development
      - PORT=5003
      - DATABASE_URL=${DATABASE_URL}
      - REDIS_HOST=redis
      - REDIS_PORT=6379
      - JWT_SECRET=${JWT_SECRET}
      - SERVICE_NAME=my-new-service
      - API_VERSION=v1
    depends_on:
      redis:
        condition: service_healthy
    networks:
      - microservices-network
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.my-new-service.rule=PathPrefix(`/api/v1/my-new-service`)"
      - "traefik.http.services.my-new-service.loadbalancer.server.port=5003"

Bước 3: Cấu Hình Traefik Routes (Tùy chọn)

Để định tuyến nâng cao, thêm vào infra/traefik/dynamic/routes.yml:

http:
  routers:
    my-new-service:
      rule: "PathPrefix(`/api/v1/my-new-service`)"
      service: my-new-service
      middlewares:
        - secure-headers
        - cors
        - compress

Bước 4: Khởi Động Nền Tảng

cd deployments/local
docker-compose up -d

Bước 5: Truy Cập Service Của Bạn

Cấu Hình Môi Trường

Services kế thừa biến môi trường từ:

  1. Platform Level: deployments/local/.env.local
  2. Service Level: Service-specific environment trong docker-compose.yml
  3. Defaults: .env.example của service cho development

Xuất sắc Vận hành

Phản hồi Sự cố

  1. Detection: Automated monitoring alerts
  2. Assessment: Incident severity classification
  3. Communication: Stakeholder notification
  4. Investigation: Root cause analysis
  5. Resolution: Fix deployment và verification
  6. Post-mortem: Incident review và improvement

Lập kế hoạch Dung lượng

  • Resource Monitoring: Theo dõi CPU, memory, disk, và network usage
  • Performance Benchmarks: Regular performance testing
  • Scaling Triggers: Automated scaling dựa trên metrics
  • Cost Optimization: Right-sizing resources

Tuân thủ & Bảo mật

  • Security Audits: Regular security assessments
  • Compliance Checks: GDPR, HIPAA, SOC2 compliance
  • Data Encryption: At-rest và in-transit encryption
  • Access Controls: Least privilege access principles