feat(docs): Enhance Vietnamese documentation with updated diagrams and troubleshooting flowcharts

- Revised the Vietnamese documentation to include clearer instructions and improved Mermaid diagrams for better visualization.
- Added detailed troubleshooting flowcharts to assist users in diagnosing issues effectively.
- Updated color palette references and visual elements in diagrams for consistency and clarity.
- Enhanced the structure of various guides, ensuring alignment between English and Vietnamese versions.
- Included quick tips and common issues sections to facilitate user navigation through the documentation.
This commit is contained in:
Ho Ngoc Hai
2026-01-08 16:57:56 +07:00
parent 2a09a6e989
commit b441a7757a
11 changed files with 1272 additions and 251 deletions

View File

@@ -15,7 +15,7 @@ Bước 5 - Color Palette (CHI TIẾT HƠN)
- Color Palette Reference đầy đủ
- Checklist áp dụng màu chi tiết
- Pattern cho từng loại node
⚠️ Lưu ý: Sử dụng bảng màu tối.
⚠️ Lưu ý: Sử dụng bảng màu tối và text chữ trắng.
Bước 8 - Verification (MỚI)
- Checklist kiểm tra chất lượng
- Đảm bảo đồng bộ VI-EN

View File

@@ -36,9 +36,15 @@ const ITEM_ORDER: Record<string, string[]> = {
'guides': [
'getting-started', // EN: Always show getting started first / VI: Luôn hiển thị getting started đầu tiên
'local-development', // EN: Then local setup / VI: Sau đó là local setup
'development', // EN: Then development / VI: Sau đó là development
'deployment', // EN: Then deployment / VI: Sau đó là deployment
// EN: Other items will be alphabetically sorted / VI: Các items khác sẽ được sắp xếp theo alphabet
'development',
'local-deployment',
'deployment',
'kubernetes-local',
'mermaid',
'neon-database',
'observability',
'troubleshooting',
'iam-migration',
],
'architecture': [
'system-design', // EN: Overview first / VI: Overview trước

View File

@@ -97,35 +97,35 @@ flowchart TD
DeepDebug --> RedisInspect[Inspect Redis]
DeepDebug --> APITest[Direct API Testing]
style Start fill:#1a1a2e
style Resolved fill:#0f3460
style CheckStatus fill:#16213e
style ServiceType fill:#16213e
style ErrorType fill:#16213e
style DBCheck fill:#16213e
style RedisCheck fill:#16213e
style TraefikCheck fill:#16213e
style GatewayTest fill:#16213e
style ServiceTest fill:#16213e
style Verify fill:#16213e
style LogAnalysis fill:#16213e
style InfraCheck fill:#1a1a40
style AppCheck fill:#1a1a40
style DBSolution fill:#0f4c75
style RedisSolution fill:#0f4c75
style TraefikSolution fill:#0f4c75
style ConfigFix fill:#0f4c75
style PrismaFix fill:#0f4c75
style AuthFix fill:#0f4c75
style Restart fill:#3282b8
style DeepDebug fill:#1b262c
style IdentifyService fill:#1a1a40
style CheckLogs fill:#1a1a40
style ConnCheck fill:#1a1a40
style ContainerShell fill:#0f3460
style PrismaStudio fill:#0f3460
style RedisInspect fill:#0f3460
style APITest fill:#0f3460
style Start fill:#1a1a2e,color:#fff
style Resolved fill:#0f3460,color:#fff
style CheckStatus fill:#16213e,color:#fff
style ServiceType fill:#16213e,color:#fff
style ErrorType fill:#16213e,color:#fff
style DBCheck fill:#16213e,color:#fff
style RedisCheck fill:#16213e,color:#fff
style TraefikCheck fill:#16213e,color:#fff
style GatewayTest fill:#16213e,color:#fff
style ServiceTest fill:#16213e,color:#fff
style Verify fill:#16213e,color:#fff
style LogAnalysis fill:#16213e,color:#fff
style InfraCheck fill:#1a1a40,color:#fff
style AppCheck fill:#1a1a40,color:#fff
style DBSolution fill:#0f4c75,color:#fff
style RedisSolution fill:#0f4c75,color:#fff
style TraefikSolution fill:#0f4c75,color:#fff
style ConfigFix fill:#0f4c75,color:#fff
style PrismaFix fill:#0f4c75,color:#fff
style AuthFix fill:#0f4c75,color:#fff
style Restart fill:#3282b8,color:#fff
style DeepDebug fill:#1b262c,color:#fff
style IdentifyService fill:#1a1a40,color:#fff
style CheckLogs fill:#1a1a40,color:#fff
style ConnCheck fill:#1a1a40,color:#fff
style ContainerShell fill:#0f3460,color:#fff
style PrismaStudio fill:#0f3460,color:#fff
style RedisInspect fill:#0f3460,color:#fff
style APITest fill:#0f3460,color:#fff
```
---

View File

@@ -6,6 +6,99 @@ Tài liệu này hướng dẫn cách migrate từ `auth-service` sang `iam-serv
IAM Service là phiên bản mở rộng của Auth Service với các tính năng bổ sung về Identity Management, Access Management, và Governance & Compliance. Tất cả các API endpoints của Auth Service vẫn được giữ nguyên để đảm bảo backward compatibility.
### 🔄 Migration Process Flow
```mermaid
graph TD
Start([🚀 Bắt đầu Migration]) --> Backup[📦 Step 1: Backup<br/>Database & Code]
Backup --> Update[🔧 Step 2: Update Codebase<br/>Package refs, Env vars]
Update --> Migrate[🗄️ Step 3: Run Prisma Migration<br/>Add IAM models]
Migrate --> Deploy{🚀 Deployment Strategy}
Deploy -->|Khuyến nghị| BlueGreen[💚 Blue-Green Deployment]
Deploy -->|Dễ dàng hơn| InPlace[⚡ In-Place Migration]
BlueGreen --> DeployNew[Deploy IAM Service mới]
DeployNew --> Verify1[✅ Verify hoạt động]
Verify1 --> Switch[🔀 Switch traffic]
Switch --> Monitor1[📊 Monitor]
Monitor1 --> Success{Thành công?}
InPlace --> DeployBoth[Deploy cả 2 service]
DeployBoth --> GradualRoute[🔀 Gradually route traffic]
GradualRoute --> Monitor2[📊 Monitor]
Monitor2 --> Success
Success -->|Yes| Cleanup[🧹 Decommission Auth Service]
Success -->|No| Rollback[⏮️ Rollback]
Cleanup --> Complete([✨ Migration Hoàn Thành])
Rollback --> End([❌ Migration Failed])
style Start fill:#1a472a,stroke:#2d8659,stroke-width:3px,color:#fff
style Complete fill:#1a472a,stroke:#2d8659,stroke-width:3px,color:#fff
style End fill:#4a1a1a,stroke:#8b2e2e,stroke-width:3px,color:#fff
style Backup fill:#1e3a5f,stroke:#2e5984,color:#fff
style Update fill:#1e3a5f,stroke:#2e5984,color:#fff
style Migrate fill:#1e3a5f,stroke:#2e5984,color:#fff
style Deploy fill:#4a2c5f,stroke:#6b4391,color:#fff
style BlueGreen fill:#2d5016,stroke:#4a7c2c,color:#fff
style InPlace fill:#5f4a1e,stroke:#8b7030,color:#fff
style DeployNew fill:#1e3a5f,stroke:#2e5984,color:#fff
style Verify1 fill:#1e3a5f,stroke:#2e5984,color:#fff
style Switch fill:#1e3a5f,stroke:#2e5984,color:#fff
style Monitor1 fill:#1e3a5f,stroke:#2e5984,color:#fff
style DeployBoth fill:#1e3a5f,stroke:#2e5984,color:#fff
style GradualRoute fill:#1e3a5f,stroke:#2e5984,color:#fff
style Monitor2 fill:#1e3a5f,stroke:#2e5984,color:#fff
style Success fill:#4a2c5f,stroke:#6b4391,color:#fff
style Cleanup fill:#1e3a5f,stroke:#2e5984,color:#fff
style Rollback fill:#4a1a1a,stroke:#8b2e2e,color:#fff
```
### 🏗️ Architecture Evolution
```mermaid
graph TB
subgraph Before["Auth Service (Trước)"]
AuthAPI[🔐 Authentication APIs<br/>/api/v1/auth/*]
RBACAPI[👥 RBAC APIs<br/>/api/v1/rbac/*]
MFAAPI[🔒 MFA APIs<br/>/api/v1/mfa/*]
SessionAPI[🎫 Session APIs<br/>/api/v1/sessions/*]
OIDCAPI[🆔 OIDC APIs<br/>/api/v1/oidc/*]
end
subgraph After["IAM Service (Sau)"]
AuthAPI2[🔐 Authentication APIs<br/>/api/v1/auth/*<br/>✅ Giữ nguyên]
RBACAPI2[👥 RBAC APIs<br/>/api/v1/rbac/*<br/>✅ Giữ nguyên]
MFAAPI2[🔒 MFA APIs<br/>/api/v1/mfa/*<br/>✅ Giữ nguyên]
SessionAPI2[🎫 Session APIs<br/>/api/v1/sessions/*<br/>✅ Giữ nguyên]
OIDCAPI2[🆔 OIDC APIs<br/>/api/v1/oidc/*<br/>✅ Giữ nguyên]
IdentityAPI[🆔 Identity Management<br/>/api/v1/identity/*<br/>⭐ MỚI]
AccessAPI[🔑 Access Management<br/>/api/v1/access/*<br/>⭐ MỚI]
GovernanceAPI[📋 Governance<br/>/api/v1/governance/*<br/>⭐ MỚI]
end
Before -.->|Backward Compatible<br/>Migration| After
style Before fill:#2d2d2d,stroke:#4a4a4a,color:#fff
style After fill:#1a472a,stroke:#2d8659,color:#fff
style AuthAPI fill:#1e3a5f,stroke:#2e5984,color:#fff
style RBACAPI fill:#1e3a5f,stroke:#2e5984,color:#fff
style MFAAPI fill:#1e3a5f,stroke:#2e5984,color:#fff
style SessionAPI fill:#1e3a5f,stroke:#2e5984,color:#fff
style OIDCAPI fill:#1e3a5f,stroke:#2e5984,color:#fff
style AuthAPI2 fill:#2d5016,stroke:#4a7c2c,color:#fff
style RBACAPI2 fill:#2d5016,stroke:#4a7c2c,color:#fff
style MFAAPI2 fill:#2d5016,stroke:#4a7c2c,color:#fff
style SessionAPI2 fill:#2d5016,stroke:#4a7c2c,color:#fff
style OIDCAPI2 fill:#2d5016,stroke:#4a7c2c,color:#fff
style IdentityAPI fill:#4a2c5f,stroke:#6b4391,color:#fff
style AccessAPI fill:#4a2c5f,stroke:#6b4391,color:#fff
style GovernanceAPI fill:#4a2c5f,stroke:#6b4391,color:#fff
```
## Backward Compatibility
**Tất cả các endpoints hiện tại vẫn hoạt động bình thường:**
@@ -120,6 +213,32 @@ cp -r services/auth-service services/auth-service.backup
### Step 3: Deployment
#### 🎯 Deployment Strategy Comparison
```mermaid
graph LR
subgraph BlueGreen["💚 Blue-Green Deployment (Khuyến nghị)"]
BG1[Ưu điểm:<br/>✅ Zero downtime<br/>✅ Easy rollback<br/>✅ Safe testing]
BG2[Nhược điểm:<br/>⚠️ Cần thêm resources<br/>⚠️ Phức tạp hơn]
end
subgraph InPlace["⚡ In-Place Migration"]
IP1[Ưu điểm:<br/>✅ Simple setup<br/>✅ Less resources<br/>✅ Gradual migration]
IP2[Nhược điểm:<br/>⚠️ Potential downtime<br/>⚠️ Harder rollback<br/>⚠️ Higher risk]
end
Decision{Chọn Strategy} -->|Production| BlueGreen
Decision -->|Staging/Dev| InPlace
style BlueGreen fill:#1a472a,stroke:#2d8659,color:#fff
style InPlace fill:#5f4a1e,stroke:#8b7030,color:#fff
style BG1 fill:#2d5016,stroke:#4a7c2c,color:#fff
style BG2 fill:#4a1a1a,stroke:#8b2e2e,color:#fff
style IP1 fill:#2d5016,stroke:#4a7c2c,color:#fff
style IP2 fill:#4a1a1a,stroke:#8b2e2e,color:#fff
style Decision fill:#4a2c5f,stroke:#6b4391,color:#fff
```
#### Option A: Blue-Green Deployment (Khuyến Nghị)
1. **Deploy iam-service mới:**
@@ -199,6 +318,77 @@ Nếu gặp vấn đề trong quá trình migration, vui lòng:
2. Review migration guide này
3. Contact team lead hoặc DevOps team
## 💡 Quick Tips
### Migration Best Practices
✅ **DO:**
- Backup database trước khi migrate
- Test migration trên staging trước
- Monitor metrics trong quá trình migration
- Sử dụng Blue-Green deployment cho production
- Prepare rollback plan trước khi deploy
- Document tất cả các thay đổi
❌ **DON'T:**
- Skip backup step
- Migrate trực tiếp trên production
- Ignore error logs
- Deploy vào giờ peak traffic
- Quên update environment variables
- Rush migration process
### Common Issues & Solutions
| Vấn đề | Nguyên nhân | Giải pháp |
|--------|-------------|-----------|
| 🔴 Migration failed | Database connection | Check `DATABASE_URL` trong `.env` |
| 🔴 Service won't start | Missing env vars | Verify tất cả env vars được set |
| 🟡 Slow performance | Database indexes | Run Prisma migrations đầy đủ |
| 🟡 Connection timeout | Network issues | Check firewall & security groups |
| 🔵 New endpoints 404 | Routing config | Update Traefik/Ingress config |
### Troubleshooting Quick Reference
```bash
# Check migration status
pnpm prisma migrate status
# View service logs
docker logs iam-service-local -f
kubectl logs deployment/iam-service -f --tail=100
# Test health endpoint
curl http://localhost:5001/health
curl http://localhost:5001/health/ready
# Database connection test
psql $DATABASE_URL -c "SELECT 1"
# Rollback migration (CAREFUL!)
pnpm prisma migrate reset # DEV ONLY
kubectl rollout undo deployment/iam-service
```
### 📊 Color Palette Reference
**Diagram Colors:**
- 🟢 **Success/Recommended**: `#1a472a` (Dark green)
- 🔵 **Process/Info**: `#1e3a5f` (Dark blue)
- 🟣 **Decision/Important**: `#4a2c5f` (Dark purple)
- 🟡 **Warning/Alternative**: `#5f4a1e` (Dark yellow)
- 🔴 **Error/Rollback**: `#4a1a1a` (Dark red)
### ⚠️ Important Reminders
- 📦 **Always backup** trước khi migrate
- 🧪 **Test thoroughly** trên staging
- 📊 **Monitor closely** sau khi deploy
- 🔄 **Prepare rollback** plan
- 📝 **Document changes** cho team
-**Schedule wisely** - tránh giờ peak
- 🤝 **Communicate** với team và stakeholders
---
**Last Updated**: 2024-12-30

View File

@@ -1,51 +1,53 @@
# Hướng Dẫn Deploy Kubernetes Local
> **EN**: Local Kubernetes Deployment Guide
>
> **VI**: Hướng dẫn triển khai Kubernetes cục bộ
> Hướng dẫn triển khai Kubernetes cục bộ với Docker Desktop trên macOS
**Cập nhật**: 2026-01-05
**Độ khó**: Trung bình (Intermediate)
**Độ khó**: Trung bình
**Thời gian**: 30-45 phút
## Workflow / Quy Trình
## Quy Trình Deploy
```mermaid
graph TD
Start([Bắt đầu / Start]) --> EnvPrep[1. Chuẩn bị Môi trường<br/>Environment Prep]
Start([🚀 Bắt đầu]) --> EnvPrep[1. Chuẩn bị Môi trường]
EnvPrep --> BuildImg[2. Build Docker Image]
BuildImg --> LoadImg[3. Load Image vào Cluster<br/>(Kind/Docker Desktop)]
LoadImg --> Secrets[4. Cấu hình Secrets<br/>& Environment]
Secrets --> Deploy[5. Deploy Service<br/>(K8s Manifests)]
BuildImg --> LoadImg[3. Load Image vào Cluster]
LoadImg --> Secrets[4. Cấu hình Secrets & Environment]
Secrets --> Deploy[5. Deploy Service]
Deploy --> Verify[6. Kiểm tra & Verify]
Verify --> Test[7. Test Service<br/>(Port Forward & Curl)]
Test --> End([Hoàn tất / Complete])
Verify --> Test[7. Test Service]
Test --> End([Hoàn tất])
subgraph "Chi tiết Deploy / Deployment Details"
Deploy --> |Apply| ConfigMap
Deploy --> |Apply| Deployment
Deploy --> |Apply| Service
subgraph "Chi tiết Deploy"
Deploy --> |Apply| ConfigMap[ConfigMap]
Deploy --> |Apply| Deployment[Deployment]
Deploy --> |Apply| Service[Service]
end
style Start fill:#d4edda,stroke:#28a745,stroke-width:2px
style End fill:#d4edda,stroke:#28a745,stroke-width:2px
style EnvPrep fill:#e2e3e5,stroke:#6c757d
style BuildImg fill:#fff3cd,stroke:#ffc107
style LoadImg fill:#fff3cd,stroke:#ffc107
style Secrets fill:#f8d7da,stroke:#dc3545
style Deploy fill:#cce5ff,stroke:#007bff
style Verify fill:#cce5ff,stroke:#007bff
style Start fill:#1a1a2e,color:#fff
style End fill:#0f3460,color:#fff
style EnvPrep fill:#16213e,color:#fff
style BuildImg fill:#1a1a40,color:#fff
style LoadImg fill:#1a1a40,color:#fff
style Secrets fill:#0f4c75,color:#fff
style Deploy fill:#3282b8,color:#fff
style Verify fill:#3282b8,color:#fff
style Test fill:#3282b8,color:#fff
style ConfigMap fill:#16213e,color:#fff
style Deployment fill:#16213e,color:#fff
style Service fill:#16213e,color:#fff
```
## Tổng Quan / Overview
## Tổng Quan
Hướng dẫn này mô tả chi tiết cách deploy IAM Service (hoặc bất kỳ microservice nào trong hệ sinh thái GoodGo) lên local Kubernetes cluster sử dụng Docker Desktop trên macOS.
> **Lưu ý quan trọng**: Hướng dẫn này giả định bạn đang sử dụng **Docker Desktop** với **Kubernetes enabled**. Nếu bạn sử dụng Minikube hoặc Kind thuần, các bước có thể hơi khác một chút (đặc biệt là phần load image).
> **Lưu ý**: Hướng dẫn này giả định bạn đang sử dụng **Docker Desktop** với **Kubernetes enabled**. Nếu bạn sử dụng Minikube hoặc Kind thuần, các bước có thể hơi khác một chút (đặc biệt là phần load image).
## 1. Yêu Cầu / Prerequisites
## 1. Yêu Cầu
### Phần Mềm / Software
### Phần Mềm
- **Docker Desktop 4.0+**: [Download Link](https://www.docker.com/products/docker-desktop/)
- Kubernetes phải được enable trong settings.
- **kubectl CLI**: Công cụ dòng lệnh để tương tác với K8s.
@@ -61,12 +63,12 @@ Hướng dẫn này mô tả chi tiết cách deploy IAM Service (hoặc bất k
npm install -g pnpm
```
### Kiến Thức / Knowledge
### Kiến Thức
- Hiểu cơ bản về các khái niệm Kubernetes: **Pod**, **Deployment**, **Service**, **Secret**, **ConfigMap**.
- Quen thuộc với các lệnh Docker cơ bản (`docker build`, `docker images`).
- Biết cách điều hướng và chạy lệnh trong Terminal.
## 2. Chuẩn Bị Môi Trường / Environment Preparation
## 2. Chuẩn Bị Môi Trường
### 2.1 Enable Kubernetes trong Docker Desktop
@@ -83,13 +85,11 @@ Hướng dẫn này mô tả chi tiết cách deploy IAM Service (hoặc bất k
Kiểm tra xem `kubectl` đã kết nối đúng context chưa:
```bash
# EN: Check current context
# VI: Kiểm tra context hiện tại
# Kiểm tra context hiện tại
kubectl config current-context
# Output mong đợi: docker-desktop
# EN: List all nodes in the cluster
# VI: Liệt kê các node trong cluster
# Lit kê các node trong cluster
kubectl get nodes
# Output mong đợi:
# NAME STATUS ROLES AGE VERSION
@@ -101,17 +101,14 @@ kubectl get nodes
Chúng ta cần build image của service trước khi deploy. Ở đây lấy ví dụ là `iam-service`.
```bash
# EN: Navigate to the kubernetes deployment directory
# VI: Di chuyển đến thư mục deployments/local/kubernetes
# Di chuyển đến thư mục deployments/local/kubernetes
cd deployments/local/kubernetes
# EN: Build the Docker image from the root context
# VI: Build Docker image từ root context
# Build Docker image từ root context
# Lưu ý: -f trỏ đến Dockerfile của service, context là root (../../..)
docker build -t iam-service:local -f ../../../services/iam-service/Dockerfile ../../..
# EN: Verify the image was built successfully
# VI: Kiểm tra image đã build thành công chưa
# Kiểm tra image đã build thành công chưa
docker images | grep iam-service
# Output mong đợi:
# iam-service local [IMAGE_ID] [SIZE] [CREATED]
@@ -119,17 +116,15 @@ docker images | grep iam-service
## 4. Load Image vào Cluster
**⚠️ QUAN TRỌNG / IMPORTANT**: Docker Desktop có thể sử dụng các backend khác nhau. Nếu bạn đang chạy Kubernetes trong Docker Desktop, đôi khi nó không nhìn thấy image local ngay lập tức nếu sử dụng `kind` node dưới nền.
**⚠️ QUAN TRỌNG**: Docker Desktop có thể sử dụng các backend khác nhau. Nếu bạn đang chạy Kubernetes trong Docker Desktop, đôi khi nó không nhìn thấy image local ngay lập tức nếu sử dụng `kind` node dưới nền.
Nếu bạn dùng **Kind** (Kubernetes in Docker) riêng biệt hoặc cấu hình Docker Desktop đặc biệt, bạn cần load image:
```bash
# EN: Load image into kind cluster (if using kind explicitly)
# VI: Load image vào kind cluster (nếu dùng kind rõ ràng)
# Load image o kind cluster (nếu dùng kind rõ ràng)
kind load docker-image iam-service:local --name desktop
# EN: Validating image presence (optional, hard with Docker Desktop K8s directly)
# VI: Kiểm tra sự tồn tại của image (tùy chọn)
# Kiểm tra sự tồn tại của image (tùy chọn)
```
> **Mẹo**: Với Docker Desktop mặc định, việc build image local (`docker build ...`) thường tự động khả dụng cho K8s cluster của Docker Desktop. Bước load này chủ yếu dành cho ai dùng `kind` CLI để tạo cluster riêng.
@@ -143,12 +138,10 @@ Môi trường Kubernetes cần các biến môi trường nhạy cảm (Secrets
Bạn có thể chạy script hoặc lệnh sau để tạo secrets an toàn.
```bash
# EN: Create a dedicated namespace for local testing
# VI: Tạo namespace riêng cho local testing
# Tạo namespace riêng cho local testing
kubectl create namespace iam-local
# EN: Generate random secrets and store in Kubernetes
# VI: Tạo secrets ngẫu nhiên và lưu vào Kubernetes
# Tạo secrets ngẫu nhiên và lưu vào Kubernetes
kubectl create secret generic iam-service-secrets \
--from-literal=DATABASE_URL="postgresql://user:password@host.docker.internal:5432/iam_db?schema=public" \
--from-literal=JWT_SECRET="$(openssl rand -base64 32)" \
@@ -156,8 +149,7 @@ kubectl create secret generic iam-service-secrets \
--from-literal=ENCRYPTION_KEY="$(openssl rand -base64 32)" \
-n iam-local
# EN: Verify secrets creation
# VI: Kiểm tra secrets đã tạo
# Kiểm tra secrets đã tạo
kubectl get secrets -n iam-local
```
@@ -168,8 +160,7 @@ kubectl get secrets -n iam-local
File `iam-service-configmap.yaml` thường chứa các biến không nhạy cảm như `NODE_ENV`, `LOG_LEVEL`.
```bash
# EN: Apply ConfigMap
# VI: Apply ConfigMap
# Apply ConfigMap
kubectl apply -f iam-service-configmap.yaml -n iam-local
```
@@ -178,24 +169,21 @@ kubectl apply -f iam-service-configmap.yaml -n iam-local
Bây giờ chúng ta sẽ deploy các resource chính.
```bash
# EN: Apply Deployment manifest
# VI: Apply file Deployment manifest
# Apply file Deployment manifest
kubectl apply -f iam-service-deployment.yaml -n iam-local
# EN: Apply Service manifest (LoadBalancer/NodePort)
# VI: Apply file Service manifest
# Apply file Service manifest
kubectl apply -f iam-service-service.yaml -n iam-local
```
## 7. Verify & Debug / Kiểm Tra & Gỡ Lỗi
## 7. Verify & Debug
Sau khi deploy, cần đảm bảo Pod đang chạy ổn định (Running).
### 7.1 Kiểm tra Pods
```bash
# EN: Get all pods in the namespace
# VI: Lấy danh sách pod trong namespace
# Lấy danh sách pod trong namespace
kubectl get pods -n iam-local
# Output mong đợi:
@@ -208,16 +196,14 @@ kubectl get pods -n iam-local
Nếu Status không phải `Running` (ví dụ `CrashLoopBackOff` hoặc `ImagePullBackOff`), hãy xem logs:
```bash
# EN: Stream logs from the pod
# VI: Xem logs thời gian thực từ pod
# Xem logs thời gian thực từ pod
kubectl logs -f -n iam-local -l app=iam-service
# EN: Describe pod to see events (pull error, mounts, scheduling)
# VI: Xem chi tiết pod để check events (lỗi pull, mount, scheduling)
# Xem chi tiết pod để check events (lỗi pull, mount, scheduling)
kubectl describe pod -n iam-local -l app=iam-service
```
### 7.3 Common Errors / Lỗi Thường Gặp
### 7.3 Lỗi Thường Gặp
1. **ImagePullBackOff**:
- **Lý do**: K8s không tìm thấy image `iam-service:local`.
@@ -236,8 +222,7 @@ kubectl describe pod -n iam-local -l app=iam-service
Để truy cập service từ máy local, cách an toàn nhất là dùng `port-forward`.
```bash
# EN: Port forward from local port 5002 to service port 80
# VI: Port forward từ cổng local 5002 tới cổng 80 của service
# Port forward từ cổng local 5002 tới cổng 80 của service
kubectl port-forward svc/iam-service 5002:80 -n iam-local
# Terminal sẽ treo và hiện: Forwarding from 127.0.0.1:5002 -> 8000
@@ -246,28 +231,125 @@ kubectl port-forward svc/iam-service 5002:80 -n iam-local
Mở terminal khác và test:
```bash
# EN: Test Health Check
# VI: Test Health Check
# Test Health Check
curl http://localhost:5002/health/live
# Response: {"status":"ok", ...}
# EN: View Swagger/OpenAPI docs (if enabled)
# VI: Xem tài liệu Swagger/OpenAPI (nếu bật)
# Xem tài liệu Swagger/OpenAPI (nếu bật)
open http://localhost:5002/api-docs
```
## 9. Cleanup / Dọn Dẹp
## 9. Cleanup
Khi hoàn tất, hãy xóa resources để giải phóng tài nguyên.
```bash
# EN: Delete the namespace (removes all resources within)
# VI: Xóa namespace (xóa tất cả resource bên trong)
# Xóa namespace (xóa tất cả resource bên trong)
kubectl delete namespace iam-local
```
## Tài Liệu Tham Khảo / References
---
## Quick Tips
### 🎯 Lệnh Kubectl Hữu Ích
```bash
# Xem tất cả resources trong namespace
kubectl get all -n iam-local
# Xem logs của tất cả pods với label
kubectl logs -f -n iam-local -l app=iam-service --tail=100
# Exec vào pod để debug
kubectl exec -it -n iam-local deployment/iam-service -- sh
# Xem resource usage
kubectl top pods -n iam-local
# Restart deployment
kubectl rollout restart deployment/iam-service -n iam-local
# Xem rollout history
kubectl rollout history deployment/iam-service -n iam-local
# Rollback về version trước
kubectl rollout undo deployment/iam-service -n iam-local
```
### 🔍 Debug Patterns
| Vấn đề | Lệnh kiểm tra | Giải pháp |
|--------|--------------|----------|
| Pod không start | `kubectl describe pod -n iam-local <pod-name>` | Kiểm tra Events section |
| Image pull failed | `kubectl get events -n iam-local` | Đảm bảo `imagePullPolicy: IfNotPresent` |
| Service unreachable | `kubectl get svc -n iam-local` | Kiểm tra port mapping |
| Config issues | `kubectl get configmap -n iam-local -o yaml` | Verify config values |
| Secret issues | `kubectl get secret -n iam-local` | Check secret exists |
### 📋 Deployment Checklist
- [ ] ✅ Docker Desktop Kubernetes enabled
- [ ] ✅ kubectl context = `docker-desktop`
- [ ] ✅ Image built locally: `docker images | grep iam-service`
- [ ] ✅ Namespace created: `kubectl get ns iam-local`
- [ ] ✅ Secrets created: `kubectl get secrets -n iam-local`
- [ ] ✅ ConfigMap applied: `kubectl get cm -n iam-local`
- [ ] ✅ Deployment applied: `kubectl get deploy -n iam-local`
- [ ] ✅ Service created: `kubectl get svc -n iam-local`
- [ ] ✅ Pods running: `kubectl get pods -n iam-local`
- [ ] ✅ Port-forward works: `kubectl port-forward ...`
- [ ] ✅ Health check passes: `curl http://localhost:5002/health/live`
### 💾 Resource Management
**Recommended Resources per Pod:**
```yaml
resources:
requests:
memory: "256Mi"
cpu: "250m"
limits:
memory: "512Mi"
cpu: "500m"
```
**Check Resource Usage:**
```bash
# Overall cluster resources
kubectl top nodes
# Pod resource usage
kubectl top pods -n iam-local
# Detailed pod metrics
kubectl describe node docker-desktop
```
### 🛡️ Best Practices
1. **Sử dụng namespaces** để tách biệt môi trường
2. **Set resource limits** cho mọi pod
3. **Use health checks** (liveness & readiness probes)
4. **Tag images** với version cụ thể, không dùng `:latest`
5. **Store secrets** trong Kubernetes Secrets, không hardcode
6. **Use ConfigMaps** cho configuration
7. **Enable logging** để dễ debug
8. **Regular cleanup** các resources không dùng
### 🎨 Visual Indicators
Khi đọc pod status:
- 🟢 `Running` = Pod hoạt động bình thường
- 🟡 `Pending` = Đang chờ scheduling
- 🔴 `CrashLoopBackOff` = Pod liên tục crash
- 🔵 `ContainerCreating` = Đang tạo container
- ⚠️ `ImagePullBackOff` = Không pull được image
### 🔗 Tài Liệu Tham Khảo
- [Kubernetes Documentation](https://kubernetes.io/docs/)
- [Docker Desktop for Mac](https://docs.docker.com/desktop/mac/networking/)
- [Prisma Deployment Guide](https://www.prisma.io/docs/guides/deployment/deployment-guides/deploying-to-kubernetes)
- [kubectl Cheat Sheet](https://kubernetes.io/docs/reference/kubectl/cheatsheet/)
- [Kubernetes Best Practices](https://kubernetes.io/docs/concepts/configuration/overview/)

View File

@@ -1,4 +1,4 @@
# Triển Khai Phát Triển Cục Bộ
# Hướng dẫn Local Deployment
Thư mục này chứa cấu hình Docker Compose để chạy toàn bộ nền tảng GoodGo ở local.

View File

@@ -1,4 +1,4 @@
# Hướng Dẫn Phát Triển Local (Local Development)
# Hướng Dẫn Local Development
>Hướng dẫn phát triển cục bộ

View File

@@ -1,36 +1,28 @@
# Mermaid Diagram Guide / Hướng dẫn Sơ đồ Mermaid
# Hướng dẫn Sơ đồ Mermaid
## Overview / Tổng quan
## Tổng quan
**EN**: This guide helps you choose the right Mermaid diagram type for your documentation and provides examples for common use cases.
Hướng dẫn này giúp bạn chọn loại sơ đồ Mermaid phù hợp cho tài liệu của bạn và cung cấp ví dụ cho các trường hợp sử dụng phổ biến.
**VI**: Hướng dẫn này giúp bạn chọn loại sơ đồ Mermaid phù hợp cho tài liệu của bạn và cung cấp ví dụ cho các trường hợp sử dụng phổ biến.
## Tham chiếu Nhanh
## Quick Reference / Tham chiếu Nhanh
| Diagram Type / Loại | Use For / Sử dụng cho | Complexity / Độ phức tạp |
|----------------------|------------------------|---------------------------|
| **Flowchart** | Workflows, decision trees / Quy trình, cây quyết định | ⭐⭐ |
| **Sequence Diagram** | API interactions, request flows / Tương tác API, luồng request | ⭐⭐ |
| **Class Diagram** | Code structure, patterns / Cấu trúc code, patterns | ⭐⭐⭐ |
| **Graph** | System architecture, dependencies / Kiến trúc hệ thống, dependencies | ⭐⭐ |
| **ER Diagram** | Database schema / Schema database | ⭐⭐⭐ |
| **Gantt** | Timeline, project schedule / Timeline, lịch trình dự án | ⭐⭐ |
| **C4 Diagram** | System context, containers / Bối cảnh hệ thống, containers | ⭐⭐⭐⭐ |
| Loại Sơ đồ | Sử dụng cho | Độ phức tạp |
|-------------|-------------|-------------|
| **Flowchart** | Quy trình, cây quyết định | ⭐⭐ |
| **Sequence Diagram** | Tương tác API, luồng request | ⭐⭐⭐ |
| **Class Diagram** | Cấu trúc code, patterns | ⭐⭐ |
| **Graph** | Kiến trúc hệ thống, dependencies | ⭐⭐ |
| **ER Diagram** | Schema database | ⭐⭐⭐ |
| **Gantt** | Timeline, lịch trình dự án | ⭐⭐ |
| **C4 Diagram** | Bối cảnh hệ thống, containers | ⭐⭐⭐ |
---
## 1. Flowcharts / Sơ đồ Luồng
## 1. Sơ đồ Luồng (Flowcharts)
### When to Use / Khi nào sử dụng
### Khi nào sử dụng
**EN**: Use flowcharts for:
- Step-by-step guides and workflows
- Decision trees and conditional logic
- Process flows with multiple branches
- Troubleshooting procedures
**VI**: Sử dụng flowcharts cho:
Sử dụng flowcharts cho:
- Hướng dẫn từng bước và quy trình (ví dụ: Quy trình đăng ký tài khoản)
- Cây quyết định và logic điều kiện (ví dụ: Luồng phê duyệt đơn hàng)
- Luồng quy trình với nhiều nhánh (ví dụ: Xử lý thanh toán đa kênh)
@@ -48,10 +40,13 @@ flowchart TD
Output --> End([End])
Error --> End
style Start fill:#2980b9,stroke:#333,stroke-width:2px,color:#fff
style End fill:#27ae60,stroke:#333,stroke-width:2px,color:#fff
style Check fill:#f39c12,stroke:#333,stroke-width:2px,color:#fff
style Error fill:#c0392b,stroke:#333,stroke-width:2px,color:#fff
style Start fill:#2C3E50,color:#ECF0F1,stroke:#34495E,stroke-width:3px
style End fill:#27AE60,color:#ECF0F1,stroke:#229954,stroke-width:3px
style Check fill:#E67E22,color:#ECF0F1,stroke:#D35400,stroke-width:2px
style Error fill:#C0392B,color:#ECF0F1,stroke:#A93226,stroke-width:2px
style Input fill:#8E44AD,color:#ECF0F1,stroke:#7D3C98,stroke-width:2px
style Process fill:#8E44AD,color:#ECF0F1,stroke:#7D3C98,stroke-width:2px
style Output fill:#8E44AD,color:#ECF0F1,stroke:#7D3C98,stroke-width:2px
```
**Giải thích**: Sơ đồ này minh họa quy trình từ lúc Bắt đầu -> Nhận đầu vào -> Kiểm tra tính hợp lệ -> Xử lý (nếu hợp lệ) hoặc Báo lỗi (nếu không) -> Kết thúc.
@@ -69,10 +64,13 @@ flowchart TD
Output --> End([End])
Error --> End
style Start fill:#2980b9,stroke:#333,stroke-width:2px,color:#fff
style End fill:#27ae60,stroke:#333,stroke-width:2px,color:#fff
style Check fill:#f39c12,stroke:#333,stroke-width:2px,color:#fff
style Error fill:#c0392b,stroke:#333,stroke-width:2px,color:#fff
style Start fill:#2C3E50,color:#ECF0F1,stroke:#34495E,stroke-width:3px
style End fill:#27AE60,color:#ECF0F1,stroke:#229954,stroke-width:3px
style Check fill:#E67E22,color:#ECF0F1,stroke:#D35400,stroke-width:2px
style Error fill:#C0392B,color:#ECF0F1,stroke:#A93226,stroke-width:2px
style Input fill:#8E44AD,color:#ECF0F1,stroke:#7D3C98,stroke-width:2px
style Process fill:#8E44AD,color:#ECF0F1,stroke:#7D3C98,stroke-width:2px
style Output fill:#8E44AD,color:#ECF0F1,stroke:#7D3C98,stroke-width:2px
```
````
@@ -94,7 +92,16 @@ flowchart LR
C --> I[End]
H --> I
style Processing fill:#f0e1ff
style A fill:#3498DB,color:#ECF0F1,stroke:#2980B9,stroke-width:2px
style B fill:#E67E22,color:#ECF0F1,stroke:#D35400,stroke-width:2px
style C fill:#C0392B,color:#ECF0F1,stroke:#A93226,stroke-width:2px
style D fill:#8E44AD,color:#ECF0F1,stroke:#7D3C98,stroke-width:2px
style E fill:#8E44AD,color:#ECF0F1,stroke:#7D3C98,stroke-width:2px
style F fill:#8E44AD,color:#ECF0F1,stroke:#7D3C98,stroke-width:2px
style G fill:#8E44AD,color:#ECF0F1,stroke:#7D3C98,stroke-width:2px
style H fill:#27AE60,color:#ECF0F1,stroke:#229954,stroke-width:2px
style I fill:#7F8C8D,color:#ECF0F1,stroke:#5D6D7E,stroke-width:2px
style Processing fill:#2C3E50,color:#ECF0F1,stroke:#34495E,stroke-width:2px
```
**Giải thích**: Sơ đồ này cho thấy quy trình xử lý request phức tạp hơn với các logic nhóm trong `subgraph`. Nếu Auth thất bại, trả về 401. Nếu thành công, tiếp tục xử lý, validate, chạy logic, format và trả về 200 OK.
@@ -102,17 +109,11 @@ flowchart LR
---
## 2. Sequence Diagrams / Sơ đồ Tuần tự
## 2. Sơ đồ Tuần tự (Sequence Diagrams)
### When to Use / Khi nào sử dụng
### Khi nào sử dụng
**EN**: Use sequence diagrams for:
- API communication flows
- Authentication/authorization flows
- Service-to-service interactions
- Request/response cycles
**VI**: Sử dụng sequence diagrams cho:
Sử dụng sequence diagrams cho:
- Luồng giao tiếp API (ví dụ: API tạo đơn hàng mới)
- Luồng xác thực/phân quyền (ví dụ: Luồng đăng nhập và cấp Token)
- Tương tác giữa các service (ví dụ: Order Service gọi Inventory Service)
@@ -187,17 +188,11 @@ sequenceDiagram
---
## 3. Class Diagrams / Sơ đồ Class
## 3. Sơ đồ Class (Class Diagrams)
### When to Use / Khi nào sử dụng
### Khi nào sử dụng
**EN**: Use class diagrams for:
- Design patterns and code structure
- Object-oriented architecture
- Inheritance and relationships
- Module dependencies
**VI**: Sử dụng class diagrams cho:
Sử dụng class diagrams cho:
- Design patterns và cấu trúc code (ví dụ: Singleton Pattern cho Logger)
- Kiến trúc hướng đối tượng (ví dụ: Cấu trúc Class User và Admin)
- Kế thừa và mối quan hệ (ví dụ: BaseRepository và UserRepository)
@@ -206,6 +201,7 @@ sequenceDiagram
### Basic Class Diagram
```mermaid
%%{init: {'theme':'dark'}}%%
classDiagram
class BaseRepository {
#prisma: PrismaClient
@@ -236,17 +232,11 @@ classDiagram
---
## 4. Graph Diagrams / Sơ đồ Graph
## 4. Sơ đồ Graph (Graph Diagrams)
### When to Use / Khi nào sử dụng
### Khi nào sử dụng
**EN**: Use graph diagrams for:
- System architecture overview
- Component relationships
- Data flow diagrams
- Dependency graphs
**VI**: Sử dụng graph diagrams cho:
Sử dụng graph diagrams cho:
- Tổng quan kiến trúc hệ thống (ví dụ: Kiến trúc Microservices)
- Mối quan hệ giữa các thành phần (ví dụ: Web Client kết nối Gateway)
- Sơ đồ luồng dữ liệu (ví dụ: Dữ liệu từ API xuống Database)
@@ -269,9 +259,13 @@ graph TD
IAM --> Cache
User --> Cache
style Gateway fill:#2980b9,stroke:#333,stroke-width:2px,color:#fff
style DB fill:#8e44ad,stroke:#333,stroke-width:2px,color:#fff
style Cache fill:#f39c12,stroke:#333,stroke-width:2px,color:#fff
style Client fill:#3498DB,color:#ECF0F1,stroke:#2980B9,stroke-width:2px
style Gateway fill:#3498DB,color:#ECF0F1,stroke:#2980B9,stroke-width:3px
style Auth fill:#8E44AD,color:#ECF0F1,stroke:#7D3C98,stroke-width:2px
style IAM fill:#8E44AD,color:#ECF0F1,stroke:#7D3C98,stroke-width:2px
style User fill:#8E44AD,color:#ECF0F1,stroke:#7D3C98,stroke-width:2px
style DB fill:#34495E,color:#ECF0F1,stroke:#2C3E50,stroke-width:2px
style Cache fill:#34495E,color:#ECF0F1,stroke:#2C3E50,stroke-width:2px
```
**Giải thích**: Sơ đồ kiến trúc tổng quan: `Web Client` đi qua `Traefik Gateway`, sau đó được điều hướng đến các microservices (`Auth`, `IAM`, `User`). Các service này đều kết nối đến Database chung và Redis Cache.
@@ -291,9 +285,15 @@ graph LR
Service --> Cache[Cache Service]
Cache --> Redis[(Redis)]
style Validation fill:#27ae60,stroke:#333,stroke-width:2px,color:#fff
style Service fill:#2980b9,stroke:#333,stroke-width:2px,color:#fff
style Cache fill:#f39c12,stroke:#333,stroke-width:2px,color:#fff
style Input fill:#3498DB,color:#ECF0F1,stroke:#2980B9,stroke-width:2px
style Validation fill:#27AE60,color:#ECF0F1,stroke:#229954,stroke-width:2px
style Controller fill:#8E44AD,color:#ECF0F1,stroke:#7D3C98,stroke-width:2px
style Service fill:#8E44AD,color:#ECF0F1,stroke:#7D3C98,stroke-width:2px
style Repository fill:#8E44AD,color:#ECF0F1,stroke:#7D3C98,stroke-width:2px
style Prisma fill:#8E44AD,color:#ECF0F1,stroke:#7D3C98,stroke-width:2px
style DB fill:#34495E,color:#ECF0F1,stroke:#2C3E50,stroke-width:2px
style Cache fill:#8E44AD,color:#ECF0F1,stroke:#7D3C98,stroke-width:2px
style Redis fill:#34495E,color:#ECF0F1,stroke:#2C3E50,stroke-width:2px
```
**Giải thích**: Sơ đồ luồng dữ liệu chi tiết: Input đi qua lớp Validation -> Controller -> Service -> Repository -> ORM -> DB. Đồng thời Service cũng tương tác với Cache.
@@ -301,17 +301,11 @@ graph LR
---
## 5. ER Diagrams / Sơ đồ ER
## 5. Sơ đồ ER (ER Diagrams)
### When to Use / Khi nào sử dụng
### Khi nào sử dụng
**EN**: Use ER diagrams for:
- Database schema documentation
- Entity relationships
- Data modeling
- Prisma schema visualization
**VI**: Sử dụng ER diagrams cho:
Sử dụng ER diagrams cho:
- Tài liệu schema database
- Mối quan hệ giữa các entity
- Mô hình dữ liệu
@@ -320,6 +314,7 @@ graph LR
### Database Schema
```mermaid
%%{init: {'theme':'dark'}}%%
erDiagram
User ||--o{ Session : has
User ||--o{ RefreshToken : has
@@ -367,17 +362,11 @@ erDiagram
---
## 6. Gantt Charts / Biểu đồ Gantt
## 6. Biểu đồ Gantt (Gantt Charts)
### When to Use / Khi nào sử dụng
### Khi nào sử dụng
**EN**: Use Gantt charts for:
- Project timelines
- Implementation phases
- Migration schedules
- Deployment plans
**VI**: Sử dụng Gantt charts cho:
Sử dụng Gantt charts cho:
- Timeline dự án
- Các giai đoạn triển khai
- Lịch trình migration
@@ -406,17 +395,11 @@ gantt
---
## 7. C4 Diagrams / Sơ đồ C4
## 7. Sơ đồ C4 (C4 Diagrams)
### When to Use / Khi nào sử dụng
### Khi nào sử dụng
**EN**: Use C4 diagrams for:
- System context (highest level)
- Container diagrams (services, databases)
- Component diagrams (modules within services)
- Code diagrams (classes, functions)
**VI**: Sử dụng C4 diagrams cho:
Sử dụng C4 diagrams cho:
- Bối cảnh hệ thống (cấp cao nhất)
- Sơ đồ container (services, databases)
- Sơ đồ component (modules trong services)
@@ -425,6 +408,7 @@ gantt
### System Context
```mermaid
%%{init: {'theme':'dark'}}%%
C4Context
title System Context Diagram for IAM System
@@ -447,62 +431,130 @@ C4Context
---
## Styling Tips / Mẹo Styling
## Bảng màu Tối (Dark Color Palette)
### Color Palette / Bảng màu
### Tham chiếu Bảng màu Đầy đủ
Sử dụng bảng màu tối để tạo sơ đồ có độ tương phản cao và dễ đọc trong môi trường ánh sáng yếu:
```mermaid
graph LR
A["Primary<br/>#2980B9"] --> B["Data/Cache<br/>#F39C12"]
B --> C["Success<br/>#27AE60"]
C --> D["Warning<br/>#E67E22"]
D --> E["Error<br/>#C0392B"]
E --> F["Processing<br/>#8E44AD"]
F --> G["Info<br/>#3498DB"]
G --> H["Neutral<br/>#7F8C8D"]
A["🔵 Primary<br/>#2C3E50"] --> B["💾 Data/Cache<br/>#34495E"]
B --> C["Success<br/>#27AE60"]
C --> D["⚠️ Warning<br/>#E67E22"]
D --> E["Error<br/>#C0392B"]
E --> F["⚙️ Processing<br/>#8E44AD"]
F --> G[" Info<br/>#3498DB"]
G --> H["Neutral<br/>#7F8C8D"]
style A fill:#2980B9,color:#fff
style B fill:#F39C12,color:#fff
style C fill:#27AE60,color:#fff
style D fill:#E67E22,color:#fff
style E fill:#C0392B,color:#fff
style F fill:#8E44AD,color:#fff
style G fill:#3498DB,color:#fff
style H fill:#7F8C8D,color:#fff
style A fill:#2C3E50,color:#ECF0F1,stroke:#34495E,stroke-width:2px
style B fill:#34495E,color:#ECF0F1,stroke:#2C3E50,stroke-width:2px
style C fill:#27AE60,color:#ECF0F1,stroke:#229954,stroke-width:2px
style D fill:#E67E22,color:#ECF0F1,stroke:#D35400,stroke-width:2px
style E fill:#C0392B,color:#ECF0F1,stroke:#A93226,stroke-width:2px
style F fill:#8E44AD,color:#ECF0F1,stroke:#7D3C98,stroke-width:2px
style G fill:#3498DB,color:#ECF0F1,stroke:#2980B9,stroke-width:2px
style H fill:#7F8C8D,color:#ECF0F1,stroke:#5D6D7E,stroke-width:2px
```
### Style Syntax
### Bảng Màu Chi tiết
| Màu | Mã Hex | Sử dụng cho | Màu Viền | Màu Chữ |
|-----|--------|-------------|----------|---------|
| 🔵 **Primary** | `#2C3E50` | Node chính, bắt đầu, khối chính | `#34495E` | `#ECF0F1` |
| 💾 **Data/Cache** | `#34495E` | Database, Cache, Storage | `#2C3E50` | `#ECF0F1` |
| ✅ **Success** | `#27AE60` | Kết thúc thành công, xác nhận | `#229954` | `#ECF0F1` |
| ⚠️ **Warning** | `#E67E22` | Cảnh báo, điều kiện quan trọng | `#D35400` | `#ECF0F1` |
| ❌ **Error** | `#C0392B` | Lỗi, thất bại, hủy bỏ | `#A93226` | `#ECF0F1` |
| ⚙️ **Processing** | `#8E44AD` | Xử lý, quá trình chạy | `#7D3C98` | `#ECF0F1` |
| **Info** | `#3498DB` | Thông tin, ghi chú | `#2980B9` | `#ECF0F1` |
| ⚪ **Neutral** | `#7F8C8D` | Trung lập, không ưu tiên | `#5D6D7E` | `#ECF0F1` |
### Checklist Áp dụng Màu
✅ **Nguyên tắc Cơ bản:**
- [ ] Sử dụng màu tối cho nền (dark background)
- [ ] Màu chữ sáng (`#ECF0F1` hoặc `#fff`) để tạo tương phản
- [ ] Viền tối hơn nền một chút để tạo chiều sâu
- [ ] Độ dày viền: `2px` hoặc `3px`
✅ **Pattern theo Loại Node:**
**Start/End Nodes (Bắt đầu/Kết thúc):**
```markdown
style NodeId fill:#colorcode,stroke:#bordercolor,stroke-width:2px
style Start fill:#2C3E50,color:#ECF0F1,stroke:#34495E,stroke-width:3px
style End fill:#27AE60,color:#ECF0F1,stroke:#229954,stroke-width:3px
```
**Examples**:
**Decision Nodes (Quyết định):**
```markdown
style Start fill:#e1f5ff
style Error fill:#f8d7da
style Process fill:#d4edda,stroke:#28a745,stroke-width:2px
style Decision fill:#E67E22,color:#ECF0F1,stroke:#D35400,stroke-width:2px
```
**Error Nodes (Lỗi):**
```markdown
style Error fill:#C0392B,color:#ECF0F1,stroke:#A93226,stroke-width:2px
```
**Processing Nodes (Xử lý):**
```markdown
style Process fill:#8E44AD,color:#ECF0F1,stroke:#7D3C98,stroke-width:2px
```
**Data/Storage Nodes (Dữ liệu/Lưu trữ):**
```markdown
style DB fill:#34495E,color:#ECF0F1,stroke:#2C3E50,stroke-width:2px
style Cache fill:#34495E,color:#ECF0F1,stroke:#2C3E50,stroke-width:2px
```
**Gateway/API Nodes (Gateway/API):**
```markdown
style Gateway fill:#3498DB,color:#ECF0F1,stroke:#2980B9,stroke-width:3px
```
### Ví dụ Áp dụng Đầy đủ
```mermaid
flowchart TD
Start([Bắt đầu]) --> Auth{Xác thực?}
Auth -->|Không| Error[Lỗi 401]
Auth -->|Có| Process[Xử lý Request]
Process --> DB[(Database)]
DB --> Cache[(Redis Cache)]
Cache --> Success[Thành công]
Error --> End([Kết thúc])
Success --> End
style Start fill:#2C3E50,color:#ECF0F1,stroke:#34495E,stroke-width:3px
style Auth fill:#E67E22,color:#ECF0F1,stroke:#D35400,stroke-width:2px
style Error fill:#C0392B,color:#ECF0F1,stroke:#A93226,stroke-width:2px
style Process fill:#8E44AD,color:#ECF0F1,stroke:#7D3C98,stroke-width:2px
style DB fill:#34495E,color:#ECF0F1,stroke:#2C3E50,stroke-width:2px
style Cache fill:#34495E,color:#ECF0F1,stroke:#2C3E50,stroke-width:2px
style Success fill:#27AE60,color:#ECF0F1,stroke:#229954,stroke-width:2px
style End fill:#27AE60,color:#ECF0F1,stroke:#229954,stroke-width:3px
```
### Cú pháp Style
```markdown
style NodeId fill:#colorcode,color:#textcolor,stroke:#bordercolor,stroke-width:2px
```
**Template Mẫu:**
```markdown
style NodeName fill:#2C3E50,color:#ECF0F1,stroke:#34495E,stroke-width:2px
```
---
## Best Practices / Thực hành Tốt nhất
### EN: Guidelines
1. **Keep it Simple**: Don't overcomplicate diagrams
2. **Use Consistent Styling**: Apply color scheme consistently
3. **Add Legends**: Explain symbols and colors when needed
4. **Limit Complexity**: Break into multiple diagrams if too complex
5. **Test Rendering**: Always test diagrams render correctly
### VI: Hướng dẫn
## Thực hành Tốt nhất
1. **Giữ đơn giản**: Đừng làm phức tạp sơ đồ quá mức
2. **Sử dụng Styling nhất quán**: Áp dụng bảng màu nhất quán
2. **Sử dụng Styling nhất quán**: Áp dụng bảng màu tối nhất quán
3. **Thêm Chú giải**: Giải thích ký hiệu và màu sắc khi cần
4. **Giới hạn Độ phức tạp**: Chia thành nhiều sơ đồ nếu quá phức tạp
5. **Test Rendering**: Luôn test sơ đồ render chính xác
5. **Test Rendering**: Luôn test sơ đồ render chính xác với dark theme
---
@@ -524,6 +576,17 @@ graph TD
G --> I
H --> J
I --> J
style A fill:#E67E22,color:#ECF0F1,stroke:#D35400,stroke-width:2px
style B fill:#8E44AD,color:#ECF0F1,stroke:#7D3C98,stroke-width:2px
style C fill:#8E44AD,color:#ECF0F1,stroke:#7D3C98,stroke-width:2px
style D fill:#8E44AD,color:#ECF0F1,stroke:#7D3C98,stroke-width:2px
style E fill:#8E44AD,color:#ECF0F1,stroke:#7D3C98,stroke-width:2px
style F fill:#8E44AD,color:#ECF0F1,stroke:#7D3C98,stroke-width:2px
style G fill:#8E44AD,color:#ECF0F1,stroke:#7D3C98,stroke-width:2px
style H fill:#8E44AD,color:#ECF0F1,stroke:#7D3C98,stroke-width:2px
style I fill:#8E44AD,color:#ECF0F1,stroke:#7D3C98,stroke-width:2px
style J fill:#C0392B,color:#ECF0F1,stroke:#A93226,stroke-width:2px
```
### ✅ Simplified with Subgraphs
@@ -533,21 +596,27 @@ graph TD
A[Start] --> B[Process A]
B --> C[Process B]
subgraph "Detailed Processing"
subgraph DetailedProcessing["Detailed Processing"]
C --> D[Step 1]
D --> E[Step 2]
end
E --> F[End]
style A fill:#2C3E50,color:#ECF0F1,stroke:#34495E,stroke-width:3px
style B fill:#8E44AD,color:#ECF0F1,stroke:#7D3C98,stroke-width:2px
style C fill:#8E44AD,color:#ECF0F1,stroke:#7D3C98,stroke-width:2px
style D fill:#8E44AD,color:#ECF0F1,stroke:#7D3C98,stroke-width:2px
style E fill:#8E44AD,color:#ECF0F1,stroke:#7D3C98,stroke-width:2px
style F fill:#27AE60,color:#ECF0F1,stroke:#229954,stroke-width:3px
style DetailedProcessing fill:#2C3E50,color:#ECF0F1,stroke:#34495E,stroke-width:2px
```
---
## Kiểm tra Sơ đồ
**EN**: Always test your diagrams before committing:
**VI**: Luôn test sơ đồ trước khi commit:
Luôn test sơ đồ trước khi commit:
```bash
# Install mermaid-cli
@@ -572,11 +641,170 @@ mmdc -i your-doc.md
---
## Resources / Tài nguyên
## 💡 Quick Tips
- [Mermaid Official Documentation](https://mermaid.js.org/) - Complete reference
- [Mermaid Live Editor](https://mermaid.live/) - Test diagrams online
- [Mermaid CheatSheet](https://jojozhuang.github.io/tutorial/mermaid-cheat-sheet/) - Quick reference
### ⚠️ Lỗi Mermaid Thường gặp
#### 1. Lỗi Cú pháp
**Vấn đề:** Sơ đồ không render
```markdown
❌ SAI: flowchart TD A -> B
✅ ĐÚNG: flowchart TD
A --> B
```
**Nguyên nhân:**
- Thiếu xuống dòng sau khai báo loại diagram
- Sử dụng `->` thay vì `-->`
- Thiếu khoảng trắng đúng
#### 2. Lỗi Node ID
**Vấn đề:** Node ID trùng lặp
```markdown
❌ SAI:
graph TD
A[Start]
A[Process] <!-- Trùng ID -->
✅ ĐÚNG:
graph TD
A[Start]
B[Process]
```
#### 3. Lỗi Style
**Vấn đề:** Style không áp dụng
```markdown
❌ SAI: style Node fill:#2C3E50 <!-- Thiếu dấu phẩy -->
✅ ĐÚNG: style Node fill:#2C3E50,color:#ECF0F1
```
#### 4. Lỗi Subgraph
**Vấn đề:** Subgraph không hiển thị đúng
```markdown
❌ SAI:
subgraph "My Group"
A --> B
end
✅ ĐÚNG:
subgraph MyGroup["My Group"]
A --> B
end
```
### 🎨 Quick Color Pattern Reference
**Copy-paste Templates:**
```markdown
<!-- Start Node (Dark Theme) -->
style Start fill:#2C3E50,color:#ECF0F1,stroke:#34495E,stroke-width:3px
<!-- Success Node -->
style Success fill:#27AE60,color:#ECF0F1,stroke:#229954,stroke-width:2px
<!-- Error Node -->
style Error fill:#C0392B,color:#ECF0F1,stroke:#A93226,stroke-width:2px
<!-- Decision Node -->
style Decision fill:#E67E22,color:#ECF0F1,stroke:#D35400,stroke-width:2px
<!-- Database/Cache -->
style DB fill:#34495E,color:#ECF0F1,stroke:#2C3E50,stroke-width:2px
<!-- Processing -->
style Process fill:#8E44AD,color:#ECF0F1,stroke:#7D3C98,stroke-width:2px
<!-- Info/Gateway -->
style Info fill:#3498DB,color:#ECF0F1,stroke:#2980B9,stroke-width:2px
```
### 🔍 Visual Indicators Guide
Sử dụng emoji để tăng khả năng đọc:
| Emoji | Ý nghĩa | Sử dụng trong |
|-------|---------|---------------|
| 🚀 | Start/Launch | Node bắt đầu |
| ✅ | Success | Node thành công |
| ❌ | Error/Failed | Node lỗi |
| ⚠️ | Warning | Decision nodes quan trọng |
| 🔐 | Security/Auth | Authentication steps |
| 💾 | Database/Storage | Data nodes |
| ⚙️ | Processing | Processing nodes |
| | Information | Info nodes |
| 🔄 | Sync/Update | Sync operations |
| 📡 | API/Network | External calls |
**Ví dụ sử dụng:**
```mermaid
flowchart TD
Start([🚀 Bắt đầu]) --> Auth{🔐 Xác thực?}
Auth -->|❌| Error[Lỗi]
Auth -->|✅| Process[⚙️ Xử lý]
Process --> DB[(💾 Database)]
DB --> Success[✅ Thành công]
style Start fill:#2C3E50,color:#ECF0F1,stroke:#34495E,stroke-width:3px
style Success fill:#27AE60,color:#ECF0F1,stroke:#229954,stroke-width:2px
style Error fill:#C0392B,color:#ECF0F1,stroke:#A93226,stroke-width:2px
style Auth fill:#E67E22,color:#ECF0F1,stroke:#D35400,stroke-width:2px
style Process fill:#8E44AD,color:#ECF0F1,stroke:#7D3C98,stroke-width:2px
style DB fill:#34495E,color:#ECF0F1,stroke:#2C3E50,stroke-width:2px
```
### 🛠️ Troubleshooting Checklist
Khi sơ đồ không render:
- [ ] **Kiểm tra cú pháp**: Có xuống dòng sau `flowchart TD`?
- [ ] **Kiểm tra arrow**: Sử dụng `-->` không phải `->`
- [ ] **Kiểm tra Node ID**: Không có ID trùng lặp?
- [ ] **Kiểm tra Style**: Có dấu phẩy giữa các thuộc tính?
- [ ] **Kiểm tra Subgraph**: Sử dụng format `subgraph ID["Label"]`?
- [ ] **Kiểm tra Color**: Hex code có dấu `#` phía trước?
- [ ] **Kiểm tra Special Characters**: Tránh ký tự đặc biệt trong label
### 📊 Diagram Selection Matrix
**Chọn loại sơ đồ dựa trên mục đích:**
```mermaid
flowchart TD
Start{Bạn cần<br/>visualize gì?}
Start -->|Quy trình| Flow[Flowchart ⭐⭐]
Start -->|API/Giao tiếp| Seq[Sequence ⭐⭐⭐]
Start -->|Code Structure| Class[Class Diagram ⭐⭐⭐]
Start -->|Kiến trúc| Graph[Graph ⭐⭐]
Start -->|Database| ER[ER Diagram ⭐⭐⭐]
Start -->|Timeline| Gantt[Gantt Chart ⭐⭐]
Start -->|System Context| C4[C4 Diagram ⭐⭐⭐⭐]
style Start fill:#E67E22,color:#ECF0F1,stroke:#D35400,stroke-width:2px
style Flow fill:#3498DB,color:#ECF0F1,stroke:#2980B9,stroke-width:2px
style Seq fill:#3498DB,color:#ECF0F1,stroke:#2980B9,stroke-width:2px
style Class fill:#3498DB,color:#ECF0F1,stroke:#2980B9,stroke-width:2px
style Graph fill:#3498DB,color:#ECF0F1,stroke:#2980B9,stroke-width:2px
style ER fill:#3498DB,color:#ECF0F1,stroke:#2980B9,stroke-width:2px
style Gantt fill:#3498DB,color:#ECF0F1,stroke:#2980B9,stroke-width:2px
style C4 fill:#3498DB,color:#ECF0F1,stroke:#2980B9,stroke-width:2px
```
---
## Tài nguyên
- [Mermaid Official Documentation](https://mermaid.js.org/) - Tài liệu chính thức
- [Mermaid Live Editor](https://mermaid.live/) - Test sơ đồ online
- [Mermaid CheatSheet](https://jojozhuang.github.io/tutorial/mermaid-cheat-sheet/) - Tham chiếu nhanh
---

View File

@@ -11,6 +11,41 @@ Project này sử dụng [Neon PostgreSQL](https://neon.tech) cho tất cả mô
-**Free tier**: Hoàn hảo cho development
-**Connection pooling**: Hỗ trợ PgBouncer tích hợp
## Kiến Trúc Neon
```mermaid
graph TB
subgraph NeonProject["🌐 Neon Project: goodgo-platform"]
Main["<b>Branch: main</b><br/>🔧 Development<br/>Auto-scaling<br/>Point-in-time restore"]
Staging["<b>Branch: staging</b><br/>🧪 Staging<br/>Created from main<br/>Pre-production testing"]
Production["<b>Branch: production</b><br/>🚀 Production<br/>Created from main<br/>Live environment"]
end
subgraph Features["✨ Tính Năng Chính"]
F1["⚡ Serverless<br/>No infrastructure"]
F2["🔄 Auto-scaling<br/>Handle spikes"]
F3["💾 Backups<br/>Point-in-time"]
F4["🔌 Pooling<br/>PgBouncer"]
end
Main -->|Branch từ| Staging
Main -->|Branch từ| Production
Features -.->|Áp dụng cho| Main
Features -.->|Áp dụng cho| Staging
Features -.->|Áp dụng cho| Production
style NeonProject fill:#1a1a2e,stroke:#16213e,stroke-width:2px,color:#fff
style Main fill:#0f3460,stroke:#16213e,stroke-width:2px,color:#fff
style Staging fill:#533483,stroke:#16213e,stroke-width:2px,color:#fff
style Production fill:#c72c41,stroke:#16213e,stroke-width:2px,color:#fff
style Features fill:#1a1a2e,stroke:#16213e,stroke-width:2px,color:#fff
style F1 fill:#0f3460,stroke:#16213e,stroke-width:2px,color:#fff
style F2 fill:#0f3460,stroke:#16213e,stroke-width:2px,color:#fff
style F3 fill:#0f3460,stroke:#16213e,stroke-width:2px,color:#fff
style F4 fill:#0f3460,stroke:#16213e,stroke-width:2px,color:#fff
```
## Bắt Đầu Nhanh
### 1. Tạo Tài Khoản Neon
@@ -114,6 +149,50 @@ Migration thủ công:
./scripts/db/migrate.sh iam-service deploy
```
### Quy Trình Migration
```mermaid
flowchart TD
Start([👨‍💻 Bắt đầu<br/>Schema thay đổi]) --> Dev[📝 Development<br/>Tạo migration mới<br/>migrate.sh dev]
Dev --> Test{✅ Test<br/>Migration<br/>OK?}
Test -->|❌ Không| Fix[🔧 Sửa lỗi<br/>Cập nhật schema]
Fix --> Dev
Test -->|✅ Có| Commit[📦 Commit<br/>Migration files<br/>+ schema.prisma]
Commit --> PR[🔀 Pull Request<br/>Code review]
PR --> CICD[⚙️ CI/CD Pipeline<br/>Kiểm tra migration]
CICD --> Staging[🧪 Staging Branch<br/>Auto-apply migration]
Staging --> StagingTest{✅ Staging<br/>Test OK?}
StagingTest -->|❌ Không| Rollback1[↩️ Rollback staging]
Rollback1 --> Fix
StagingTest -->|✅ Có| Approval[👥 Approval<br/>Production deploy]
Approval --> Prod[🚀 Production Branch<br/>Apply migration]
Prod --> ProdTest{✅ Production<br/>OK?}
ProdTest -->|❌ Không| Rollback2[🚨 Emergency Rollback<br/>Restore point-in-time]
ProdTest -->|✅ Có| Complete([✨ Hoàn thành<br/>Migration thành công])
style Start fill:#1a1a2e,stroke:#16213e,stroke-width:2px,color:#fff
style Dev fill:#0f3460,stroke:#16213e,stroke-width:2px,color:#fff
style Test fill:#16213e,stroke:#0f3460,stroke-width:2px,color:#fff
style Fix fill:#c72c41,stroke:#16213e,stroke-width:2px,color:#fff
style Commit fill:#0f3460,stroke:#16213e,stroke-width:2px,color:#fff
style PR fill:#0f3460,stroke:#16213e,stroke-width:2px,color:#fff
style CICD fill:#533483,stroke:#16213e,stroke-width:2px,color:#fff
style Staging fill:#533483,stroke:#16213e,stroke-width:2px,color:#fff
style StagingTest fill:#16213e,stroke:#533483,stroke-width:2px,color:#fff
style Rollback1 fill:#c72c41,stroke:#16213e,stroke-width:2px,color:#fff
style Approval fill:#16213e,stroke:#0f3460,stroke-width:2px,color:#fff
style Prod fill:#c72c41,stroke:#16213e,stroke-width:2px,color:#fff
style ProdTest fill:#16213e,stroke:#c72c41,stroke-width:2px,color:#fff
style Rollback2 fill:#c72c41,stroke:#16213e,stroke-width:3px,color:#fff
style Complete fill:#0f3460,stroke:#16213e,stroke-width:2px,color:#fff
```
## Backup & Restore
### Backup Tự Động
@@ -149,6 +228,86 @@ Theo dõi databases qua Neon Console:
## Xử Lý Sự Cố
### Sơ Đồ Xử Lý Sự Cố
```mermaid
flowchart TD
Problem([🚨 Vấn Đề Neon<br/>Không kết nối được?]) --> Type{Loại<br/>Vấn Đề?}
Type -->|🔌 Kết nối| ConnIssue[Vấn Đề Kết Nối]
Type -->|📊 Migration| MigIssue[Vấn Đề Migration]
Type -->|⚡ Hiệu suất| PerfIssue[Vấn Đề Hiệu Suất]
ConnIssue --> CheckURL{Connection<br/>String OK?}
CheckURL -->|❌ Không| FixURL[✅ Kiểm tra:<br/>• sslmode=require<br/>• Credentials đúng<br/>• Endpoint active]
CheckURL -->|✅ Có| CheckIP{IP trong<br/>allowlist?}
CheckIP -->|❌ Không| AddIP[✅ Thêm IP vào<br/>Neon Console]
CheckIP -->|✅ Có| CheckBranch{Branch<br/>active?}
CheckBranch -->|❌ Không| ActivateBranch[✅ Kích hoạt branch<br/>hoặc tạo mới]
CheckBranch -->|✅ Có| ContactSupport[📞 Liên hệ<br/>Neon Support]
MigIssue --> CheckEnv{DATABASE_URL<br/>đã set?}
CheckEnv -->|❌ Không| SetEnv[✅ Export<br/>DATABASE_URL]
CheckEnv -->|✅ Có| CheckSchema{Schema<br/>đồng bộ?}
CheckSchema -->|❌ Không| ResetMig[✅ DEV ONLY:<br/>prisma migrate reset]
CheckSchema -->|✅ Có| CheckTimeout{Connection<br/>timeout?}
CheckTimeout -->|✅ Có| AddPooling[✅ Thêm<br/>?pgbouncer=true]
CheckTimeout -->|❌ Không| CheckLimits[✅ Kiểm tra<br/>Neon Console limits]
PerfIssue --> HasPooling{Connection<br/>Pooling ON?}
HasPooling -->|❌ Không| EnablePooling[✅ Thêm<br/>?pgbouncer=true]
HasPooling -->|✅ Có| CheckQueries{Slow<br/>queries?}
CheckQueries -->|✅ Có| AnalyzeQueries[✅ Neon Console<br/>Query Analyzer]
CheckQueries -->|❌ Không| CheckIndexes{Indexes<br/>tối ưu?}
CheckIndexes -->|❌ Không| AddIndexes[✅ Thêm indexes<br/>vào Prisma schema]
CheckIndexes -->|✅ Có| ScalePlan[✅ Nâng cấp<br/>Neon plan]
FixURL --> Solved([✨ Đã giải quyết])
AddIP --> Solved
ActivateBranch --> Solved
ContactSupport --> Solved
SetEnv --> Solved
ResetMig --> Solved
AddPooling --> Solved
CheckLimits --> Solved
EnablePooling --> Solved
AnalyzeQueries --> Solved
AddIndexes --> Solved
ScalePlan --> Solved
style Problem fill:#c72c41,stroke:#16213e,stroke-width:3px,color:#fff
style Type fill:#16213e,stroke:#0f3460,stroke-width:2px,color:#fff
style ConnIssue fill:#533483,stroke:#16213e,stroke-width:2px,color:#fff
style MigIssue fill:#533483,stroke:#16213e,stroke-width:2px,color:#fff
style PerfIssue fill:#533483,stroke:#16213e,stroke-width:2px,color:#fff
style CheckURL fill:#16213e,stroke:#533483,stroke-width:2px,color:#fff
style CheckIP fill:#16213e,stroke:#533483,stroke-width:2px,color:#fff
style CheckBranch fill:#16213e,stroke:#533483,stroke-width:2px,color:#fff
style CheckEnv fill:#16213e,stroke:#533483,stroke-width:2px,color:#fff
style CheckSchema fill:#16213e,stroke:#533483,stroke-width:2px,color:#fff
style CheckTimeout fill:#16213e,stroke:#533483,stroke-width:2px,color:#fff
style HasPooling fill:#16213e,stroke:#533483,stroke-width:2px,color:#fff
style CheckQueries fill:#16213e,stroke:#533483,stroke-width:2px,color:#fff
style CheckIndexes fill:#16213e,stroke:#533483,stroke-width:2px,color:#fff
style FixURL fill:#0f3460,stroke:#16213e,stroke-width:2px,color:#fff
style AddIP fill:#0f3460,stroke:#16213e,stroke-width:2px,color:#fff
style ActivateBranch fill:#0f3460,stroke:#16213e,stroke-width:2px,color:#fff
style ContactSupport fill:#0f3460,stroke:#16213e,stroke-width:2px,color:#fff
style SetEnv fill:#0f3460,stroke:#16213e,stroke-width:2px,color:#fff
style ResetMig fill:#0f3460,stroke:#16213e,stroke-width:2px,color:#fff
style AddPooling fill:#0f3460,stroke:#16213e,stroke-width:2px,color:#fff
style CheckLimits fill:#0f3460,stroke:#16213e,stroke-width:2px,color:#fff
style EnablePooling fill:#0f3460,stroke:#16213e,stroke-width:2px,color:#fff
style AnalyzeQueries fill:#0f3460,stroke:#16213e,stroke-width:2px,color:#fff
style AddIndexes fill:#0f3460,stroke:#16213e,stroke-width:2px,color:#fff
style ScalePlan fill:#0f3460,stroke:#16213e,stroke-width:2px,color:#fff
style Solved fill:#0f3460,stroke:#16213e,stroke-width:2px,color:#fff
```
### Vấn Đề Kết Nối
1. **Kiểm tra định dạng connection string**
@@ -208,6 +367,52 @@ Theo dõi databases qua Neon Console:
4. **Backup thường xuyên**: Sử dụng automatic backups của Neon
5. **Theo dõi usage**: Kiểm tra Neon Console thường xuyên
## 💡 Quick Tips
### Mermaid Diagram Colors
Tất cả Mermaid diagrams sử dụng **bảng màu tối (dark palette)** với chữ trắng:
| Loại Node | Màu | Mục Đích |
|-----------|-----|----------|
| 🔵 **Primary** | `#0f3460` | Actions, Steps, Solutions |
| 🟣 **Purple** | `#533483` | Staging, Categories, Warnings |
| 🔴 **Red** | `#c72c41` | Production, Errors, Critical |
| 🔘 **Dark** | `#1a1a2e` | Backgrounds, Containers |
| ⚫ **Darker** | `#16213e` | Decision Points, Questions |
**Pattern:**
```css
style NodeName fill:#0f3460,stroke:#16213e,stroke-width:2px,color:#fff
```
### Neon Common Issues & Solutions
| Vấn đề | Giải pháp nhanh | Emoji |
|--------|----------------|-------|
| Connection timeout | Thêm `?pgbouncer=true` | ⚡ |
| SSL error | Thêm `?sslmode=require` | 🔒 |
| IP bị chặn | Thêm IP vào Neon Console allowlist | 🚫 |
| Branch inactive | Kích hoạt lại trong Console | 💤 |
| Migration lỗi | Reset dev: `prisma migrate reset` | 🔄 |
| Slow queries | Bật Query Analyzer trong Console | 🐌 |
| Storage đầy | Nâng cấp plan hoặc cleanup data | 💾 |
### Visual Indicators
- 🌐 = Neon Project
- 🔧 = Development
- 🧪 = Staging
- 🚀 = Production
- ⚡ = Performance/Speed
- 🔌 = Connection
- 💾 = Storage/Backup
- 🔄 = Retry/Rollback
- ✅ = Success/OK
- ❌ = Error/Failed
- 🚨 = Critical/Emergency
- 📊 = Metrics/Analytics
## Tài Nguyên
- [Neon Documentation](https://neon.tech/docs)

View File

@@ -4,12 +4,66 @@ Tài liệu này hướng dẫn cách sử dụng stack observability (Grafana,
## Tổng quan Kiến trúc
Hệ thống bao gồm các thành phần sau:
```mermaid
graph TB
subgraph Services["🚀 Microservices"]
IAM["IAM Service"]
User["User Service"]
Order["Order Service"]
end
subgraph Collectors["📊 Data Collectors"]
Prometheus["Prometheus<br/>📈 Metrics Collector"]
Promtail["Promtail<br/>📝 Log Collector"]
end
subgraph Storage["💾 Storage"]
PrometheusDB["Prometheus TSDB<br/>Metrics Storage"]
Loki["Loki<br/>Log Aggregation"]
end
subgraph Visualization["📊 Visualization"]
Grafana["Grafana<br/>Dashboard & Analytics"]
end
IAM -->|"metrics /metrics"| Prometheus
User -->|"metrics /metrics"| Prometheus
Order -->|"metrics /metrics"| Prometheus
IAM -->|"logs (stdout)"| Promtail
User -->|"logs (stdout)"| Promtail
Order -->|"logs (stdout)"| Promtail
Prometheus -->|"store"| PrometheusDB
Promtail -->|"push logs"| Loki
PrometheusDB -->|"query PromQL"| Grafana
Loki -->|"query LogQL"| Grafana
style Services fill:#1a1a2e,stroke:#16213e,stroke-width:2px,color:#ffffff
style Collectors fill:#0f3460,stroke:#16213e,stroke-width:2px,color:#ffffff
style Storage fill:#16213e,stroke:#0f3460,stroke-width:2px,color:#ffffff
style Visualization fill:#533483,stroke:#16213e,stroke-width:2px,color:#ffffff
style IAM fill:#e94560,stroke:#c81e3b,stroke-width:2px,color:#ffffff
style User fill:#e94560,stroke:#c81e3b,stroke-width:2px,color:#ffffff
style Order fill:#e94560,stroke:#c81e3b,stroke-width:2px,color:#ffffff
style Prometheus fill:#f39c12,stroke:#d68910,stroke-width:2px,color:#ffffff
style Promtail fill:#f39c12,stroke:#d68910,stroke-width:2px,color:#ffffff
style PrometheusDB fill:#3498db,stroke:#2874a6,stroke-width:2px,color:#ffffff
style Loki fill:#3498db,stroke:#2874a6,stroke-width:2px,color:#ffffff
style Grafana fill:#9b59b6,stroke:#7d3c98,stroke-width:2px,color:#ffffff
```
- **Prometheus**: Thu thập metrics từ các services.
- **Loki**: Thu thập logs.
- **Promtail**: Quét logs từ các Docker container và gửi về Loki.
- **Grafana**: Bảng điều khiển (dashboard) để trực quan hóa metrics (từ Prometheus) và logs (từ Loki).
### Các thành phần chính
- **Prometheus**: Thu thập metrics từ các services qua endpoint `/metrics`
- **Loki**: Thu thập và tổng hợp logs từ các container
- **Promtail**: Agent quét logs từ Docker containers và đẩy đến Loki
- **Grafana**: Dashboard trực quan hóa metrics (Prometheus) và logs (Loki)
## Bắt đầu
@@ -87,3 +141,54 @@ Trong giao diện **Explore** với **Prometheus** đã chọn:
- **Prometheus**: Các rules và targets được cấu hình tại `infra/observability/prometheus/prometheus.yml`.
- **Promtail**: Rules để quét log được cấu hình tại `infra/observability/promtail/promtail-config.yml`.
- **Grafana**: Cấu hình datasources và dashboards provisioning nằm trong `infra/observability/grafana/`.
## 💡 Quick Tips
### Troubleshooting chung
| Vấn đề | Triệu chứng | Giải pháp |
|--------|-------------|-----------|
| ⚠️ Không thấy logs | Grafana Explore không hiển thị logs | Kiểm tra Promtail đang chạy: `docker ps \| grep promtail` |
| 📊 Metrics bị thiếu | Services không xuất hiện trong Prometheus targets | Kiểm tra `/metrics` endpoint của service |
| 🔴 Container không khởi động | `docker ps` không show container | Xem logs: `docker-compose logs <service-name>` |
| 🌐 Network issue | Services không kết nối được | Tạo network: `docker network create microservices-network` |
### LogQL Quick Reference
```logql
{container="iam-service"} # Logs từ IAM service
{container="iam-service"} |= "error" # Chỉ logs có chứa "error"
{container="iam-service"} | json # Parse JSON logs
{container="iam-service"} | json | level="error" # Filter by log level
```
### PromQL Quick Reference
```promql
up # Status của tất cả targets (1 = up, 0 = down)
rate(http_requests_total[5m]) # Request rate trong 5 phút
container_memory_usage_bytes{container="iam-service"} # Memory usage của IAM service
```
### Best Practices
-**Naming Convention**: Đặt tên metrics theo pattern `<namespace>_<subsystem>_<name>_<unit>`
-**Labels**: Sử dụng labels để phân loại dữ liệu (environment, service, instance)
-**Retention**: Cấu hình retention phù hợp cho Prometheus và Loki
-**Alerting**: Thiết lập alerts cho các metrics quan trọng
- ⚠️ **Cardinality**: Tránh sử dụng quá nhiều unique labels (gây tăng cardinality)
### Color Palette Reference
Diagram sử dụng bảng màu tối để dễ nhìn:
| Loại Component | Fill Color | Stroke Color | Mục đích |
|----------------|------------|--------------|----------|
| 🚀 Services | `#e94560` | `#c81e3b` | Microservices (đỏ) |
| 📊 Collectors | `#f39c12` | `#d68910` | Thu thập dữ liệu (cam) |
| 💾 Storage | `#3498db` | `#2874a6` | Lưu trữ (xanh dương) |
| 📊 Visualization | `#9b59b6` | `#7d3c98` | Trực quan hóa (tím) |
| 📦 Subgraphs | `#1a1a2e` - `#533483` | `#16213e` - `#0f3460` | Nhóm logic |
**Tất cả text sử dụng `color:#ffffff` (trắng) để dễ đọc trên nền tối**

View File

@@ -42,6 +42,92 @@ Khi có sự cố, hãy làm theo danh sách kiểm tra sau:
* Có thể truy cập Gateway không? `curl http://localhost/health`
* Có thể truy cập Dashboard không? http://localhost:8080
### Sơ Đồ Xử Lý Sự Cố
```mermaid
flowchart TD
Start([🔍 Phát Hiện Sự Cố]) --> CheckStatus{Kiểm tra<br/>Trạng thái Service}
CheckStatus -->|Tất cả Running| CheckLogs[📋 Xem Logs]
CheckStatus -->|Một số Down| IdentifyService[🎯 Xác định Service<br/>Bị Lỗi]
IdentifyService --> ServiceType{Loại Service?}
ServiceType -->|Infrastructure| InfraCheck[🔧 Kiểm tra<br/>Infrastructure]
ServiceType -->|Application| AppCheck[⚙️ Kiểm tra<br/>Application]
InfraCheck --> DBCheck{Database?}
InfraCheck --> RedisCheck{Redis?}
InfraCheck --> TraefikCheck{Traefik?}
DBCheck -->|Có| DBSolution[✅ Kiểm tra DATABASE_URL<br/>✅ Verify kết nối Neon<br/>✅ Kiểm tra IP whitelist]
RedisCheck -->|Có| RedisSolution[✅ Restart Redis<br/>✅ Kiểm tra port mapping<br/>✅ Verify connection string]
TraefikCheck -->|Có| TraefikSolution[✅ Kiểm tra labels<br/>✅ Verify PathPrefix<br/>✅ Kiểm tra health status]
AppCheck --> ErrorType{Loại Lỗi?}
ErrorType -->|Config| ConfigFix[✅ Kiểm tra .env variables<br/>✅ Chạy init-project.sh]
ErrorType -->|Prisma| PrismaFix[✅ Kiểm tra migrations<br/>✅ Regenerate client<br/>✅ Reset database]
ErrorType -->|Auth| AuthFix[✅ Kiểm tra token expiry<br/>✅ Verify keys<br/>✅ Sync thời gian Docker]
CheckLogs --> LogAnalysis{Log Hiện<br/>Lỗi?}
LogAnalysis -->|Có| ErrorType
LogAnalysis -->|Không| ConnCheck[🌐 Kiểm tra Kết nối]
ConnCheck --> GatewayTest{Gateway<br/>Truy Cập Được?}
GatewayTest -->|Không| TraefikCheck
GatewayTest -->|Có| ServiceTest{Service<br/>Truy Cập Được?}
ServiceTest -->|Không| AppCheck
ServiceTest -->|Có| Resolved([✨ Đã Giải Quyết])
DBSolution --> Restart[🔄 Restart Services]
RedisSolution --> Restart
TraefikSolution --> Restart
ConfigFix --> Restart
PrismaFix --> Restart
AuthFix --> Restart
Restart --> Verify{Đã Sửa<br/>Xong?}
Verify -->|Có| Resolved
Verify -->|Không| DeepDebug[🛠️ Debug Sâu<br/>Hơn]
DeepDebug --> ContainerShell[Truy cập Container Shell]
DeepDebug --> PrismaStudio[Dùng Prisma Studio]
DeepDebug --> RedisInspect[Kiểm tra Redis]
DeepDebug --> APITest[Test API Trực tiếp]
style Start fill:#1a1a2e,color:#fff
style Resolved fill:#0f3460,color:#fff
style CheckStatus fill:#16213e,color:#fff
style ServiceType fill:#16213e,color:#fff
style ErrorType fill:#16213e,color:#fff
style DBCheck fill:#16213e,color:#fff
style RedisCheck fill:#16213e,color:#fff
style TraefikCheck fill:#16213e,color:#fff
style GatewayTest fill:#16213e,color:#fff
style ServiceTest fill:#16213e,color:#fff
style Verify fill:#16213e,color:#fff
style LogAnalysis fill:#16213e,color:#fff
style InfraCheck fill:#1a1a40,color:#fff
style AppCheck fill:#1a1a40,color:#fff
style DBSolution fill:#0f4c75,color:#fff
style RedisSolution fill:#0f4c75,color:#fff
style TraefikSolution fill:#0f4c75,color:#fff
style ConfigFix fill:#0f4c75,color:#fff
style PrismaFix fill:#0f4c75,color:#fff
style AuthFix fill:#0f4c75,color:#fff
style Restart fill:#3282b8,color:#fff
style DeepDebug fill:#1b262c,color:#fff
style IdentifyService fill:#1a1a40,color:#fff
style CheckLogs fill:#1a1a40,color:#fff
style ConnCheck fill:#1a1a40,color:#fff
style ContainerShell fill:#0f3460,color:#fff
style PrismaStudio fill:#0f3460,color:#fff
style RedisInspect fill:#0f3460,color:#fff
style APITest fill:#0f3460,color:#fff
```
---
## Vấn đề Infrastructure
@@ -216,3 +302,122 @@ docker-compose down -v
Đ: Docker tốn nhiều RAM.
1. Tắt các service không dùng (ví dụ `future-service`).
2. Tăng giới hạn resource trong cài đặt Docker Desktop.
---
## Mẹo Nhanh (Quick Tips)
### 🎯 Lệnh Debug Nhanh
```bash
# Kiểm tra nhanh các service bị lỗi
docker-compose ps | grep -v "Up"
# Xem logs tất cả services (50 dòng cuối)
docker-compose logs -f --tail=50
# Restart service cụ thể không rebuild
docker-compose restart iam-service
# Rebuild và restart service
docker-compose up -d --build iam-service
# Kiểm tra resource usage
docker stats --no-stream
# Dọn dẹp resources không dùng
docker system prune -a --volumes
```
### 🔍 Các Pattern Lỗi Thường Gặp
| Pattern Lỗi | Nguyên nhân Có thể | Cách Sửa Nhanh |
|-------------|-------------------|----------------|
| `ECONNREFUSED` | Service chưa chạy | `docker-compose restart <service>` |
| `P1001` | Database không kết nối được | Kiểm tra `DATABASE_URL` và internet |
| `P2002` | Dữ liệu trùng lặp | Kiểm tra unique constraints |
| `401 Unauthorized` | Token hết hạn/không hợp lệ | Refresh token hoặc đăng nhập lại |
| `404 Not Found` | Route sai/service down | Kiểm tra Traefik dashboard |
| `502 Bad Gateway` | Service bị crash | Xem logs service |
| `Config validation error` | Thiếu biến môi trường | Chạy `init-project.sh` |
### 📋 Mẹo Phân Tích Logs
**Những gì cần tìm trong logs:**
- ✅ `Server listening on port XXXX` = Service khởi động thành công
- ⚠️ `Warning:` = Vấn đề không nghiêm trọng
- ❌ `Error:` = Vấn đề nghiêm trọng cần xử lý
- 🔍 `Trace:` = Chi tiết luồng thực thi
**Các pattern grep hữu ích:**
```bash
# Tìm tất cả lỗi
docker-compose logs | grep -i error
# Tìm lỗi của service cụ thể
docker-compose logs iam-service | grep -i "error\|failed"
# Tìm vấn đề database connection
docker-compose logs | grep -i "prisma\|database\|p1001\|p1003"
# Tìm vấn đề auth
docker-compose logs | grep -i "unauthorized\|401\|jwt\|token"
```
### 💾 Quản Lý Tài Nguyên
**Docker Resources Khuyến nghị:**
- **RAM**: Tối thiểu 4GB, Khuyến nghị 8GB
- **CPU**: Tối thiểu 2 cores, Khuyến nghị 4 cores
- **Disk**: Tối thiểu 10GB dung lượng trống
**Kiểm tra resource usage:**
```bash
# Tổng quan hệ thống
docker system df
# Theo từng container
docker stats --no-stream --format "table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}"
```
**Lệnh dọn dẹp:**
```bash
# Xóa containers đã dừng
docker container prune
# Xóa images không dùng
docker image prune -a
# Xóa volumes không dùng (⚠️ mất dữ liệu!)
docker volume prune
# Tùy chọn hạt nhân (⚠️ xóa mọi thứ!)
docker system prune -a --volumes
```
### 🛡️ Best Practices
1. **Luôn kiểm tra logs trước** khi thay đổi gì
2. **Dùng Traefik Dashboard** (http://localhost:8080) để verify routing
3. **Giữ `.env.local` cập nhật** với credentials đúng
4. **Đừng xóa volumes** trừ khi muốn mất dữ liệu
5. **Restart Docker Desktop** nếu gặp vấn đề network lạ
6. **Dùng `docker-compose down && up`** sau khi thay đổi `.env`
7. **Giữ services đang chạy** mà bạn đang develop
8. **Tắt services** không dùng để tiết kiệm tài nguyên
### 🎨 Visual Indicators
Khi đọc logs, chú ý các pattern sau:
- 🟢 `[INFO]` = Hoạt động bình thường
- 🟡 `[WARN]` = Cần theo dõi
- 🔴 `[ERROR]` = Cần xử lý ngay
- 🔵 `[DEBUG]` = Thông tin chi tiết
- ⚡ `[TRACE]` = Luồng thực thi rất chi tiết
### 🔗 Tài Liệu Liên Quan
- [Hướng dẫn Local Deployment](./local-deployment.md) - Hướng dẫn setup
- [Hướng dẫn Development](./development.md) - Workflow phát triển
- [Hướng dẫn Kubernetes Local](./kubernetes-local.md) - Troubleshooting K8s
- [Hướng dẫn Neon Database](./neon-database.md) - Quản lý database