feat: Bổ sung hỗ trợ song ngữ (EN/VI) và chuẩn hóa cấu trúc cho các mẫu tài liệu.
This commit is contained in:
@@ -1,9 +1,8 @@
|
||||
# Data Consistency Patterns / Patterns Đồng bộ Dữ liệu
|
||||
# Data Consistency Patterns
|
||||
|
||||
> **EN**: Patterns for maintaining data consistency in distributed microservices architecture
|
||||
> **VI**: Các patterns để duy trì tính nhất quán dữ liệu trong kiến trúc microservices phân tán
|
||||
> Patterns for maintaining data consistency in distributed microservices architecture
|
||||
|
||||
## Overview Diagram / Sơ đồ Tổng quan
|
||||
## Overview Diagram
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
@@ -31,9 +30,9 @@ graph TD
|
||||
style CQRS fill:#d4edda
|
||||
```
|
||||
|
||||
## Architecture Description / Mô tả Kiến trúc
|
||||
## Architecture Description
|
||||
|
||||
### EN: Architecture Overview
|
||||
### Architecture Overview
|
||||
|
||||
GoodGo platform uses multiple consistency patterns to handle distributed data:
|
||||
|
||||
@@ -50,24 +49,7 @@ GoodGo platform uses multiple consistency patterns to handle distributed data:
|
||||
- **Optimistic Locking**: For concurrent updates
|
||||
- **CQRS**: For read/write optimization
|
||||
|
||||
### VI: Tổng quan Kiến trúc
|
||||
|
||||
Nền tảng GoodGo sử dụng nhiều consistency patterns để xử lý dữ liệu phân tán:
|
||||
|
||||
**Thách thức Cốt lõi**:
|
||||
- Không có distributed transactions (2PC quá chậm)
|
||||
- Services sở hữu dữ liệu riêng (database per service)
|
||||
- Network failures có thể gây partial completion
|
||||
- Cần maintain data integrity giữa các services
|
||||
|
||||
**Lựa chọn Pattern**:
|
||||
- **Saga**: Cho workflows nhiều services
|
||||
- **Outbox**: Cho event publishing đảm bảo
|
||||
- **Idempotency**: Cho retries an toàn
|
||||
- **Optimistic Locking**: Cho concurrent updates
|
||||
- **CQRS**: Cho tối ưu read/write
|
||||
|
||||
## System Context / Bối cảnh Hệ thống
|
||||
## System Context
|
||||
|
||||
```mermaid
|
||||
C4Context
|
||||
@@ -106,11 +88,9 @@ C4Context
|
||||
UpdateRelStyle(saga_orchestrator, inventory_service, $lineColor="red", $textColor="red")
|
||||
```
|
||||
|
||||
**EN**: The GoodGo platform uses a database-per-service architecture where each service owns its data. Data consistency across services is achieved through patterns like Saga (for coordinated workflows), Outbox (for reliable event publishing), Idempotency (for safe retries), and Optimistic Locking (for concurrent updates). These patterns enable eventual consistency while maintaining data integrity.
|
||||
The GoodGo platform uses a database-per-service architecture where each service owns its data. Data consistency across services is achieved through patterns like Saga (for coordinated workflows), Outbox (for reliable event publishing), Idempotency (for safe retries), and Optimistic Locking (for concurrent updates). These patterns enable eventual consistency while maintaining data integrity.
|
||||
|
||||
**VI**: Nền tảng GoodGo sử dụng kiến trúc database-per-service nơi mỗi service sở hữu dữ liệu riêng. Tính nhất quán dữ liệu giữa các services đạt được thông qua các patterns như Saga (cho workflows phối hợp), Outbox (cho event publishing đáng tin cậy), Idempotency (cho retries an toàn), và Optimistic Locking (cho concurrent updates). Các patterns này cho phép eventual consistency đồng thời duy trì data integrity.
|
||||
|
||||
## Saga Pattern / Pattern Saga
|
||||
## Saga Pattern
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
@@ -139,9 +119,7 @@ sequenceDiagram
|
||||
end
|
||||
```
|
||||
|
||||
**EN Description**: Saga manages distributed transactions as sequence of local transactions with compensation.
|
||||
|
||||
**VI Mô tả**: Saga quản lý distributed transactions dưới dạng chuỗi local transactions với compensation.
|
||||
**Description**: Saga manages distributed transactions as sequence of local transactions with compensation.
|
||||
|
||||
**Implementation**:
|
||||
```typescript
|
||||
@@ -187,7 +165,7 @@ class OrderSaga {
|
||||
}
|
||||
```
|
||||
|
||||
## Outbox Pattern / Pattern Outbox
|
||||
## Outbox Pattern
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
@@ -211,9 +189,7 @@ sequenceDiagram
|
||||
end
|
||||
```
|
||||
|
||||
**EN**: Guarantees event publishing by storing events in database within same transaction as business data.
|
||||
|
||||
**VI**: Đảm bảo event publishing bằng cách lưu events trong database cùng transaction với business data.
|
||||
**Description**: Guarantees event publishing by storing events in database within same transaction as business data.
|
||||
|
||||
**Implementation**:
|
||||
```typescript
|
||||
@@ -263,7 +239,7 @@ async processOutbox(): Promise<void> {
|
||||
}
|
||||
```
|
||||
|
||||
## Idempotency Pattern / Pattern Idempotency
|
||||
## Idempotency Pattern
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
@@ -284,9 +260,7 @@ graph LR
|
||||
style Store fill:#d4edda
|
||||
```
|
||||
|
||||
**EN**: Ensures operations can be safely retried without side effects by using idempotency keys.
|
||||
|
||||
**VI**: Đảm bảo operations có thể retry an toàn mà không có side effects bằng cách sử dụng idempotency keys.
|
||||
**Description**: Ensures operations can be safely retried without side effects by using idempotency keys.
|
||||
|
||||
**Implementation**:
|
||||
```typescript
|
||||
@@ -328,7 +302,7 @@ async createPayment(req: Request, res: Response): Promise<void> {
|
||||
}
|
||||
```
|
||||
|
||||
## Optimistic Locking / Khóa Lạc quan
|
||||
## Optimistic Locking
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
@@ -354,9 +328,7 @@ sequenceDiagram
|
||||
Service-->>User2: Success
|
||||
```
|
||||
|
||||
**EN**: Prevents lost updates by checking version on update.
|
||||
|
||||
**VI**: Ngăn chặn lost updates bằng cách kiểm tra version khi update.
|
||||
**Description**: Prevents lost updates by checking version on update.
|
||||
|
||||
**Implementation**:
|
||||
```prisma
|
||||
@@ -413,26 +385,22 @@ graph LR
|
||||
style ReadModel fill:#d4edda
|
||||
```
|
||||
|
||||
**EN**: Separates read and write models for optimal performance.
|
||||
**Description**: Separates read and write models for optimal performance.
|
||||
|
||||
**VI**: Tách biệt read và write models để tối ưu hiệu suất.
|
||||
## Performance Characteristics
|
||||
|
||||
## Performance Characteristics / Đặc điểm Hiệu suất
|
||||
Performance metrics and optimization strategies for data consistency patterns.
|
||||
|
||||
**EN**: Performance metrics and optimization strategies for data consistency patterns.
|
||||
| Pattern | Latency Impact | Throughput | Notes |
|
||||
|---------|----------------|------------|-------|
|
||||
| **Saga Execution** | 500ms - 2s | 100-500 sagas/s | Depends on number of steps and compensation |
|
||||
| **Outbox Processing** | < 100ms | 10,000 events/s | Async processing, minimal user impact |
|
||||
| **Idempotency Check** | < 10ms | 50,000 checks/s | Redis lookup, very fast |
|
||||
| **Optimistic Lock Update** | < 50ms | 5,000 updates/s | Single DB operation with version check |
|
||||
| **CQRS Projection** | 100ms - 1s | 1,000 events/s | Event processing to read model |
|
||||
| **Compensation Execution** | 200ms - 1s | Varies | Rollback operations in saga |
|
||||
|
||||
**VI**: Chỉ số hiệu suất và chiến lược tối ưu cho patterns đồng bộ dữ liệu.
|
||||
|
||||
| Pattern / Pattern | Latency Impact / Tác động Độ trễ | Throughput / Thông lượng | Notes / Ghi chú |
|
||||
|-------------------|----------------------------------|--------------------------|-----------------|
|
||||
| **Saga Execution / Thực thi Saga** | 500ms - 2s | 100-500 sagas/s | Depends on number of steps and compensation |
|
||||
| **Outbox Processing / Xử lý Outbox** | < 100ms | 10,000 events/s | Async processing, minimal user impact |
|
||||
| **Idempotency Check / Kiểm tra Idempotency** | < 10ms | 50,000 checks/s | Redis lookup, very fast |
|
||||
| **Optimistic Lock Update / Cập nhật Optimistic Lock** | < 50ms | 5,000 updates/s | Single DB operation with version check |
|
||||
| **CQRS Projection / CQRS Projection** | 100ms - 1s | 1,000 events/s | Event processing to read model |
|
||||
| **Compensation Execution / Thực thi Compensation** | 200ms - 1s | Varies | Rollback operations in saga |
|
||||
|
||||
### Performance Optimization Strategies / Chiến lược Tối ưu Hiệu suất
|
||||
### Performance Optimization Strategies
|
||||
|
||||
**Saga Pattern**:
|
||||
- Minimize number of steps (< 5 steps ideal)
|
||||
@@ -458,56 +426,52 @@ graph LR
|
||||
- Monitor conflict rates (should be < 5%)
|
||||
- Consider pessimistic locking if conflicts > 10%
|
||||
|
||||
## Security Considerations / Cân nhắc Bảo mật
|
||||
## Security Considerations
|
||||
|
||||
**EN**: Security measures for protecting data consistency operations.
|
||||
Security measures for protecting data consistency operations.
|
||||
|
||||
**VI**: Biện pháp bảo mật để bảo vệ các operations đồng bộ dữ liệu.
|
||||
### Saga Security
|
||||
|
||||
### Saga Security / Bảo mật Saga
|
||||
|
||||
**Compensation Protection / Bảo vệ Compensation**:
|
||||
**Compensation Protection**:
|
||||
- Validate saga execution permissions at each step
|
||||
- Encrypt sensitive data in saga context
|
||||
- Log all saga executions for audit
|
||||
- Implement timeout to prevent hanging sagas
|
||||
|
||||
```typescript
|
||||
// EN: Secure saga context
|
||||
// VI: Saga context bảo mật
|
||||
// Secure saga context
|
||||
interface SecureSagaContext {
|
||||
sagaId: string;
|
||||
userId: string; // EN: User who initiated / VI: User khởi tạo
|
||||
permissions: string[]; // EN: Required permissions / VI: Quyền yêu cầu
|
||||
encryptedData: string; // EN: Encrypted sensitive data / VI: Dữ liệu nhạy cảm đã mã hóa
|
||||
auditLog: AuditEntry[]; // EN: Audit trail / VI: Audit trail
|
||||
userId: string; // User who initiated
|
||||
permissions: string[]; // Required permissions
|
||||
encryptedData: string; // Encrypted sensitive data
|
||||
auditLog: AuditEntry[]; // Audit trail
|
||||
}
|
||||
```
|
||||
|
||||
### Outbox Security / Bảo mật Outbox
|
||||
### Outbox Security
|
||||
|
||||
**Event Payload Encryption / Mã hóa Event Payload**:
|
||||
**Event Payload Encryption**:
|
||||
- Encrypt PII (Personally Identifiable Information) before storing in outbox
|
||||
- Use AES-256-GCM for event payload encryption
|
||||
- Decrypt only when publishing to Kafka
|
||||
- Rotate encryption keys quarterly
|
||||
|
||||
**Access Control / Kiểm soát Truy cập**:
|
||||
**Access Control**:
|
||||
- Restrict outbox table access to outbox processor only
|
||||
- Use database roles and permissions
|
||||
- Monitor outbox table access patterns
|
||||
|
||||
### Idempotency Security / Bảo mật Idempotency
|
||||
### Idempotency Security
|
||||
|
||||
**Key Security / Bảo mật Key**:
|
||||
**Key Security**:
|
||||
- Use cryptographic hashing for idempotency keys (SHA-256)
|
||||
- Include user context in key generation
|
||||
- Validate key ownership before processing
|
||||
- Clear keys on user logout for sensitive operations
|
||||
|
||||
```typescript
|
||||
// EN: Secure idempotency key generation
|
||||
// VI: Tạo idempotency key bảo mật
|
||||
// Secure idempotency key generation
|
||||
function generateIdempotencyKey(
|
||||
operation: string,
|
||||
userId: string,
|
||||
@@ -518,19 +482,17 @@ function generateIdempotencyKey(
|
||||
}
|
||||
```
|
||||
|
||||
### Optimistic Locking Security / Bảo mật Optimistic Lock
|
||||
### Optimistic Locking Security
|
||||
|
||||
**Version Tampering Prevention / Ngăn chặn Giả mạo Version**:
|
||||
**Version Tampering Prevention**:
|
||||
- Validate version field on server-side only
|
||||
- Never accept version from client directly
|
||||
- Log version conflicts for security monitoring
|
||||
- Rate limit update attempts per user
|
||||
|
||||
## Deployment / Triển khai
|
||||
## Deployment
|
||||
|
||||
**EN**: How data consistency patterns are deployed and scaled.
|
||||
|
||||
**VI**: Cách các patterns đồng bộ dữ liệu được triển khai và mở rộng.
|
||||
How data consistency patterns are deployed and scaled.
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
@@ -569,16 +531,16 @@ graph TD
|
||||
style Kafka fill:#ffe1e1
|
||||
```
|
||||
|
||||
### Deployment Configuration / Cấu hình Triển khai
|
||||
### Deployment Configuration
|
||||
|
||||
| Component / Thành phần | Replicas | Resources | HA Strategy |
|
||||
|------------------------|----------|-----------|-------------|
|
||||
| Component | Replicas | Resources | HA Strategy |
|
||||
|-----------|----------|-----------|-------------|
|
||||
| **Saga Orchestrator** | 2-3 | 512Mi RAM, 500m CPU | Leader election with etcd |
|
||||
| **Outbox Processor** | 2-5 | 256Mi RAM, 250m CPU | Distributed lock per event batch |
|
||||
| **Services with Outbox** | 3+ | Varies | Standard service scaling |
|
||||
| **Redis (Idempotency)** | 3 nodes | 1Gi RAM each | Redis Cluster with replication |
|
||||
|
||||
### Scaling Strategy / Chiến lược Mở rộng
|
||||
### Scaling Strategy
|
||||
|
||||
**Saga Orchestrator**:
|
||||
- Scale based on pending saga count
|
||||
@@ -595,13 +557,11 @@ graph TD
|
||||
- Use consistent hashing for key distribution
|
||||
- Monitor memory usage (should be < 70%)
|
||||
|
||||
## Monitoring & Observability / Giám sát & Khả năng quan sát
|
||||
## Monitoring & Observability
|
||||
|
||||
**EN**: Monitoring strategies for data consistency patterns.
|
||||
Monitoring strategies for data consistency patterns.
|
||||
|
||||
**VI**: Chiến lược giám sát cho patterns đồng bộ dữ liệu.
|
||||
|
||||
### Key Metrics / Chỉ số Chính
|
||||
### Key Metrics
|
||||
|
||||
**Saga Metrics**:
|
||||
- `saga_executions_total` - Total saga executions (success/failure)
|
||||
@@ -628,7 +588,7 @@ graph TD
|
||||
- `optimistic_lock_retries_total` - Retry attempts after conflict
|
||||
- `optimistic_lock_success_rate` - Update success percentage
|
||||
|
||||
### Alerts / Cảnh báo
|
||||
### Alerts
|
||||
|
||||
**Critical Alerts**:
|
||||
```yaml
|
||||
@@ -651,7 +611,7 @@ for: 5m
|
||||
severity: warning
|
||||
```
|
||||
|
||||
### Monitoring Dashboard / Dashboard Giám sát
|
||||
### Monitoring Dashboard
|
||||
|
||||
**Grafana Panels**:
|
||||
|
||||
@@ -677,12 +637,11 @@ severity: warning
|
||||
- Mean time to consistency (MTTC)
|
||||
- Conflict resolution success rate
|
||||
|
||||
### Distributed Tracing / Tracing Phân tán
|
||||
### Distributed Tracing
|
||||
|
||||
**Trace Saga Execution**:
|
||||
```typescript
|
||||
// EN: Traced saga step
|
||||
// VI: Saga step được trace
|
||||
// Traced saga step
|
||||
async function executeStepWithTracing(
|
||||
step: SagaStep,
|
||||
context: SagaContext
|
||||
@@ -709,7 +668,7 @@ async function executeStepWithTracing(
|
||||
}
|
||||
```
|
||||
|
||||
## Related Documentation / Tài liệu Liên quan
|
||||
## Related Documentation
|
||||
|
||||
- [Event-Driven Architecture](./event-driven-architecture.md) - Event sourcing and Kafka
|
||||
- [System Design](./system-design.md) - Overall architecture
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
# Microservices Communication / Giao tiếp Microservices
|
||||
# Microservices Communication
|
||||
|
||||
> **EN**: Communication patterns and protocols for inter-service communication
|
||||
> **VI**: Các patterns và protocols giao tiếp giữa các services
|
||||
> Communication patterns and protocols for inter-service communication
|
||||
|
||||
## Overview Diagram / Sơ đồ Tổng quan
|
||||
## Overview Diagram
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
@@ -24,7 +23,7 @@ graph TD
|
||||
style SD fill:#d4edda
|
||||
```
|
||||
|
||||
## System Context / Bối cảnh Hệ thống
|
||||
## System Context
|
||||
|
||||
```mermaid
|
||||
C4Context
|
||||
@@ -54,13 +53,11 @@ C4Context
|
||||
Rel(services, external_api, "Integrates", "HTTPS")
|
||||
```
|
||||
|
||||
**EN**: The GoodGo platform uses a microservices architecture where all client requests flow through an API Gateway (Traefik), which routes them to appropriate microservices. Services communicate synchronously via REST/HTTP for request-response patterns and asynchronously via Kafka for event-driven workflows. Service discovery is handled by Docker DNS in local environments and Kubernetes DNS in production.
|
||||
The GoodGo platform uses a microservices architecture where all client requests flow through an API Gateway (Traefik), which routes them to appropriate microservices. Services communicate synchronously via REST/HTTP for request-response patterns and asynchronously via Kafka for event-driven workflows. Service discovery is handled by Docker DNS in local environments and Kubernetes DNS in production.
|
||||
|
||||
**VI**: Nền tảng GoodGo sử dụng kiến trúc microservices nơi tất cả client requests đi qua API Gateway (Traefik), được route đến các microservices phù hợp. Các services giao tiếp đồng bộ qua REST/HTTP cho patterns request-response và bất đồng bộ qua Kafka cho workflows event-driven. Service discovery được xử lý bởi Docker DNS trong môi trường local và Kubernetes DNS trong production.
|
||||
## Communication Protocols
|
||||
|
||||
## Communication Protocols / Protocols Giao tiếp
|
||||
|
||||
### Protocol Comparison / So sánh Protocols
|
||||
### Protocol Comparison
|
||||
|
||||
| Protocol | Latency | Complexity | Use Case |
|
||||
|----------|---------|------------|----------|
|
||||
@@ -86,9 +83,7 @@ sequenceDiagram
|
||||
Gateway-->>Client: JSON Response
|
||||
```
|
||||
|
||||
**EN**: Synchronous request-response using HTTP/REST.
|
||||
|
||||
**VI**: Request-response đồng bộ sử dụng HTTP/REST.
|
||||
Synchronous request-response using HTTP/REST.
|
||||
|
||||
**Implementation**:
|
||||
```typescript
|
||||
@@ -130,11 +125,9 @@ sequenceDiagram
|
||||
end
|
||||
```
|
||||
|
||||
**EN**: Asynchronous event-based communication via Kafka.
|
||||
Asynchronous event-based communication via Kafka.
|
||||
|
||||
**VI**: Giao tiếp bất đồng bộ dựa trên events qua Kafka.
|
||||
|
||||
### Service Discovery / Khám phá Dịch vụ
|
||||
### Service Discovery
|
||||
|
||||
**Local (Docker Compose)**:
|
||||
```yaml
|
||||
@@ -150,7 +143,7 @@ http://service-name.namespace.svc.cluster.local
|
||||
http://iam-service.default.svc.cluster.local:3001
|
||||
```
|
||||
|
||||
## API Gateway Pattern / Pattern API Gateway
|
||||
## API Gateway Pattern
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
@@ -172,61 +165,54 @@ graph LR
|
||||
style Gateway fill:#e1f5ff
|
||||
```
|
||||
|
||||
**EN**: Single entry point for all client requests with routing, auth, rate limiting.
|
||||
Single entry point for all client requests with routing, auth, rate limiting.
|
||||
|
||||
**VI**: Điểm vào duy nhất cho tất cả client requests với routing, auth, rate limiting.
|
||||
## Performance Characteristics
|
||||
|
||||
## Performance Characteristics / Đặc điểm Hiệu suất
|
||||
Performance expectations and optimization strategies for inter-service communication.
|
||||
|
||||
**EN**: Performance expectations and optimization strategies for inter-service communication.
|
||||
| Metric | Target | Notes |
|
||||
|--------|--------|-------|
|
||||
| **REST API Response Time** | < 100ms | P95 for internal service-to-service calls |
|
||||
| **Event Publishing Latency** | < 50ms | Time to publish to Kafka |
|
||||
| **Service Discovery Lookup** | < 10ms | DNS resolution time |
|
||||
| **Gateway Routing Overhead** | < 20ms | Additional latency added by Traefik |
|
||||
| **Throughput** | 10,000 req/s | Per service instance |
|
||||
| **Kafka Event Processing** | < 500ms | P95 end-to-end event processing |
|
||||
|
||||
**VI**: Kỳ vọng hiệu suất và chiến lược tối ưu cho giao tiếp giữa các services.
|
||||
|
||||
| Metric / Chỉ số | Target / Mục tiêu | Notes / Ghi chú |
|
||||
|------------------|-------------------|-----------------|
|
||||
| **REST API Response Time / Thời gian phản hồi REST API** | < 100ms | P95 for internal service-to-service calls |
|
||||
| **Event Publishing Latency / Độ trễ publish event** | < 50ms | Time to publish to Kafka |
|
||||
| **Service Discovery Lookup / Service discovery lookup** | < 10ms | DNS resolution time |
|
||||
| **Gateway Routing Overhead / Chi phí routing của Gateway** | < 20ms | Additional latency added by Traefik |
|
||||
| **Throughput / Thông lượng** | 10,000 req/s | Per service instance |
|
||||
| **Kafka Event Processing / Xử lý Kafka event** | < 500ms | P95 end-to-end event processing |
|
||||
|
||||
**Optimization Strategies / Chiến lược Tối ưu**:
|
||||
**Optimization Strategies**:
|
||||
- **Connection Pooling**: Reuse HTTP connections between services
|
||||
- **Circuit Breaker**: Prevent cascading failures with Opossum library
|
||||
- **Retry with Backoff**: Exponential backoff for transient failures
|
||||
- **Compression**: Enable gzip for large payloads
|
||||
- **Caching**: Cache service discovery results and responses
|
||||
|
||||
## Security Considerations / Cân nhắc Bảo mật
|
||||
## Security Considerations
|
||||
|
||||
**EN**: Security measures for protecting inter-service communication.
|
||||
Security measures for protecting inter-service communication.
|
||||
|
||||
**VI**: Biện pháp bảo mật để bảo vệ giao tiếp giữa các services.
|
||||
|
||||
### Service-to-Service Authentication / Xác thực Service-to-Service
|
||||
### Service-to-Service Authentication
|
||||
|
||||
- **Internal API Keys**: Services authenticate using `x-service-auth` header
|
||||
- **JWT Tokens**: For user context propagation between services
|
||||
- **Mutual TLS (mTLS)**: Optional for production environments (Kubernetes service mesh)
|
||||
|
||||
### Network Security / Bảo mật Mạng
|
||||
### Network Security
|
||||
|
||||
- **Network Policies**: Kubernetes NetworkPolicies restrict service-to-service traffic
|
||||
- **Service Mesh**: Istio/Linkerd for advanced security policies (optional)
|
||||
- **Private Networks**: Services communicate within private VPC/cluster network
|
||||
|
||||
### Data Protection / Bảo vệ Dữ liệu
|
||||
### Data Protection
|
||||
|
||||
- **Encryption in Transit**: TLS 1.2+ for all external communication
|
||||
- **Event Payload Encryption**: Sensitive data encrypted before publishing to Kafka
|
||||
- **API Gateway**: Traefik handles SSL termination and request validation
|
||||
|
||||
### Security Best Practices / Best Practices Bảo mật
|
||||
### Security Best Practices
|
||||
|
||||
```typescript
|
||||
// EN: Service client with authentication
|
||||
// VI: Service client với xác thực
|
||||
// Service client with authentication
|
||||
export class SecureServiceClient {
|
||||
private client = axios.create({
|
||||
baseURL: process.env.SERVICE_URL,
|
||||
@@ -236,17 +222,15 @@ export class SecureServiceClient {
|
||||
'x-correlation-id': generateCorrelationId()
|
||||
},
|
||||
httpsAgent: new https.Agent({
|
||||
rejectUnauthorized: true // EN: Verify SSL certificates / VI: Xác minh SSL certificates
|
||||
rejectUnauthorized: true // Verify SSL certificates
|
||||
})
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
## Deployment / Triển khai
|
||||
## Deployment
|
||||
|
||||
**EN**: How microservices communication is deployed and scaled across environments.
|
||||
|
||||
**VI**: Cách giao tiếp microservices được triển khai và mở rộng qua các môi trường.
|
||||
How microservices communication is deployed and scaled across environments.
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
@@ -274,7 +258,7 @@ graph TD
|
||||
style Redis fill:#ffe1e1
|
||||
```
|
||||
|
||||
### Deployment Environments / Môi trường Triển khai
|
||||
### Deployment Environments
|
||||
|
||||
| Environment | Gateway | Services | Kafka | Service Discovery |
|
||||
|-------------|---------|----------|-------|-------------------|
|
||||
@@ -282,20 +266,18 @@ graph TD
|
||||
| **Staging** | Traefik (2 replicas) | 2 replicas per service | 3 brokers | Kubernetes DNS |
|
||||
| **Production** | Traefik (3+ replicas) | 3+ replicas per service | 5+ brokers | Kubernetes DNS + Service Mesh |
|
||||
|
||||
### Scaling Strategy / Chiến lược Mở rộng
|
||||
### Scaling Strategy
|
||||
|
||||
- **Horizontal Pod Autoscaler (HPA)**: Auto-scale based on CPU/memory
|
||||
- **Kafka Partitions**: Scale event processing by increasing partitions
|
||||
- **Load Balancing**: Kubernetes Service load balances across pod replicas
|
||||
- **Gateway Scaling**: Traefik scales independently from backend services
|
||||
|
||||
## Monitoring & Observability / Giám sát & Khả năng quan sát
|
||||
## Monitoring & Observability
|
||||
|
||||
**EN**: How to monitor and observe microservices communication.
|
||||
How to monitor and observe microservices communication.
|
||||
|
||||
**VI**: Cách giám sát và quan sát giao tiếp microservices.
|
||||
|
||||
### Key Metrics / Chỉ số Chính
|
||||
### Key Metrics
|
||||
|
||||
**Service-to-Service Metrics**:
|
||||
- `http_request_duration_seconds` - Request latency histogram
|
||||
@@ -313,18 +295,16 @@ graph TD
|
||||
- `kafka_consumer_lag` - Consumer lag
|
||||
- `kafka_consumer_records_consumed_total` - Events consumed
|
||||
|
||||
### Health Checks / Kiểm tra Sức khỏe
|
||||
### Health Checks
|
||||
|
||||
**Service Endpoints**:
|
||||
```typescript
|
||||
// EN: Liveness - is service running?
|
||||
// VI: Liveness - service có đang chạy không?
|
||||
// Liveness - is service running?
|
||||
app.get('/health/live', (req, res) => {
|
||||
res.json({ status: 'ok', timestamp: new Date().toISOString() });
|
||||
});
|
||||
|
||||
// EN: Readiness - can service handle traffic?
|
||||
// VI: Readiness - service có thể xử lý traffic không?
|
||||
// Readiness - can service handle traffic?
|
||||
app.get('/health/ready', async (req, res) => {
|
||||
const checks = {
|
||||
database: await checkDatabase(),
|
||||
@@ -354,13 +334,13 @@ readinessProbe:
|
||||
periodSeconds: 5
|
||||
```
|
||||
|
||||
### Distributed Tracing / Tracing Phân tán
|
||||
### Distributed Tracing
|
||||
|
||||
- **OpenTelemetry**: Instrument all service-to-service calls
|
||||
- **Jaeger**: Visualize distributed traces
|
||||
- **Correlation IDs**: Propagate via `x-correlation-id` header for request tracking
|
||||
|
||||
### Monitoring Dashboard / Dashboard Giám sát
|
||||
### Monitoring Dashboard
|
||||
|
||||
**Grafana Panels**:
|
||||
- Service Communication Overview (request rate, latency, errors)
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
# [Tên Kiến trúc]
|
||||
# [Architecture Name] / [Tên Kiến trúc]
|
||||
|
||||
> **Mô tả**: Mô tả ngắn gọn bằng tiếng Việt về thành phần kiến trúc hoặc hệ thống này
|
||||
> **EN**: Brief English description of this architectural component or system
|
||||
> **VI**: Mô tả ngắn gọn bằng tiếng Việt về thành phần kiến trúc hoặc hệ thống này
|
||||
|
||||
## Sơ đồ Tổng quan
|
||||
## Overview Diagram / Sơ đồ Tổng quan
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
A[Thành phần A] --> B[Thành phần B]
|
||||
B --> C[Thành phần C]
|
||||
C --> D[Thành phần D]
|
||||
A[Component A] --> B[Component B]
|
||||
B --> C[Component C]
|
||||
C --> D[Component D]
|
||||
|
||||
style A fill:#e1f5ff
|
||||
style B fill:#fff4e1
|
||||
@@ -16,47 +17,61 @@ graph TD
|
||||
style D fill:#e1ffe1
|
||||
```
|
||||
|
||||
## Mô tả Kiến trúc
|
||||
## Architecture Description / Mô tả Kiến trúc
|
||||
|
||||
Giải thích chi tiết về kiến trúc, bao gồm:
|
||||
### EN: English Section
|
||||
|
||||
Detailed English explanation of the architecture, including:
|
||||
- Purpose and goals
|
||||
- Key components
|
||||
- Design decisions
|
||||
- Technology choices
|
||||
- Trade-offs and considerations
|
||||
|
||||
### VI: Phần Tiếng Việt
|
||||
|
||||
Giải thích chi tiết bằng tiếng Việt về kiến trúc, bao gồm:
|
||||
- Mục đích và mục tiêu
|
||||
- Các thành phần chính
|
||||
- Các thành phần chính
|
||||
- Quyết định thiết kế
|
||||
- Lựa chọn công nghệ
|
||||
- Đánh đổi và cân nhắc
|
||||
|
||||
## Bối cảnh Hệ thống
|
||||
## System Context / Bối cảnh Hệ thống
|
||||
|
||||
```mermaid
|
||||
C4Context
|
||||
title Sơ đồ Bối cảnh Hệ thống cho [Tên Hệ thống]
|
||||
title System Context Diagram for [System Name]
|
||||
|
||||
Person(user, "Người dùng", "Người dùng hệ thống")
|
||||
System(system, "Tên Hệ thống", "Mô tả hệ thống")
|
||||
System_Ext(external, "Hệ thống Bên ngoài", "Phụ thuộc bên ngoài")
|
||||
Person(user, "User", "System user")
|
||||
System(system, "System Name", "System description")
|
||||
System_Ext(external, "External System", "External dependency")
|
||||
|
||||
Rel(user, system, "Sử dụng")
|
||||
Rel(system, external, "Gọi", "HTTPS")
|
||||
Rel(user, system, "Uses")
|
||||
Rel(system, external, "Calls", "HTTPS")
|
||||
```
|
||||
|
||||
## Thành phần
|
||||
## Components / Thành phần
|
||||
|
||||
### Thành phần A
|
||||
### Component A / Thành phần A
|
||||
|
||||
**Mô tả**: Mô tả Thành phần A, trách nhiệm của nó và cách nó khớp vào kiến trúc tổng thể.
|
||||
**EN**: Description of Component A, its responsibilities, and how it fits into the overall architecture.
|
||||
|
||||
**Tính năng chính**:
|
||||
- Tính năng 1
|
||||
- Tính năng 2
|
||||
- Tính năng 3
|
||||
**VI**: Mô tả Thành phần A, trách nhiệm của nó và cách nó khớp vào kiến trúc tổng thể.
|
||||
|
||||
**Công nghệ sử dụng**:
|
||||
- Công nghệ 1
|
||||
- Công nghệ 2
|
||||
**Key Features / Tính năng chính**:
|
||||
- Feature 1 / Tính năng 1
|
||||
- Feature 2 / Tính năng 2
|
||||
- Feature 3 / Tính năng 3
|
||||
|
||||
**Tham chiếu Code**:
|
||||
**Technologies Used / Công nghệ sử dụng**:
|
||||
- Technology 1
|
||||
- Technology 2
|
||||
|
||||
**Code Reference / Tham chiếu Code**:
|
||||
```typescript
|
||||
// Ví dụ code cho thấy cách thành phần này được triển khai
|
||||
// EN: Example code showing how this component is implemented
|
||||
// VI: Ví dụ code cho thấy cách thành phần này được triển khai
|
||||
import { ComponentA } from './component-a';
|
||||
|
||||
const componentA = new ComponentA({
|
||||
@@ -64,35 +79,40 @@ const componentA = new ComponentA({
|
||||
});
|
||||
```
|
||||
|
||||
**Vị trí File**: [`component-a.ts`](file:///path/to/component-a.ts)
|
||||
**File Location**: [`component-a.ts`](file:///path/to/component-a.ts)
|
||||
|
||||
### Thành phần B
|
||||
### Component B / Thành phần B
|
||||
|
||||
(Lặp lại cấu trúc cho mỗi thành phần chính)
|
||||
(Repeat structure for each major component)
|
||||
|
||||
## Luồng Dữ liệu
|
||||
## Data Flow / Luồng Dữ liệu
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant Client as Khách hàng
|
||||
participant Client
|
||||
participant API
|
||||
participant Service as Dịch vụ
|
||||
participant Database as Cơ sở dữ liệu
|
||||
participant Service
|
||||
participant Database
|
||||
|
||||
Client->>API: Yêu cầu
|
||||
API->>Service: Xử lý
|
||||
Service->>Database: Truy vấn
|
||||
Database-->>Service: Kết quả
|
||||
Service-->>API: Phản hồi
|
||||
Client->>API: Request
|
||||
API->>Service: Process
|
||||
Service->>Database: Query
|
||||
Database-->>Service: Result
|
||||
Service-->>API: Response
|
||||
API-->>Client: JSON
|
||||
```
|
||||
|
||||
**Giải thích chi tiết về luồng dữ liệu**:
|
||||
**EN**: Detailed explanation of the data flow:
|
||||
1. Step 1: Description
|
||||
2. Step 2: Description
|
||||
3. Step 3: Description
|
||||
|
||||
**VI**: Giải thích chi tiết về luồng dữ liệu:
|
||||
1. Bước 1: Mô tả
|
||||
2. Bước 2: Mô tả
|
||||
3. Bước 3: Mô tả
|
||||
|
||||
## Kiến trúc Database
|
||||
## Database Architecture / Kiến trúc Database
|
||||
|
||||
```mermaid
|
||||
erDiagram
|
||||
@@ -112,40 +132,56 @@ erDiagram
|
||||
}
|
||||
```
|
||||
|
||||
**Mô tả**: Mô tả schema database, mối quan hệ và quyết định thiết kế.
|
||||
**EN**: Database schema description, relationships, and design decisions.
|
||||
|
||||
## Quyết định Thiết kế
|
||||
**VI**: Mô tả schema database, mối quan hệ và quyết định thiết kế.
|
||||
|
||||
### Quyết định 1: [Tiêu đề Quyết định]
|
||||
## Design Decisions / Quyết định Thiết kế
|
||||
|
||||
**Bối cảnh**: Tại sao quyết định này cần thiết
|
||||
### Decision 1 / Quyết định 1: [Decision Title]
|
||||
|
||||
**Quyết định**: Điều gì đã được quyết định
|
||||
**EN Context**: Why this decision was needed
|
||||
|
||||
**Hậu quả**: Tác động của quyết định (tích cực và tiêu cực)
|
||||
**VI Bối cảnh**: Tại sao quyết định này cần thiết
|
||||
|
||||
**Các lựa chọn thay thế**: Các tùy chọn khác đã được đánh giá
|
||||
**EN Decision**: What was decided
|
||||
|
||||
## Đặc điểm Hiệu suất
|
||||
**VI Quyết định**: Điều gì đã được quyết định
|
||||
|
||||
**Mô tả**: Mô tả kỳ vọng hiệu suất và tối ưu hóa
|
||||
**EN Consequences**: Impact of the decision (positive and negative)
|
||||
|
||||
| Chỉ số | Mục tiêu | Ghi chú |
|
||||
|---------|----------|---------|
|
||||
| Thời gian phản hồi | < 100ms | P95 |
|
||||
| Thông lượng | 1000 req/s | Peak load |
|
||||
| Sử dụng RAM | < 512MB | Mỗi instance |
|
||||
**VI Hậu quả**: Tác động của quyết định (tích cực và tiêu cực)
|
||||
|
||||
## Cân nhắc Bảo mật
|
||||
**EN Alternatives Considered**: Other options that were evaluated
|
||||
|
||||
**Mô tả**: Tính năng bảo mật, xác thực, phân quyền, bảo vệ dữ liệu
|
||||
**VI Các lựa chọn thay thế**: Các tùy chọn khác đã được đánh giá
|
||||
|
||||
- Tính năng bảo mật 1
|
||||
- Tính năng bảo mật 2
|
||||
## Performance Characteristics / Đặc điểm Hiệu suất
|
||||
|
||||
## Triển khai
|
||||
**EN**: Description of performance expectations and optimizations
|
||||
|
||||
**Mô tả**: Cách kiến trúc này được triển khai và mở rộng
|
||||
**VI**: Mô tả kỳ vọng hiệu suất và tối ưu hóa
|
||||
|
||||
| Metric / Chỉ số | Target / Mục tiêu | Notes / Ghi chú |
|
||||
|------------------|-------------------|-----------------|
|
||||
| Response Time / Thời gian phản hồi | < 100ms | P95 |
|
||||
| Throughput / Thông lượng | 1000 req/s | Peak load |
|
||||
| Memory Usage / Sử dụng RAM | < 512MB | Per instance |
|
||||
|
||||
## Security Considerations / Cân nhắc Bảo mật
|
||||
|
||||
**EN**: Security features, authentication, authorization, data protection
|
||||
|
||||
**VI**: Tính năng bảo mật, xác thực, phân quyền, bảo vệ dữ liệu
|
||||
|
||||
- Security feature 1 / Tính năng bảo mật 1
|
||||
- Security feature 2 / Tính năng bảo mật 2
|
||||
|
||||
## Deployment / Triển khai
|
||||
|
||||
**EN**: How this architecture is deployed and scaled
|
||||
|
||||
**VI**: Cách kiến trúc này được triển khai và mở rộng
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
@@ -160,31 +196,33 @@ graph LR
|
||||
C --> Cache
|
||||
```
|
||||
|
||||
## Giám sát & Khả năng quan sát
|
||||
## Monitoring & Observability / Giám sát & Khả năng quan sát
|
||||
|
||||
**Mô tả**: Cách giám sát kiến trúc này, các chỉ số chính, cảnh báo
|
||||
**EN**: How to monitor this architecture, key metrics, alerts
|
||||
|
||||
**Chỉ số chính**:
|
||||
- Chỉ số 1
|
||||
- Chỉ số 2
|
||||
**VI**: Cách giám sát kiến trúc này, các chỉ số chính, cảnh báo
|
||||
|
||||
**Kiểm tra Sức khỏe**:
|
||||
**Key Metrics / Chỉ số chính**:
|
||||
- Metric 1 / Chỉ số 1
|
||||
- Metric 2 / Chỉ số 2
|
||||
|
||||
**Health Checks / Kiểm tra Sức khỏe**:
|
||||
- `/health/live` - Liveness probe
|
||||
- `/health/ready` - Readiness probe
|
||||
|
||||
## Tài liệu Liên quan
|
||||
## Related Documentation / Tài liệu Liên quan
|
||||
|
||||
- [Tài liệu Kiến trúc Liên quan 1](../architecture/related-doc-1.md) - Mô tả
|
||||
- [Hướng dẫn Liên quan](../guides/related-guide.md) - Mô tả
|
||||
- [Skill Liên quan](../skills/related-skill.md) - Mô tả
|
||||
- [Related Arch Doc 1](../architecture/related-doc-1.md) - EN: Description / VI: Mô tả
|
||||
- [Related Guide](../guides/related-guide.md) - EN: Description / VI: Mô tả
|
||||
- [Related Skill](../skills/related-skill.md) - EN: Description / VI: Mô tả
|
||||
|
||||
## Tham khảo
|
||||
## References / Tham khảo
|
||||
|
||||
- [Tài nguyên Bên ngoài 1](https://example.com) - Mô tả
|
||||
- [Tài nguyên Bên ngoài 2](https://example.com) - Mô tả
|
||||
- [External Resource 1](https://example.com) - EN: Description
|
||||
- [External Resource 2](https://example.com) - EN: Description
|
||||
|
||||
---
|
||||
|
||||
**Cập nhật lần cuối**: YYYY-MM-DD
|
||||
**Tác giả**: Tên của bạn
|
||||
**Người review**: Tên người review
|
||||
**Last Updated / Cập nhật lần cuối**: YYYY-MM-DD
|
||||
**Authors / Tác giả**: Your Name
|
||||
**Reviewers / Người review**: Reviewer Names
|
||||
|
||||
@@ -1,20 +1,21 @@
|
||||
# [Tiêu đề Hướng dẫn]
|
||||
# [Guide Title] / [Tiêu đề Hướng dẫn]
|
||||
|
||||
> **Mô tả**: Mô tả ngắn gọn về nội dung hướng dẫn này
|
||||
> **EN**: Brief English description of what this guide covers
|
||||
> **VI**: Mô tả ngắn gọn bằng tiếng Việt về nội dung hướng dẫn này
|
||||
|
||||
## Sơ đồ Quy trình
|
||||
## Workflow Diagram / Sơ đồ Quy trình
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
Start([Bắt đầu]) --> Check{Yêu cầu<br/>Đáp ứng?}
|
||||
Check -->|Không| Install[Cài đặt Yêu cầu]
|
||||
Check -->|Có| Step1[Bước 1: Hành động]
|
||||
Start([Start]) --> Check{Prerequisites<br/>Met?}
|
||||
Check -->|No| Install[Install Prerequisites]
|
||||
Check -->|Yes| Step1[Step 1: Action]
|
||||
Install --> Step1
|
||||
Step1 --> Step2[Bước 2: Hành động]
|
||||
Step2 --> Step3[Bước 3: Hành động]
|
||||
Step3 --> Verify{Xác minh<br/>Thành công?}
|
||||
Verify -->|Không| Troubleshoot[Xem Khắc phục sự cố]
|
||||
Verify -->|Có| End([Hoàn thành])
|
||||
Step1 --> Step2[Step 2: Action]
|
||||
Step2 --> Step3[Step 3: Action]
|
||||
Step3 --> Verify{Verify<br/>Success?}
|
||||
Verify -->|No| Troubleshoot[Check Troubleshooting]
|
||||
Verify -->|Yes| End([Complete])
|
||||
Troubleshoot --> Step1
|
||||
|
||||
style Start fill:#e1f5ff
|
||||
@@ -23,186 +24,234 @@ flowchart LR
|
||||
style Verify fill:#fff3cd
|
||||
```
|
||||
|
||||
## Yêu cầu
|
||||
## Prerequisites / Yêu cầu
|
||||
|
||||
### EN: Requirements
|
||||
|
||||
Before starting this guide, ensure you have:
|
||||
- Requirement 1 with specific version (e.g., Node.js 20+)
|
||||
- Requirement 2
|
||||
- Requirement 3
|
||||
|
||||
### VI: Yêu cầu
|
||||
|
||||
Trước khi bắt đầu hướng dẫn này, hãy đảm bảo bạn có:
|
||||
- Yêu cầu 1 với phiên bản cụ thể (ví dụ: Node.js 20+)
|
||||
- Yêu cầu 2
|
||||
- Yêu cầu 3
|
||||
|
||||
**Kiểm tra nhanh**:
|
||||
**Quick Check / Kiểm tra nhanh**:
|
||||
```bash
|
||||
# Xác minh yêu cầu
|
||||
node --version # Phải là 20 hoặc cao hơn
|
||||
docker --version # Phải được cài đặt
|
||||
# EN: Verify prerequisites / VI: Xác minh yêu cầu
|
||||
node --version # Should be 20 or higher / Phải là 20 hoặc cao hơn
|
||||
docker --version # Should be installed / Phải được cài đặt
|
||||
```
|
||||
|
||||
## Tổng quan
|
||||
## Overview / Tổng quan
|
||||
|
||||
### Bạn Sẽ Học Được Gì
|
||||
### EN: What You'll Learn
|
||||
|
||||
By the end of this guide, you will be able to:
|
||||
1. Outcome 1
|
||||
2. Outcome 2
|
||||
3. Outcome 3
|
||||
|
||||
**Estimated Time / Thời gian ước tính**: X minutes
|
||||
|
||||
### VI: Bạn Sẽ Học Được Gì
|
||||
|
||||
Khi hoàn thành hướng dẫn này, bạn sẽ có thể:
|
||||
1. Kết quả 1
|
||||
2. Kết quả 2
|
||||
3. Kết quả 3
|
||||
|
||||
**Thời gian ước tính**: X phút
|
||||
**Estimated Time / Thời gian ước tính**: X phút
|
||||
|
||||
## Hướng dẫn Từng bước
|
||||
## Step-by-Step Guide / Hướng dẫn Từng bước
|
||||
|
||||
### Bước 1: [Tiêu đề Hành động]
|
||||
### Step 1 / Bước 1: [Action Title]
|
||||
|
||||
**Mô tả**: Giải thích về những gì bước này đạt được và tại sao nó cần thiết.
|
||||
**EN**: English explanation of what this step accomplishes and why it's necessary.
|
||||
|
||||
**VI**: Giải thích tiếng Việt về những gì bước này đạt được và tại sao nó cần thiết.
|
||||
|
||||
```bash
|
||||
# Mô tả lệnh
|
||||
# EN: Command description / VI: Mô tả lệnh
|
||||
command-here --flag value
|
||||
|
||||
# Kết quả mong đợi
|
||||
Thông báo thành công hoặc kết quả
|
||||
# EN: Expected output / VI: Kết quả mong đợi
|
||||
Success message or output
|
||||
```
|
||||
|
||||
**Ghi chú quan trọng**:
|
||||
- Ghi chú 1
|
||||
- Ghi chú 2
|
||||
**Important Notes / Ghi chú quan trọng**:
|
||||
- Note 1 / Ghi chú 1
|
||||
- Note 2 / Ghi chú 2
|
||||
|
||||
**File cần tạo**:
|
||||
**File to Create / File cần tạo**:
|
||||
```bash
|
||||
# Tạo file cấu hình
|
||||
# EN: Create configuration file / VI: Tạo file cấu hình
|
||||
touch .env.local
|
||||
```
|
||||
|
||||
**Nội dung ví dụ**:
|
||||
**Example Content / Nội dung ví dụ**:
|
||||
```env
|
||||
# Biến môi trường
|
||||
# EN: Environment variables / VI: Biến môi trường
|
||||
PORT=5000
|
||||
NODE_ENV=development
|
||||
DATABASE_URL=postgresql://localhost:5432/mydb
|
||||
```
|
||||
|
||||
### Bước 2: [Tiêu đề Hành động]
|
||||
### Step 2 / Bước 2: [Action Title]
|
||||
|
||||
**Mô tả**: Tiếp tục với giải thích bước tiếp theo...
|
||||
**EN**: Continue with next step explanation...
|
||||
|
||||
**VI**: Tiếp tục với giải thích bước tiếp theo...
|
||||
|
||||
```typescript
|
||||
// Ví dụ code cho bước này
|
||||
// EN: Code example for this step
|
||||
// VI: Ví dụ code cho bước này
|
||||
import { Example } from './example';
|
||||
|
||||
const instance = new Example();
|
||||
await instance.initialize();
|
||||
```
|
||||
|
||||
**Kết quả mong đợi**:
|
||||
- ✅ Kết quả 1
|
||||
- ✅ Kết quả 2
|
||||
**Expected Result / Kết quả mong đợi**:
|
||||
- ✅ Result 1 / Kết quả 1
|
||||
- ✅ Result 2 / Kết quả 2
|
||||
|
||||
### Bước 3: [Tiêu đề Hành động]
|
||||
### Step 3 / Bước 3: [Action Title]
|
||||
|
||||
(Tiếp tục mẫu cho mỗi bước)
|
||||
(Continue pattern for each step)
|
||||
|
||||
## Xác minh
|
||||
## Verification / Xác minh
|
||||
|
||||
**Mô tả**: Cách xác minh mọi thứ đang hoạt động chính xác.
|
||||
**EN**: How to verify that everything is working correctly.
|
||||
|
||||
### Kiểm tra nhanh
|
||||
**VI**: Cách xác minh mọi thứ đang hoạt động chính xác.
|
||||
|
||||
### Quick Test / Kiểm tra nhanh
|
||||
|
||||
```bash
|
||||
# Chạy lệnh xác minh
|
||||
# EN: Run verification command / VI: Chạy lệnh xác minh
|
||||
curl http://localhost:5000/health
|
||||
|
||||
# Phản hồi mong đợi
|
||||
# EN: Expected response / VI: Phản hồi mong đợi
|
||||
{"status":"ok","timestamp":"2024-01-01T00:00:00.000Z"}
|
||||
```
|
||||
|
||||
### Danh sách kiểm tra
|
||||
### Verification Checklist / Danh sách kiểm tra
|
||||
|
||||
- [ ] Kiểm tra 1: Mô tả
|
||||
- [ ] Kiểm tra 2: Mô tả
|
||||
- [ ] Kiểm tra 3: Mô tả
|
||||
- [ ] Check 1 / Kiểm tra 1: Description / Mô tả
|
||||
- [ ] Check 2 / Kiểm tra 2: Description / Mô tả
|
||||
- [ ] Check 3 / Kiểm tra 3: Description / Mô tả
|
||||
|
||||
## Vấn đề Thường gặp
|
||||
## Common Issues / Vấn đề Thường gặp
|
||||
|
||||
### Vấn đề 1: [Mô tả Vấn đề]
|
||||
### Issue 1: [Problem Description]
|
||||
|
||||
**Triệu chứng**: Những gì bạn thấy khi vấn đề này xảy ra
|
||||
**EN Symptoms**: What you see when this problem occurs
|
||||
|
||||
**Giải pháp**:
|
||||
**VI Triệu chứng**: Những gì bạn thấy khi vấn đề này xảy ra
|
||||
|
||||
**EN Solution**:
|
||||
```bash
|
||||
# Steps to fix
|
||||
step-1
|
||||
step-2
|
||||
```
|
||||
|
||||
**VI Giải pháp**:
|
||||
```bash
|
||||
# Các bước để sửa
|
||||
step-1
|
||||
step-2
|
||||
```
|
||||
|
||||
### Vấn đề 2: [Mô tả Vấn đề]
|
||||
### Issue 2: [Problem Description]
|
||||
|
||||
(Lặp lại mẫu cho các vấn đề thường gặp)
|
||||
(Repeat pattern for common issues)
|
||||
|
||||
## Cây Quyết định Khắc phục
|
||||
## Troubleshooting Decision Tree / Cây Quyết định Khắc phục
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
Problem[Xảy ra Vấn đề] --> Check1{Kiểm tra 1:<br/>Điều kiện?}
|
||||
Check1 -->|Có| Solution1[Giải pháp 1]
|
||||
Check1 -->|Không| Check2{Kiểm tra 2:<br/>Điều kiện?}
|
||||
Check2 -->|Có| Solution2[Giải pháp 2]
|
||||
Check2 -->|Không| Check3{Kiểm tra 3:<br/>Điều kiện?}
|
||||
Check3 -->|Có| Solution3[Giải pháp 3]
|
||||
Check3 -->|Không| Support[Liên hệ Hỗ trợ]
|
||||
Problem[Problem Occurs] --> Check1{Check 1:<br/>Condition?}
|
||||
Check1 -->|Yes| Solution1[Solution 1]
|
||||
Check1 -->|No| Check2{Check 2:<br/>Condition?}
|
||||
Check2 -->|Yes| Solution2[Solution 2]
|
||||
Check2 -->|No| Check3{Check 3:<br/>Condition?}
|
||||
Check3 -->|Yes| Solution3[Solution 3]
|
||||
Check3 -->|No| Support[Contact Support]
|
||||
|
||||
Solution1 --> Resolved{Đã giải quyết?}
|
||||
Solution1 --> Resolved{Resolved?}
|
||||
Solution2 --> Resolved
|
||||
Solution3 --> Resolved
|
||||
Resolved -->|Không| Support
|
||||
Resolved -->|Có| Success([Thành công])
|
||||
Resolved -->|No| Support
|
||||
Resolved -->|Yes| Success([Success])
|
||||
```
|
||||
|
||||
## Tùy chọn Nâng cao
|
||||
## Advanced Options / Tùy chọn Nâng cao
|
||||
|
||||
**Mô tả**: Cấu hình nâng cao tùy chọn hoặc cách tiếp cận thay thế.
|
||||
**EN**: Optional advanced configurations or alternative approaches.
|
||||
|
||||
### Tùy chọn 1: [Tiêu đề]
|
||||
**VI**: Cấu hình nâng cao tùy chọn hoặc cách tiếp cận thay thế.
|
||||
|
||||
**Mô tả**: Khi nào sử dụng tùy chọn này và cách triển khai.
|
||||
### Option 1 / Tùy chọn 1: [Title]
|
||||
|
||||
**EN**: When to use this option and how to implement it.
|
||||
|
||||
**VI**: Khi nào sử dụng tùy chọn này và cách triển khai.
|
||||
|
||||
```bash
|
||||
# Lệnh ví dụ
|
||||
# Example command
|
||||
advanced-command --option
|
||||
```
|
||||
|
||||
## Bước Tiếp theo
|
||||
## Next Steps / Bước Tiếp theo
|
||||
|
||||
**Mô tả**: Làm gì sau khi hoàn thành hướng dẫn này.
|
||||
**EN**: What to do after completing this guide.
|
||||
|
||||
- [ ] Bước tiếp theo 1: [Hướng dẫn Liên quan](../guides/related-guide.md)
|
||||
- [ ] Bước tiếp theo 2: [Hướng dẫn Khác](../guides/another-guide.md)
|
||||
- [ ] Bước tiếp theo 3: [Tìm hiểu Sâu](../skills/deep-dive.md)
|
||||
**VI**: Làm gì sau khi hoàn thành hướng dẫn này.
|
||||
|
||||
## Tài nguyên Bổ sung
|
||||
- [ ] Next step 1 / Bước tiếp theo 1: [Related Guide](../guides/related-guide.md)
|
||||
- [ ] Next step 2 / Bước tiếp theo 2: [Another Guide](../guides/another-guide.md)
|
||||
- [ ] Next step 3 / Bước tiếp theo 3: [Deep Dive](../skills/deep-dive.md)
|
||||
|
||||
### Tài liệu Liên quan
|
||||
## Additional Resources / Tài nguyên Bổ sung
|
||||
|
||||
- [Hướng dẫn Liên quan 1](../guides/guide-1.md) - Mô tả
|
||||
- [Kiến trúc Liên quan](../architecture/arch-doc.md) - Mô tả
|
||||
- [Skill Liên quan](../skills/skill-doc.md) - Mô tả
|
||||
### Related Documentation / Tài liệu Liên quan
|
||||
|
||||
### Tài nguyên Bên ngoài
|
||||
- [Related Guide 1](../guides/guide-1.md) - EN: Description / VI: Mô tả
|
||||
- [Related Architecture](../architecture/arch-doc.md) - EN: Description / VI: Mô tả
|
||||
- [Related Skill](../skills/skill-doc.md) - EN: Description / VI: Mô tả
|
||||
|
||||
- [Tài liệu Chính thức](https://example.com) - Nội dung bao gồm
|
||||
- [Bài hướng dẫn](https://example.com) - Mô tả video hoặc bài viết
|
||||
### External Resources / Tài nguyên Bên ngoài
|
||||
|
||||
## Câu hỏi Thường gặp
|
||||
- [Official Documentation](https://example.com) - EN: What it covers
|
||||
- [Tutorial](https://example.com) - EN: Video or article description
|
||||
|
||||
### Câu hỏi 1?
|
||||
## FAQ / Câu hỏi Thường gặp
|
||||
|
||||
Câu trả lời 1.
|
||||
### EN: Question 1?
|
||||
|
||||
### Câu hỏi 2?
|
||||
Answer 1 in English.
|
||||
|
||||
Câu trả lời 2.
|
||||
### VI: Câu hỏi 1?
|
||||
|
||||
Câu trả lời 1 bằng tiếng Việt.
|
||||
|
||||
### EN: Question 2?
|
||||
|
||||
Answer 2 in English.
|
||||
|
||||
### VI: Câu hỏi 2?
|
||||
|
||||
Câu trả lời 2 bằng tiếng Việt.
|
||||
|
||||
---
|
||||
|
||||
**Cập nhật lần cuối**: YYYY-MM-DD
|
||||
**Độ khó**: Beginner/Intermediate/Advanced
|
||||
**Thời gian ước tính**: X phút
|
||||
**Tác giả**: Tên của bạn
|
||||
**Last Updated / Cập nhật lần cuối**: YYYY-MM-DD
|
||||
**Difficulty / Độ khó**: Beginner/Intermediate/Advanced
|
||||
**Estimated Time / Thời gian ước tính**: X minutes
|
||||
**Authors / Tác giả**: Your Name
|
||||
|
||||
@@ -1,18 +1,19 @@
|
||||
# Pattern [Tên Pattern]
|
||||
# [Pattern Name] Pattern / Pattern [Tên Pattern]
|
||||
|
||||
> **Mô tả**: Mô tả ngắn gọn về khi nào và tại sao sử dụng pattern này
|
||||
> **EN**: Brief English description of when and why to use this pattern
|
||||
> **VI**: Mô tả ngắn gọn bằng tiếng Việt về khi nào và tại sao sử dụng pattern này
|
||||
|
||||
## Tổng quan Pattern
|
||||
## Pattern Overview / Tổng quan Pattern
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
Input[Đầu vào/Yêu cầu] --> Process[Xử lý Pattern]
|
||||
Process --> Output[Đầu ra/Kết quả]
|
||||
Input[Input/Request] --> Process[Pattern Process]
|
||||
Process --> Output[Output/Result]
|
||||
|
||||
subgraph Pattern["Triển khai Pattern"]
|
||||
Process --> Step1[Bước 1]
|
||||
Step1 --> Step2[Bước 2]
|
||||
Step2 --> Step3[Bước 3]
|
||||
subgraph Pattern["Pattern Implementation"]
|
||||
Process --> Step1[Step 1]
|
||||
Step1 --> Step2[Step 2]
|
||||
Step2 --> Step3[Step 3]
|
||||
end
|
||||
|
||||
style Input fill:#e1f5ff
|
||||
@@ -20,9 +21,24 @@ graph LR
|
||||
style Pattern fill:#f0e1ff
|
||||
```
|
||||
|
||||
## Khi nào sử dụng
|
||||
## When to Use / Khi nào sử dụng
|
||||
|
||||
### EN: Use this pattern when
|
||||
|
||||
- Scenario 1: Description of when this pattern is beneficial
|
||||
- Scenario 2: Another use case
|
||||
- Scenario 3: Additional context
|
||||
|
||||
**DO use this pattern for**:
|
||||
- ✅ Use case 1
|
||||
- ✅ Use case 2
|
||||
|
||||
**DON'T use this pattern for**:
|
||||
- ❌ Anti-pattern 1
|
||||
- ❌ Anti-pattern 2
|
||||
|
||||
### VI: Sử dụng pattern này khi
|
||||
|
||||
Sử dụng pattern này khi:
|
||||
- Tình huống 1: Mô tả khi pattern này có lợi
|
||||
- Tình huống 2: Trường hợp sử dụng khác
|
||||
- Tình huống 3: Bối cảnh bổ sung
|
||||
@@ -35,29 +51,40 @@ Sử dụng pattern này khi:
|
||||
- ❌ Anti-pattern 1
|
||||
- ❌ Anti-pattern 2
|
||||
|
||||
## Khái niệm Cốt lõi
|
||||
## Core Concepts / Khái niệm Cốt lõi
|
||||
|
||||
### Nguyên tắc Chính
|
||||
### EN: Key Principles
|
||||
|
||||
1. **Principle 1**: Description of the first core principle
|
||||
2. **Principle 2**: Description of the second core principle
|
||||
3. **Principle 3**: Description of the third core principle
|
||||
|
||||
### VI: Nguyên tắc Chính
|
||||
|
||||
1. **Nguyên tắc 1**: Mô tả nguyên tắc cốt lõi đầu tiên
|
||||
2. **Nguyên tắc 2**: Mô tả nguyên tắc cốt lõi thứ hai
|
||||
3. **Nguyên tắc 3**: Mô tả nguyên tắc cốt lõi thứ ba
|
||||
|
||||
## Triển khai
|
||||
## Implementation / Triển khai
|
||||
|
||||
### Triển khai Cơ bản
|
||||
### Basic Implementation / Triển khai Cơ bản
|
||||
|
||||
Giải thích từng bước về cách triển khai pattern này.
|
||||
**EN**: Step-by-step explanation of how to implement this pattern.
|
||||
|
||||
**VI**: Giải thích từng bước về cách triển khai pattern này.
|
||||
|
||||
```typescript
|
||||
// Ví dụ triển khai cơ bản
|
||||
// EN: Basic implementation example
|
||||
// VI: Ví dụ triển khai cơ bản
|
||||
|
||||
/**
|
||||
* Class triển khai pattern
|
||||
* EN: Pattern implementation class
|
||||
* VI: Class triển khai pattern
|
||||
*/
|
||||
export class ExamplePattern {
|
||||
/**
|
||||
* Constructor với các dependencies
|
||||
* EN: Constructor with dependencies
|
||||
* VI: Constructor với các dependencies
|
||||
*/
|
||||
constructor(
|
||||
private dependency1: Dependency1,
|
||||
@@ -65,36 +92,43 @@ export class ExamplePattern {
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Phương thức cốt lõi triển khai pattern
|
||||
* EN: Core method implementing the pattern
|
||||
* VI: Phương thức cốt lõi triển khai pattern
|
||||
*
|
||||
* @param input - Dữ liệu đầu vào
|
||||
* @returns Kết quả đã xử lý
|
||||
* @param input - EN: Input data / VI: Dữ liệu đầu vào
|
||||
* @returns EN: Processed result / VI: Kết quả đã xử lý
|
||||
*/
|
||||
async execute(input: InputType): Promise<OutputType> {
|
||||
// Bước 1: Validate đầu vào
|
||||
// EN: Step 1: Validate input
|
||||
// VI: Bước 1: Validate đầu vào
|
||||
this.validateInput(input);
|
||||
|
||||
// Bước 2: Xử lý
|
||||
// EN: Step 2: Process
|
||||
// VI: Bước 2: Xử lý
|
||||
const processed = await this.process(input);
|
||||
|
||||
// Bước 3: Trả về kết quả
|
||||
// EN: Step 3: Return result
|
||||
// VI: Bước 3: Trả về kết quả
|
||||
return this.formatOutput(processed);
|
||||
}
|
||||
|
||||
private validateInput(input: InputType): void {
|
||||
// Logic validation
|
||||
// EN: Validation logic
|
||||
// VI: Logic validation
|
||||
if (!input) {
|
||||
throw new Error('Đầu vào là bắt buộc');
|
||||
throw new Error('Input is required / Đầu vào là bắt buộc');
|
||||
}
|
||||
}
|
||||
|
||||
private async process(input: InputType): Promise<ProcessedType> {
|
||||
// Logic nghiệp vụ cốt lõi
|
||||
// EN: Core business logic
|
||||
// VI: Logic nghiệp vụ cốt lõi
|
||||
return await this.dependency1.transform(input);
|
||||
}
|
||||
|
||||
private formatOutput(processed: ProcessedType): OutputType {
|
||||
// Định dạng cho đầu ra
|
||||
// EN: Format for output
|
||||
// VI: Định dạng cho đầu ra
|
||||
return {
|
||||
success: true,
|
||||
data: processed,
|
||||
@@ -103,12 +137,19 @@ export class ExamplePattern {
|
||||
}
|
||||
```
|
||||
|
||||
### Triển khai Nâng cao
|
||||
**File Location / Vị trí File**:
|
||||
- **Template**: [`_template/src/modules/example/example.pattern.ts`](file:///Users/velikho/Desktop/WORKING/Base/services/_template/src/modules/example/example.pattern.ts)
|
||||
- **Production**: [`iam-service/src/modules/example/example.pattern.ts`](file:///Users/velikho/Desktop/WORKING/Base/services/iam-service/src/modules/example/example.pattern.ts)
|
||||
|
||||
Triển khai phức tạp hơn với các tính năng bổ sung.
|
||||
### Advanced Implementation / Triển khai Nâng cao
|
||||
|
||||
**EN**: More complex implementation with additional features.
|
||||
|
||||
**VI**: Triển khai phức tạp hơn với các tính năng bổ sung.
|
||||
|
||||
```typescript
|
||||
// Triển khai nâng cao với caching và xử lý lỗi
|
||||
// EN: Advanced implementation with caching and error handling
|
||||
// VI: Triển khai nâng cao với caching và xử lý lỗi
|
||||
|
||||
export class AdvancedExamplePattern extends ExamplePattern {
|
||||
constructor(
|
||||
@@ -121,7 +162,8 @@ export class AdvancedExamplePattern extends ExamplePattern {
|
||||
}
|
||||
|
||||
async execute(input: InputType): Promise<OutputType> {
|
||||
// Thử cache trước
|
||||
// EN: Try cache first
|
||||
// VI: Thử cache trước
|
||||
const cacheKey = this.getCacheKey(input);
|
||||
const cached = await this.cache.get<OutputType>(cacheKey);
|
||||
|
||||
@@ -131,17 +173,20 @@ export class AdvancedExamplePattern extends ExamplePattern {
|
||||
}
|
||||
|
||||
try {
|
||||
// Thực thi logic pattern
|
||||
// EN: Execute pattern logic
|
||||
// VI: Thực thi logic pattern
|
||||
const result = await super.execute(input);
|
||||
|
||||
// Cache kết quả
|
||||
await this.cache.set(cacheKey, result, 300); // 5 phút
|
||||
// EN: Cache result
|
||||
// VI: Cache kết quả
|
||||
await this.cache.set(cacheKey, result, 300); // 5 minutes
|
||||
|
||||
return result;
|
||||
} catch (error) {
|
||||
// Xử lý lỗi
|
||||
this.logger.error('Thực thi pattern thất bại', { error, input });
|
||||
throw new PatternExecutionError('Thực thi thất bại', { cause: error });
|
||||
// EN: Error handling
|
||||
// VI: Xử lý lỗi
|
||||
this.logger.error('Pattern execution failed', { error, input });
|
||||
throw new PatternExecutionError('Execution failed', { cause: error });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -151,9 +196,9 @@ export class AdvancedExamplePattern extends ExamplePattern {
|
||||
}
|
||||
```
|
||||
|
||||
## Sơ đồ Pattern
|
||||
## Pattern Diagram / Sơ đồ Pattern
|
||||
|
||||
### Cấu trúc Class
|
||||
### Class Structure / Cấu trúc Class
|
||||
|
||||
```mermaid
|
||||
classDiagram
|
||||
@@ -173,14 +218,25 @@ classDiagram
|
||||
-getCacheKey(input: InputType): string
|
||||
}
|
||||
|
||||
class Dependency1 {
|
||||
+transform(input: InputType): ProcessedType
|
||||
}
|
||||
|
||||
class CacheService {
|
||||
+get(key: string): Promise~any~
|
||||
+set(key: string, value: any, ttl: number): Promise~void~
|
||||
}
|
||||
|
||||
ExamplePattern <|-- AdvancedExamplePattern
|
||||
ExamplePattern --> Dependency1
|
||||
AdvancedExamplePattern --> CacheService
|
||||
```
|
||||
|
||||
### Luồng Tuần tự
|
||||
### Sequence Flow / Luồng Tuần tự
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant Client as Khách hàng
|
||||
participant Client
|
||||
participant Pattern as ExamplePattern
|
||||
participant Dep1 as Dependency1
|
||||
participant Cache as CacheService
|
||||
@@ -197,19 +253,23 @@ sequenceDiagram
|
||||
Pattern-->>Client: result
|
||||
```
|
||||
|
||||
## Ví dụ Sử dụng
|
||||
## Usage Examples / Ví dụ Sử dụng
|
||||
|
||||
### Ví dụ 1: Sử dụng Cơ bản
|
||||
### Example 1 / Ví dụ 1: Basic Usage
|
||||
|
||||
Tình huống sử dụng cơ bản với giải thích.
|
||||
**EN**: Basic usage scenario with explanation.
|
||||
|
||||
**VI**: Tình huống sử dụng cơ bản với giải thích.
|
||||
|
||||
```typescript
|
||||
// Thiết lập
|
||||
// EN: Setup
|
||||
// VI: Thiết lập
|
||||
const dependency1 = new Dependency1();
|
||||
const dependency2 = new Dependency2();
|
||||
const pattern = new ExamplePattern(dependency1, dependency2);
|
||||
|
||||
// Thực thi pattern
|
||||
// EN: Execute pattern
|
||||
// VI: Thực thi pattern
|
||||
const input: InputType = {
|
||||
id: '123',
|
||||
data: 'example',
|
||||
@@ -218,15 +278,19 @@ const input: InputType = {
|
||||
const result = await pattern.execute(input);
|
||||
|
||||
console.log(result);
|
||||
// Kết quả: { success: true, data: { ... } }
|
||||
// EN: Output / VI: Kết quả:
|
||||
// { success: true, data: { ... } }
|
||||
```
|
||||
|
||||
### Ví dụ 2: Sử dụng Nâng cao
|
||||
### Example 2 / Ví dụ 2: Advanced Usage with Caching
|
||||
|
||||
Sử dụng nâng cao với caching được bật.
|
||||
**EN**: Advanced usage with caching enabled.
|
||||
|
||||
**VI**: Sử dụng nâng cao với caching được bật.
|
||||
|
||||
```typescript
|
||||
// Thiết lập với các dependencies bổ sung
|
||||
// EN: Setup with additional dependencies
|
||||
// VI: Thiết lập với các dependencies bổ sung
|
||||
const cache = new CacheService();
|
||||
const logger = new Logger();
|
||||
const pattern = new AdvancedExamplePattern(
|
||||
@@ -236,118 +300,176 @@ const pattern = new AdvancedExamplePattern(
|
||||
logger
|
||||
);
|
||||
|
||||
// Lần gọi đầu tiên (cache miss)
|
||||
// EN: First call (cache miss)
|
||||
// VI: Lần gọi đầu tiên (cache miss)
|
||||
const result1 = await pattern.execute(input);
|
||||
|
||||
// Lần gọi thứ hai (cache hit)
|
||||
const result2 = await pattern.execute(input); // Trả về kết quả cached
|
||||
// EN: Second call (cache hit)
|
||||
// VI: Lần gọi thứ hai (cache hit)
|
||||
const result2 = await pattern.execute(input); // Returns cached result
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
## Best Practices / Best Practices
|
||||
|
||||
### Thực hành Được đề xuất
|
||||
### EN: Recommended Practices
|
||||
|
||||
1. **Practice 1**: Description of best practice with reasoning
|
||||
2. **Practice 2**: Another important guideline
|
||||
3. **Practice 3**: Additional recommendation
|
||||
|
||||
**Configuration / Cấu hình**:
|
||||
```typescript
|
||||
const config = {
|
||||
timeout: 5000,
|
||||
retries: 3,
|
||||
cacheTime: 300, // 5 minutes
|
||||
};
|
||||
```
|
||||
|
||||
### VI: Thực hành Được đề xuất
|
||||
|
||||
1. **Nguyên tắc 1**: Mô tả best practice với lý do
|
||||
2. **Nguyên tắc 2**: Hướng dẫn quan trọng khác
|
||||
3. **Nguyên tắc 3**: Khuyến nghị bổ sung
|
||||
|
||||
**Cấu hình**:
|
||||
```typescript
|
||||
const config = {
|
||||
timeout: 5000,
|
||||
retries: 3,
|
||||
cacheTime: 300, // 5 phút
|
||||
};
|
||||
```
|
||||
## Common Mistakes / Lỗi Thường gặp
|
||||
|
||||
## Lỗi Thường gặp
|
||||
### EN: Mistakes to Avoid
|
||||
|
||||
### Lỗi 1: [Mô tả]
|
||||
#### Mistake 1 / Lỗi 1: [Description]
|
||||
|
||||
```typescript
|
||||
// ❌ KHÔNG TỐT: Triển khai không chính xác
|
||||
const result = await pattern.execute(null); // Sẽ throw error
|
||||
// ❌ BAD: Incorrect implementation
|
||||
const result = await pattern.execute(null); // Will throw error
|
||||
```
|
||||
|
||||
```typescript
|
||||
// ✅ TỐT: Triển khai chính xác
|
||||
// ✅ GOOD: Correct implementation
|
||||
if (input) {
|
||||
const result = await pattern.execute(input);
|
||||
}
|
||||
```
|
||||
|
||||
**Tại sao**: Giải thích tại sao cách tiếp cận đầu tiên là không tốt và cách thứ hai là tốt.
|
||||
**EN Why**: Explanation of why the first approach is bad and the second is good.
|
||||
|
||||
## Cân nhắc Hiệu suất
|
||||
**VI Tại sao**: Giải thích tại sao cách tiếp cận đầu tiên là không tốt và cách thứ hai là tốt.
|
||||
|
||||
**Mô tả**: Đặc điểm hiệu suất và mẹo tối ưu hóa.
|
||||
#### Mistake 2 / Lỗi 2: [Description]
|
||||
|
||||
| Khía cạnh | Tác động | Giảm thiểu |
|
||||
|-----------|----------|------------|
|
||||
| Sử dụng RAM | Trung bình | Sử dụng caching có chiến lược |
|
||||
| Sử dụng CPU | Thấp | N/A |
|
||||
| Thao tác I/O | Cao | Triển khai connection pooling |
|
||||
(Repeat pattern for each common mistake)
|
||||
|
||||
## Kiểm thử
|
||||
## Performance Considerations / Cân nhắc Hiệu suất
|
||||
|
||||
**EN**: Performance characteristics and optimization tips.
|
||||
|
||||
**VI**: Đặc điểm hiệu suất và mẹo tối ưu hóa.
|
||||
|
||||
| Aspect / Khía cạnh | Impact / Tác động | Mitigation / Giảm thiểu |
|
||||
|---------------------|-------------------|-------------------------|
|
||||
| Memory usage / Sử dụng RAM | Medium / Trung bình | Use caching strategically / Sử dụng caching có chiến lược |
|
||||
| CPU usage / Sử dụng CPU | Low / Thấp | N/A |
|
||||
| I/O operations / Thao tác I/O | High / Cao | Implement connection pooling / Triển khai connection pooling |
|
||||
|
||||
## Testing / Kiểm thử
|
||||
|
||||
### Unit Test Example / Ví dụ Unit Test
|
||||
|
||||
```typescript
|
||||
// Unit test cho pattern
|
||||
// EN: Unit test for the pattern
|
||||
// VI: Unit test cho pattern
|
||||
|
||||
describe('ExamplePattern', () => {
|
||||
let pattern: ExamplePattern;
|
||||
let mockDep1: jest.Mocked<Dependency1>;
|
||||
let mockDep2: jest.Mocked<Dependency2>;
|
||||
|
||||
beforeEach(() => {
|
||||
mockDep1 = {
|
||||
transform: jest.fn(),
|
||||
} as any;
|
||||
mockDep2 = {} as any;
|
||||
|
||||
pattern = new ExamplePattern(mockDep1, {} as any);
|
||||
pattern = new ExamplePattern(mockDep1, mockDep2);
|
||||
});
|
||||
|
||||
it('nên thực thi thành công', async () => {
|
||||
// Chuẩn bị
|
||||
it('should execute successfully', async () => {
|
||||
// EN: Arrange
|
||||
// VI: Chuẩn bị
|
||||
const input = { id: '123', data: 'test' };
|
||||
const expectedProcessed = { transformed: true };
|
||||
mockDep1.transform.mockResolvedValue(expectedProcessed);
|
||||
|
||||
// Thực thi
|
||||
// EN: Act
|
||||
// VI: Thực thi
|
||||
const result = await pattern.execute(input);
|
||||
|
||||
// Kiểm tra
|
||||
// EN: Assert
|
||||
// VI: Kiểm tra
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.data).toEqual(expectedProcessed);
|
||||
expect(mockDep1.transform).toHaveBeenCalledWith(input);
|
||||
});
|
||||
|
||||
it('nên throw error cho đầu vào không hợp lệ', async () => {
|
||||
// Mong đợi lỗi cho đầu vào null
|
||||
it('should throw error for invalid input', async () => {
|
||||
// EN: Expect error for null input
|
||||
// VI: Mong đợi lỗi cho đầu vào null
|
||||
await expect(pattern.execute(null as any))
|
||||
.rejects
|
||||
.toThrow('Đầu vào là bắt buộc');
|
||||
.toThrow('Input is required');
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
## Patterns Liên quan
|
||||
## Related Patterns / Patterns Liên quan
|
||||
|
||||
Các patterns khác bổ sung hoặc liên quan đến pattern này.
|
||||
**EN**: Other patterns that complement or relate to this one.
|
||||
|
||||
- [Pattern Liên quan 1](./related-pattern-1.md) - Cách nó liên quan
|
||||
- [Pattern Liên quan 2](./related-pattern-2.md) - So sánh
|
||||
- [Pattern Thay thế](./alternative-pattern.md) - Khi nào sử dụng thay thế
|
||||
**VI**: Các patterns khác bổ sung hoặc liên quan đến pattern này.
|
||||
|
||||
## Tài nguyên Bổ sung
|
||||
- [Related Pattern 1](./related-pattern-1.md) - EN: How it relates / VI: Cách nó liên quan
|
||||
- [Related Pattern 2](./related-pattern-2.md) - EN: Comparison / VI: So sánh
|
||||
- [Alternative Pattern](./alternative-pattern.md) - EN: When to use instead / VI: Khi nào sử dụng thay thế
|
||||
|
||||
### Tài liệu Liên quan
|
||||
## Real-World Examples / Ví dụ Thực tế
|
||||
|
||||
**EN**: Examples of this pattern used in the codebase.
|
||||
|
||||
**VI**: Ví dụ về pattern này được sử dụng trong codebase.
|
||||
|
||||
### Example from IAM Service
|
||||
|
||||
**File**: [`iam-service/src/modules/rbac/rbac.service.ts`](file:///Users/velikho/Desktop/WORKING/Base/services/iam-service/src/modules/rbac/rbac.service.ts)
|
||||
|
||||
```typescript
|
||||
// EN: Real implementation from IAM service
|
||||
// VI: Triển khai thực tế từ IAM service
|
||||
export class RBACService implements ExamplePattern {
|
||||
// ... implementation
|
||||
}
|
||||
```
|
||||
|
||||
## Additional Resources / Tài nguyên Bổ sung
|
||||
|
||||
### EN: Related Documentation
|
||||
|
||||
- [API Design Guide](../api-design.md) - How this pattern fits into API design
|
||||
- [Error Handling](../error-handling-patterns.md) - Error handling for this pattern
|
||||
- [Testing Guide](../testing-patterns.md) - Testing strategies
|
||||
|
||||
### VI: Tài liệu Liên quan
|
||||
|
||||
- [Hướng dẫn Thiết kế API](../api-design.md) - Pattern này khớp với thiết kế API như thế nào
|
||||
- [Xử lý Lỗi](../error-handling-patterns.md) - Xử lý lỗi cho pattern này
|
||||
- [Hướng dẫn Kiểm thử](../testing-patterns.md) - Chiến lược kiểm thử
|
||||
|
||||
### External Resources / Tài nguyên Bên ngoài
|
||||
|
||||
- [Design Patterns Book](https://example.com) - Classic reference
|
||||
- [Blog Post](https://example.com) - Modern interpretation
|
||||
|
||||
---
|
||||
|
||||
**Cập nhật lần cuối**: YYYY-MM-DD
|
||||
**Độ phức tạp**: Beginner/Intermediate/Advanced
|
||||
**Danh mục**: [Tên Danh mục]
|
||||
**Tác giả**: Tên của bạn
|
||||
**Last Updated / Cập nhật lần cuối**: YYYY-MM-DD
|
||||
**Complexity / Độ phức tạp**: Beginner/Intermediate/Advanced
|
||||
**Category / Danh mục**: [Category Name]
|
||||
**Authors / Tác giả**: Your Name
|
||||
|
||||
Reference in New Issue
Block a user