feat(docs): Revise deployment and development guides with enhanced visuals and clarity

- Updated color schemes in Mermaid diagrams across deployment and development guides for improved visual distinction.
- Enhanced the structure and clarity of the migration guide, including detailed workflows and architecture comparisons.
- Added new sections for troubleshooting and observability, incorporating flowcharts and diagrams for better understanding.
- Improved formatting and consistency in both English and Vietnamese documentation to align with recent updates.
- Introduced quick tips and common issues sections to assist users in navigating the documentation effectively.
This commit is contained in:
Ho Ngoc Hai
2026-01-08 16:41:02 +07:00
parent 92d14877e5
commit 2a09a6e989
13 changed files with 1351 additions and 448 deletions

View File

@@ -40,17 +40,17 @@ graph TD
Deploy --> Ingress
style Code fill:#3498DB,color:#fff
style Test fill:#27AE60,color:#fff
style Build fill:#2980B9,color:#fff
style Registry fill:#8E44AD,color:#fff
style Deploy fill:#E67E22,color:#fff
style Ingress fill:#2980B9,color:#fff
style Service fill:#3498DB,color:#fff
style Pods fill:#27AE60,color:#fff
style Secrets fill:#E67E22,color:#fff
style Neon fill:#8E44AD,color:#fff
style Redis fill:#F39C12,color:#fff
style Code fill:#1e3a5f,color:#e0e7ff
style Test fill:#065f46,color:#d1fae5
style Build fill:#1e40af,color:#dbeafe
style Registry fill:#581c87,color:#f3e8ff
style Deploy fill:#9a3412,color:#fed7aa
style Ingress fill:#312e81,color:#e0e7ff
style Service fill:#1e40af,color:#dbeafe
style Pods fill:#14532d,color:#d1fae5
style Secrets fill:#78350f,color:#fef3c7
style Neon fill:#4c1d95,color:#f3e8ff
style Redis fill:#854d0e,color:#fef3c7
```
---

View File

@@ -1,6 +1,6 @@
# Development Guide
>Comprehensive standards and workflows for contributing to the GoodGo Microservices Platform
Comprehensive standards and workflows for contributing to the GoodGo Microservices Platform.
## Table of Contents
@@ -149,20 +149,20 @@ graph TD
ErrorHandler --> Response[Error Response]
ErrorCheck -->|No| Success[Success Response]
style Start fill:#27AE60,color:#fff,stroke:#27AE60,stroke-width:2px
style Done fill:#27AE60,color:#fff,stroke:#27AE60,stroke-width:2px
style DTO fill:#3498DB,color:#fff
style Repo fill:#2980B9,color:#fff
style Service fill:#8E44AD,color:#fff
style Controller fill:#E67E22, color:#fff
style Route fill:#2980B9,color:#fff
style Middleware fill:#3498DB,color:#fff
style Test fill:#27AE60,color:#fff
style ErrorCheck fill:#E67E22,color:#fff
style ThrowError fill:#C0392B,color:#fff
style ErrorHandler fill:#C0392B,color:#fff
style Response fill:#7F8C8D,color:#fff
style Success fill:#27AE60,color:#fff
style Start fill:#1e3a2e,color:#4ade80,stroke:#4ade80,stroke-width:3px
style Done fill:#1e3a2e,color:#4ade80,stroke:#4ade80,stroke-width:3px
style DTO fill:#1e293b,color:#60a5fa
style Repo fill:#1e293b,color:#3b82f6
style Service fill:#2e1a47,color:#a78bfa
style Controller fill:#2d1b0e,color:#fb923c
style Route fill:#1e293b,color:#3b82f6
style Middleware fill:#1e293b,color:#60a5fa
style Test fill:#1e3a2e,color:#4ade80
style ErrorCheck fill:#2d1b0e,color:#fb923c
style ThrowError fill:#3f1a1a,color:#f87171
style ErrorHandler fill:#3f1a1a,color:#f87171
style Response fill:#27272a,color:#a1a1aa
style Success fill:#1e3a2e,color:#4ade80
```
### Creating a New API Endpoint
@@ -237,24 +237,24 @@ graph TB
AddTests --> RunUnit
Coverage -->|Yes| ReadyMerge[Ready to Merge]
style Unit fill:#27AE60,color:#fff
style Integration fill:#3498DB,color:#fff
style E2E fill:#8E44AD,color:#fff
style Code fill:#2980B9,color:#fff
style CheckLint fill:#E67E22,color:#fff
style UnitPass fill:#27AE60,color:#fff
style IntPass fill:#3498DB,color:#fff
style E2EPass fill:#8E44AD,color:#fff
style Coverage fill:#F39C12,color:#fff
style RunUnit fill:#27AE60,color:#fff
style RunIntegration fill:#3498DB,color:#fff
style RunE2E fill:#8E44AD,color:#fff
style ReadyMerge fill:#27AE60,color:#fff,stroke:#27AE60,stroke-width:2px
style FixLint fill:#C0392B,color:#fff
style FixUnit fill:#C0392B,color:#fff
style FixIntegration fill:#C0392B,color:#fff
style FixE2E fill:#C0392B,color:#fff
style AddTests fill:#F39C12,color:#fff
style Unit fill:#1e3a2e,color:#4ade80
style Integration fill:#1e293b,color:#60a5fa
style E2E fill:#2e1a47,color:#a78bfa
style Code fill:#1e293b,color:#3b82f6
style CheckLint fill:#2d1b0e,color:#fb923c
style UnitPass fill:#1e3a2e,color:#4ade80
style IntPass fill:#1e293b,color:#60a5fa
style E2EPass fill:#2e1a47,color:#a78bfa
style Coverage fill:#2d1b0e,color:#fbbf24
style RunUnit fill:#1e3a2e,color:#4ade80
style RunIntegration fill:#1e293b,color:#60a5fa
style RunE2E fill:#2e1a47,color:#a78bfa
style ReadyMerge fill:#1e3a2e,color:#4ade80,stroke:#4ade80,stroke-width:3px
style FixLint fill:#3f1a1a,color:#f87171
style FixUnit fill:#3f1a1a,color:#f87171
style FixIntegration fill:#3f1a1a,color:#f87171
style FixE2E fill:#3f1a1a,color:#f87171
style AddTests fill:#2d1b0e,color:#fbbf24
```
### Unit Tests (`*.test.ts`)

View File

@@ -49,35 +49,35 @@ graph TD
IAM --> Redis[(Redis Cache)]
IAM --> Kafka[Kafka Events]
style Client fill:#7F8C8D,color:#fff
style Traefik fill:#2980B9,color:#fff
style IAM fill:#27AE60,color:#fff
style Template fill:#E67E22,color:#fff
style DB fill:#8E44AD,color:#fff
style Redis fill:#F39C12,color:#fff
style Kafka fill:#3498DB,color:#fff
style Client fill:#34495E,stroke:#2C3E50,color:#ECF0F1
style Traefik fill:#1A5490,stroke:#154360,color:#ECF0F1
style IAM fill:#1E8449,stroke:#186A3B,color:#ECF0F1
style Template fill:#BA6610,stroke:#935116,color:#ECF0F1
style DB fill:#6C3483,stroke:#512E5F,color:#ECF0F1
style Redis fill:#CA6F1E,stroke:#A04000,color:#ECF0F1
style Kafka fill:#21618C,stroke:#1B4F72,color:#ECF0F1
```
### Color Palette
```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/>#1A5490"] --> B["🟠 Data/Cache<br/>#CA6F1E"]
B --> C["🟢 Success<br/>#1E8449"]
C --> D["🟡 Warning<br/>#BA6610"]
D --> E["🔴 Error<br/>#922B21"]
E --> F["🟣 Processing<br/>#6C3483"]
F --> G["🔷 Info<br/>#21618C"]
G --> H["Neutral<br/>#34495E"]
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:#1A5490,stroke:#154360,color:#ECF0F1
style B fill:#CA6F1E,stroke:#A04000,color:#ECF0F1
style C fill:#1E8449,stroke:#186A3B,color:#ECF0F1
style D fill:#BA6610,stroke:#935116,color:#ECF0F1
style E fill:#922B21,stroke:#78281F,color:#ECF0F1
style F fill:#6C3483,stroke:#512E5F,color:#ECF0F1
style G fill:#21618C,stroke:#1B4F72,color:#ECF0F1
style H fill:#34495E,stroke:#2C3E50,color:#ECF0F1
```
## Project Structure

View File

@@ -1,14 +1,45 @@
# Migration Guide: Auth Service → IAM Service
Tài liệu này hướng dẫn cách migrate từ `auth-service` sang `iam-service`.
This document guides you through migrating from `auth-service` to `iam-service`.
## Tổng Quan
## Overview
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, Governance & Compliance. Tất cả các API endpoints của Auth Service vẫn được giữ nguyên để đảm bảo backward compatibility.
IAM Service is an extended version of Auth Service with additional features for Identity Management, Access Management, and Governance & Compliance. All Auth Service API endpoints remain unchanged to ensure backward compatibility.
## Migration Workflow
```mermaid
graph LR
Start([Start Migration]) --> Backup[📦 Backup]
Backup --> DBMigrate[🗄️ Database Migration]
DBMigrate --> UpdateDeps[📚 Update Dependencies]
UpdateDeps --> Deploy[🚀 Deploy]
Deploy --> Verify[✅ Verify]
Verify --> Decision{All Tests Pass?}
Decision -->|Yes| Rollout[📊 Gradual Rollout]
Decision -->|No| Rollback[⏮️ Rollback]
Rollback --> Debug[🔍 Debug Issues]
Debug --> DBMigrate
Rollout --> Monitor[📈 Monitor]
Monitor --> Complete([✨ Complete])
style Start fill:#2d4263,stroke:#c69b7b,stroke-width:2px,color:#f5f5f5
style Backup fill:#191e29,stroke:#76b6c4,stroke-width:2px,color:#f5f5f5
style DBMigrate fill:#191e29,stroke:#76b6c4,stroke-width:2px,color:#f5f5f5
style UpdateDeps fill:#191e29,stroke:#76b6c4,stroke-width:2px,color:#f5f5f5
style Deploy fill:#2d4263,stroke:#87a2a7,stroke-width:2px,color:#f5f5f5
style Verify fill:#2d4263,stroke:#87a2a7,stroke-width:2px,color:#f5f5f5
style Decision fill:#4a5568,stroke:#c69b7b,stroke-width:2px,color:#f5f5f5
style Rollout fill:#1a472a,stroke:#48bb78,stroke-width:2px,color:#f5f5f5
style Rollback fill:#742a2a,stroke:#f56565,stroke-width:2px,color:#f5f5f5
style Debug fill:#742a2a,stroke:#f56565,stroke-width:2px,color:#f5f5f5
style Monitor fill:#2d4263,stroke:#87a2a7,stroke-width:2px,color:#f5f5f5
style Complete fill:#1a472a,stroke:#48bb78,stroke-width:2px,color:#f5f5f5
```
## Backward Compatibility
**Tất cả các endpoints hiện tại vẫn hoạt động bình thường:**
**All existing endpoints continue to work normally:**
- `/api/v1/auth/*` - Authentication endpoints
- `/api/v1/rbac/*` - RBAC endpoints
@@ -16,42 +47,128 @@ IAM Service là phiên bản mở rộng của Auth Service với các tính nă
- `/api/v1/sessions/*` - Session management endpoints
- `/api/v1/oidc/*` - OIDC endpoints
Không có breaking changes. Các clients hiện tại có thể tiếp tục sử dụng các endpoints này mà không cần thay đổi.
No breaking changes. Existing clients can continue using these endpoints without any modifications.
## Các Thay Đổi
## Architecture Comparison
```mermaid
graph TB
subgraph "Auth Service (Old)"
A1[Authentication]
A2[RBAC]
A3[MFA]
A4[Sessions]
A5[OIDC]
end
subgraph "IAM Service (New)"
B1[Authentication]
B2[RBAC]
B3[MFA]
B4[Sessions]
B5[OIDC]
B6[Identity Management]
B7[Access Management]
B8[Governance]
end
A1 -.->|Unchanged| B1
A2 -.->|Unchanged| B2
A3 -.->|Unchanged| B3
A4 -.->|Unchanged| B4
A5 -.->|Unchanged| B5
style A1 fill:#2d4263,stroke:#76b6c4,stroke-width:2px,color:#f5f5f5
style A2 fill:#2d4263,stroke:#76b6c4,stroke-width:2px,color:#f5f5f5
style A3 fill:#2d4263,stroke:#76b6c4,stroke-width:2px,color:#f5f5f5
style A4 fill:#2d4263,stroke:#76b6c4,stroke-width:2px,color:#f5f5f5
style A5 fill:#2d4263,stroke:#76b6c4,stroke-width:2px,color:#f5f5f5
style B1 fill:#2d4263,stroke:#76b6c4,stroke-width:2px,color:#f5f5f5
style B2 fill:#2d4263,stroke:#76b6c4,stroke-width:2px,color:#f5f5f5
style B3 fill:#2d4263,stroke:#76b6c4,stroke-width:2px,color:#f5f5f5
style B4 fill:#2d4263,stroke:#76b6c4,stroke-width:2px,color:#f5f5f5
style B5 fill:#2d4263,stroke:#76b6c4,stroke-width:2px,color:#f5f5f5
style B6 fill:#1a472a,stroke:#48bb78,stroke-width:2px,color:#f5f5f5
style B7 fill:#1a472a,stroke:#48bb78,stroke-width:2px,color:#f5f5f5
style B8 fill:#1a472a,stroke:#48bb78,stroke-width:2px,color:#f5f5f5
```
## Changes
### 1. Service Name
- ****: `auth-service`
- **Mới**: `iam-service`
- **Old**: `auth-service`
- **New**: `iam-service`
### 2. Package Name
- ****: `@goodgo/auth-service`
- **Mới**: `@goodgo/iam-service`
- **Old**: `@goodgo/auth-service`
- **New**: `@goodgo/iam-service`
### 3. Database Schema
Database schema được mở rộng với các models mới nhưng **không xóa hoặc thay đổi** các models hiện có:
Database schema is extended with new models but **does not delete or modify** existing models:
**Models mới được thêm:**
- `Organization` - Quản lý tổ chức
- `Group` - Quản lý nhóm
- `GroupMember` - Thành viên nhóm
- `GroupPermission` - Quyền nhóm
- `UserProfile` - Profile mở rộng
- `IdentityVerification` - Xác thực danh tính
- `AccessRequest` - Yêu cầu truy cập
- `AccessReview` - Đánh giá truy cập
- `ComplianceReport` - Báo cáo tuân thủ
- `PolicyTemplate` - Template policy
- `RiskScore` - Điểm rủi ro
**New models added:**
- `Organization` - Organization management
- `Group` - Group management
- `GroupMember` - Group members
- `GroupPermission` - Group permissions
- `UserProfile` - Extended profile
- `IdentityVerification` - Identity verification
- `AccessRequest` - Access requests
- `AccessReview` - Access reviews
- `ComplianceReport` - Compliance reports
- `PolicyTemplate` - Policy templates
- `RiskScore` - Risk scores
**User model được mở rộng:**
- Thêm field `organizationId` (optional)
- Thêm các relations mới (optional)
**User model extended:**
- Added `organizationId` field (optional)
- Added new relations (optional)
### 4. API Endpoints Mới
```mermaid
erDiagram
User ||--o{ UserProfile : has
User ||--o{ AccessRequest : creates
User }o--|| Organization : "belongs to"
User ||--o{ GroupMember : "member of"
Organization ||--o{ Group : contains
Group ||--o{ GroupMember : has
Group ||--o{ GroupPermission : has
AccessRequest ||--|| AccessReview : "reviewed by"
Organization ||--o{ ComplianceReport : generates
User {
string id PK
string email
string organizationId FK
}
Organization {
string id PK
string name
}
Group {
string id PK
string organizationId FK
}
UserProfile {
string userId FK
json metadata
}
AccessRequest {
string id PK
string userId FK
}
```
### 4. New API Endpoints
#### Identity Management
- `/api/v1/identity/users/*` - User lifecycle management
@@ -73,14 +190,14 @@ Database schema được mở rộng với các models mới nhưng **không xó
### 5. Environment Variables
Một số biến môi trường mới có thể được thêm trong tương lai cho các tính năng IAM nâng cao (email service, SMS service, file storage), nhưng không ảnh hưởng đến các biến hiện tại.
Some new environment variables may be added in the future for advanced IAM features (email service, SMS service, file storage), but they will not affect existing variables.
### 6. Deployment Configuration
**Docker Compose:**
- Service name: `auth-service``iam-service`
- Container name: `auth-service-local``iam-service-local`
- Traefik labels: Thêm routes mới cho `/api/v1/identity/*`, `/api/v1/access/*`, `/api/v1/governance/*`
- Traefik labels: Add new routes for `/api/v1/identity/*`, `/api/v1/access/*`, `/api/v1/governance/*`
**Kubernetes:**
- Deployment name: `auth-service``iam-service`
@@ -90,7 +207,7 @@ Một số biến môi trường mới có thể được thêm trong tương la
## Migration Steps
### Bước 1: Backup
### Step 1: Backup
```bash
# Backup database
@@ -100,48 +217,48 @@ pg_dump $DATABASE_URL > auth-service-backup.sql
cp -r services/auth-service services/auth-service.backup
```
### Bước 2: Database Migration
### Step 2: Database Migration
```bash
cd services/iam-service
# Generate Prisma client với schema mới
# Generate Prisma client with new schema
pnpm prisma generate
# Tạo migration
# Create migration
pnpm prisma migrate dev --name add_iam_models
# Verify migration
pnpm prisma studio # Check database structure
```
### Bước 3: Update Dependencies
### Step 3: Update Dependencies
```bash
# Install dependencies (nếu có package mới)
# Install dependencies (if new packages exist)
pnpm install
# Verify types compile
pnpm typecheck
```
### Bước 4: Update Deployment
### Step 4: Update Deployment
**Local Development:**
```bash
cd deployments/local
# Update docker-compose.yml (đã được cập nhật)
# Update docker-compose.yml (already updated)
docker-compose up -d iam-service
```
**Staging/Production:**
- Update Kubernetes manifests
- Update ingress routes
- Update ConfigMaps Secrets
- Update ConfigMaps and Secrets
### Bước 5: Verify Backward Compatibility
### Step 5: Verify Backward Compatibility
Test tất cả các endpoints cũ vẫn hoạt động:
Test that all old endpoints still work:
```bash
# Test auth endpoints
@@ -154,24 +271,63 @@ curl http://localhost/api/v1/rbac/permissions
curl http://localhost/api/v1/mfa/devices
```
### Bước 6: Gradual Rollout
### Step 6: Gradual Rollout
1. **Dual Deployment** (Optional):
- Deploy cả `auth-service` `iam-service` cùng lúc
- Route traffic dần dần sang `iam-service`
- Monitor errors performance
- Deploy both `auth-service` and `iam-service` simultaneously
- Gradually route traffic to `iam-service`
- Monitor errors and performance
2. **Update Clients**:
- Update clients để sử dụng các endpoints mới nếu cần
- Clients không cần update nếu chỉ dùng endpoints
- Update clients to use new endpoints if needed
- Clients don't need updates if only using old endpoints
3. **Deprecate Old Service**:
- Sau khi verify mọi thứ hoạt động tốt, có thể deprecate `auth-service`
- Đảm bảo tất cả clients đã migrate sang `iam-service`
- After verifying everything works well, deprecate `auth-service`
- Ensure all clients have migrated to `iam-service`
## Deployment Strategy
```mermaid
graph TB
Current[Current: auth-service] --> Phase1[Phase 1: Dual Deploy]
Phase1 --> Split{Traffic Split}
Split -->|10%| IAM1[iam-service]
Split -->|90%| Auth1[auth-service]
Split --> Phase2[Phase 2: Increase]
Phase2 --> Split2{Traffic Split}
Split2 -->|50%| IAM2[iam-service]
Split2 -->|50%| Auth2[auth-service]
Split2 --> Phase3[Phase 3: Majority]
Phase3 --> Split3{Traffic Split}
Split3 -->|90%| IAM3[iam-service]
Split3 -->|10%| Auth3[auth-service]
Split3 --> Phase4[Phase 4: Complete]
Phase4 --> Final[iam-service only]
style Current fill:#2d4263,stroke:#76b6c4,stroke-width:2px,color:#f5f5f5
style Phase1 fill:#2d4263,stroke:#87a2a7,stroke-width:2px,color:#f5f5f5
style Phase2 fill:#2d4263,stroke:#87a2a7,stroke-width:2px,color:#f5f5f5
style Phase3 fill:#2d4263,stroke:#87a2a7,stroke-width:2px,color:#f5f5f5
style Phase4 fill:#2d4263,stroke:#87a2a7,stroke-width:2px,color:#f5f5f5
style Final fill:#1a472a,stroke:#48bb78,stroke-width:2px,color:#f5f5f5
style Split fill:#4a5568,stroke:#c69b7b,stroke-width:2px,color:#f5f5f5
style Split2 fill:#4a5568,stroke:#c69b7b,stroke-width:2px,color:#f5f5f5
style Split3 fill:#4a5568,stroke:#c69b7b,stroke-width:2px,color:#f5f5f5
style IAM1 fill:#1a472a,stroke:#48bb78,stroke-width:1px,color:#f5f5f5
style IAM2 fill:#1a472a,stroke:#48bb78,stroke-width:1px,color:#f5f5f5
style IAM3 fill:#1a472a,stroke:#48bb78,stroke-width:1px,color:#f5f5f5
style Auth1 fill:#742a2a,stroke:#f56565,stroke-width:1px,color:#f5f5f5
style Auth2 fill:#742a2a,stroke:#f56565,stroke-width:1px,color:#f5f5f5
style Auth3 fill:#742a2a,stroke:#f56565,stroke-width:1px,color:#f5f5f5
```
## Rollback Plan
Nếu cần rollback:
If rollback is needed:
1. **Database Rollback**:
```bash
@@ -179,31 +335,53 @@ Nếu cần rollback:
cd services/iam-service
pnpm prisma migrate resolve --rolled-back <migration_name>
# Hoặc restore từ backup
# Or restore from backup
psql $DATABASE_URL < auth-service-backup.sql
```
2. **Service Rollback**:
```bash
# Switch back to auth-service in docker-compose
# Hoặc revert Kubernetes deployment
# Or revert Kubernetes deployment
kubectl rollout undo deployment/auth-service
```
## Breaking Changes
**Không có breaking changes** trong migration này. Tất cả các API endpoints database models hiện có đều được giữ nguyên.
**No breaking changes** in this migration. All existing API endpoints and database models are preserved.
## Notes
- Migration này là **additive** - chỉ thêm các tính năng mới, không xóa hoặc thay đổi tính năng cũ
- Database migrations **non-destructive** - không xóa hoặc modify dữ liệu hiện có
- Clients có thể tiếp tục sử dụng các endpoints cũ mà không cần thay đổi
- This migration is **additive** - only adds new features, does not remove or change existing ones
- Database migrations are **non-destructive** - do not delete or modify existing data
- Clients can continue using old endpoints without any changes
## Support
Nếu gặp vấn đề trong quá trình migration, vui lòng:
If you encounter issues during migration:
1. Check logs: `docker-compose logs iam-service`
2. Verify database connection
3. Check environment variables
4. Review error messages stack traces
4. Review error messages and stack traces
## Quick Tips
**Migration Checklist:**
- ✅ Backup database and code
- ✅ Run database migrations
- ✅ Update deployment configuration
- ✅ Test backward compatibility
- ✅ Monitor gradual rollout
- ✅ Prepare rollback plan
**Common Issues:**
- Database connection errors → Check DATABASE_URL
- Missing environment variables → Verify .env file
- Type errors → Run `pnpm prisma generate`
- Service not starting → Check logs with `docker-compose logs`
**Visual Indicators:**
- 🔵 Old Components (Unchanged)
- 🟢 New Components (Added)
- 🔴 Components to Deprecate
- ⚠️ Requires Attention

View File

@@ -1,8 +1,6 @@
# Local Kubernetes Deployment Guide
> **EN**: Local Kubernetes Deployment Guide
>
> **VI**: Hướng dẫn triển khai Kubernetes cục bộ
**Last Updated**: 2026-01-05
**Difficulty**: Intermediate
@@ -12,36 +10,46 @@
```mermaid
graph TD
Start([Start]) --> EnvPrep[1. Environment Prep]
EnvPrep --> BuildImg[2. Build Docker Image]
BuildImg --> LoadImg[3. Load Image to Cluster<br/>(Kind/Docker Desktop)]
LoadImg --> Secrets[4. Configure Secrets<br/>& Environment]
Secrets --> Deploy[5. Deploy Service<br/>(K8s Manifests)]
Deploy --> Verify[6. Verify Deployment]
Verify --> Test[7. Test Service<br/>(Port Forward & Curl)]
Test --> End([Complete])
Start([🚀 Start]) --> EnvPrep[1️⃣ Environment Prep<br/>Enable K8s in Docker Desktop]
EnvPrep --> BuildImg[2️⃣ Build Docker Image<br/>docker build -t service:local]
BuildImg --> LoadImg[3️⃣ Load Image to Cluster<br/>kind load docker-image]
LoadImg --> Secrets[4️⃣ Configure Secrets<br/>kubectl create secret]
Secrets --> Deploy[5️⃣ Deploy Service<br/>kubectl apply -f manifests]
Deploy --> Verify[6️⃣ Verify Deployment<br/>kubectl get pods]
Verify --> Test[7️⃣ Test Service<br/>Port Forward & Curl]
Test --> End([Complete])
subgraph "Deployment Details"
Deploy --> |Apply| ConfigMap
Deploy --> |Apply| Deployment
Deploy --> |Apply| Service
subgraph Deployment["📦 Deployment Resources"]
Deploy --> |Apply| ConfigMap[ConfigMap<br/>Environment Config]
Deploy --> |Apply| K8sDeployment[Deployment<br/>Pod Template]
Deploy --> |Apply| Service[Service<br/>LoadBalancer/NodePort]
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
%% Start/End nodes - Success Green
style Start fill:#004d40,stroke:#00bfa5,stroke-width:3px,color:#e0f2f1
style End fill:#1b5e20,stroke:#66bb6a,stroke-width:3px,color:#e8f5e9
%% Workflow steps - Dark theme with distinct colors
style EnvPrep fill:#263238,stroke:#546e7a,stroke-width:2px,color:#eceff1
style BuildImg fill:#3e2723,stroke:#8d6e63,stroke-width:2px,color:#efebe9
style LoadImg fill:#1a237e,stroke:#5c6bc0,stroke-width:2px,color:#e8eaf6
style Secrets fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#ffebee
style Deploy fill:#004d40,stroke:#26a69a,stroke-width:2px,color:#e0f2f1
style Verify fill:#1565c0,stroke:#42a5f5,stroke-width:2px,color:#e3f2fd
style Test fill:#4a148c,stroke:#ab47bc,stroke-width:2px,color:#f3e5f5
%% Deployment resources subgraph
style Deployment fill:#1a1a1a,stroke:#424242,stroke-width:2px,color:#e0e0e0
style ConfigMap fill:#263238,stroke:#78909c,stroke-width:1px,color:#cfd8dc
style K8sDeployment fill:#263238,stroke:#78909c,stroke-width:1px,color:#cfd8dc
style Service fill:#263238,stroke:#78909c,stroke-width:1px,color:#cfd8dc
```
## Overview
This guide details how to deploy the IAM Service (or any microservice in the GoodGo ecosystem) to a local Kubernetes cluster using Docker Desktop on macOS.
> **Important Note**: This guide assumes you are using **Docker Desktop** with **Kubernetes enabled**. If you are using Minikube or plain Kind, the steps might differ slightly (especially the image loading part).
**Important:** This guide assumes you are using **Docker Desktop** with **Kubernetes enabled**. If you are using Minikube or plain Kind, the steps might differ slightly (especially the image loading part).
## 1. Prerequisites
@@ -83,13 +91,11 @@ This guide details how to deploy the IAM Service (or any microservice in the Goo
Check if `kubectl` is connected to the correct context:
```bash
# EN: Check current context
# VI: Kiểm tra context hiện tại
# Check current context
kubectl config current-context
# Expected Output: docker-desktop
# EN: List all nodes in the cluster
# VI: Liệt kê các node trong cluster
# List all nodes in the cluster
kubectl get nodes
# Expected Output:
# NAME STATUS ROLES AGE VERSION
@@ -101,17 +107,14 @@ kubectl get nodes
We need to build the service image before deploying. Taking `iam-service` as an example.
```bash
# EN: Navigate to the kubernetes deployment directory
# VI: Di chuyển đến thư mục deployments/local/kubernetes
# Navigate to the kubernetes deployment directory
cd deployments/local/kubernetes
# EN: Build the Docker image from the root context
# VI: Build Docker image từ root context
# Build the Docker image from the root context
# Note: -f points to service Dockerfile, context is 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
# Verify the image was built successfully
docker images | grep iam-service
# Expected Output:
# iam-service local [IMAGE_ID] [SIZE] [CREATED]
@@ -124,15 +127,13 @@ docker images | grep iam-service
If you are using **Kind** (Kubernetes in Docker) separately or a specific Docker Desktop config, you need to load the 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 into kind cluster (if using kind explicitly)
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)
# Validating image presence (optional, hard with Docker Desktop K8s directly)
```
> **Tip**: With default Docker Desktop, building the local image (`docker build ...`) is usually automatically available to Docker Desktop's K8s cluster. This loading step is mainly for those using `kind` CLI to create separate clusters.
**Tip:** With default Docker Desktop, building the local image (`docker build ...`) is usually automatically available to Docker Desktop's K8s cluster. This loading step is mainly for those using `kind` CLI to create separate clusters.
## 5. Configure Secrets & ConfigMap
@@ -143,12 +144,10 @@ Kubernetes environments need sensitive environment variables (Secrets) and gener
You can run a script or the following commands to create secrets securely.
```bash
# EN: Create a dedicated namespace for local testing
# VI: Tạo namespace riêng cho local testing
# Create a dedicated namespace for 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
# Generate random secrets and store in 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,20 +155,18 @@ 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
# Verify secrets creation
kubectl get secrets -n iam-local
```
> **Note on `host.docker.internal`**: On macOS, for a K8s pod to connect to PostgreSQL running on the host machine (or another container via port mapping), we use `host.docker.internal`.
**Note on `host.docker.internal`:** On macOS, for a K8s pod to connect to PostgreSQL running on the host machine (or another container via port mapping), we use `host.docker.internal`.
### 5.2 ConfigMap
The `iam-service-configmap.yaml` file typically contains non-sensitive variables like `NODE_ENV`, `LOG_LEVEL`.
```bash
# EN: Apply ConfigMap
# VI: Apply ConfigMap
# Apply ConfigMap
kubectl apply -f iam-service-configmap.yaml -n iam-local
```
@@ -178,12 +175,10 @@ kubectl apply -f iam-service-configmap.yaml -n iam-local
Now we will deploy the main resources.
```bash
# EN: Apply Deployment manifest
# VI: Apply file Deployment manifest
# Apply Deployment manifest
kubectl apply -f iam-service-deployment.yaml -n iam-local
# EN: Apply Service manifest (LoadBalancer/NodePort)
# VI: Apply file Service manifest
# Apply Service manifest (LoadBalancer/NodePort)
kubectl apply -f iam-service-service.yaml -n iam-local
```
@@ -194,8 +189,7 @@ After deployment, ensure the Pod is stable (Running).
### 7.1 Check Pods
```bash
# EN: Get all pods in the namespace
# VI: Lấy danh sách pod trong namespace
# Get all pods in the namespace
kubectl get pods -n iam-local
# Expected Output:
@@ -208,12 +202,10 @@ kubectl get pods -n iam-local
If Status is not `Running` (e.g., `CrashLoopBackOff` or `ImagePullBackOff`), check logs:
```bash
# EN: Stream logs from the pod
# VI: Xem logs thời gian thực từ pod
# Stream logs from the 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)
# Describe pod to see events (pull error, mounts, scheduling)
kubectl describe pod -n iam-local -l app=iam-service
```
@@ -236,8 +228,7 @@ kubectl describe pod -n iam-local -l app=iam-service
To access the service from your local machine, the safest way is `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 from local port 5002 to service port 80
kubectl port-forward svc/iam-service 5002:80 -n iam-local
# Terminal will hang and show: Forwarding from 127.0.0.1:5002 -> 8000
@@ -246,13 +237,11 @@ kubectl port-forward svc/iam-service 5002:80 -n iam-local
Open another terminal and 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)
# View Swagger/OpenAPI docs (if enabled)
open http://localhost:5002/api-docs
```
@@ -261,11 +250,61 @@ open http://localhost:5002/api-docs
When done, delete resources to free up capacity.
```bash
# EN: Delete the namespace (removes all resources within)
# VI: Xóa namespace (xóa tất cả resource bên trong)
# Delete the namespace (removes all resources within)
kubectl delete namespace iam-local
```
## 📚 Quick Tips
### Common Issues & Solutions
| Issue | Symptoms | Solution |
|-------|----------|----------|
| 🔴 **ImagePullBackOff** | Pod stuck in `ImagePullBackOff` | Set `imagePullPolicy: Never` in deployment YAML<br/>Run `kind load docker-image` if using Kind |
| 🔴 **CrashLoopBackOff** | Pod keeps restarting | Check logs with `kubectl logs`<br/>Verify `DATABASE_URL` in secrets<br/>Ensure DB is accessible via `host.docker.internal` |
| 🟡 **Pending LoadBalancer** | Service External-IP shows `<pending>` | Normal on local—use `kubectl port-forward` instead |
| 🟡 **Connection Refused** | Can't connect after port-forward | Check pod is `Running` (not `CrashLoopBackOff`)<br/>Verify correct port mapping |
### Essential Commands Reference
```bash
# 🔍 Debugging
kubectl get pods -n iam-local -w # Watch pods in real-time
kubectl describe pod <POD_NAME> -n iam-local # Detailed pod info + events
kubectl logs -f <POD_NAME> -n iam-local # Stream logs
kubectl exec -it <POD_NAME> -n iam-local -- /bin/sh # Shell into container
# 🔄 Image Management
docker build -t service:local -f Dockerfile . # Build image
kind load docker-image service:local --name desktop # Load to Kind cluster
docker images | grep service # List local images
# 🚀 Quick Deployment
kubectl apply -f deployment.yaml -n iam-local # Deploy single manifest
kubectl apply -f . -n iam-local # Deploy all files in directory
kubectl rollout restart deployment/iam-service -n iam-local # Force pod restart
# 🧹 Cleanup
kubectl delete pod <POD_NAME> -n iam-local --force # Force delete stuck pod
kubectl delete namespace iam-local --force --grace-period=0 # Force delete namespace
```
### Visual Status Indicators
- 🟢 **Running** - Service is healthy
- 🟡 **Pending** - Waiting for resources
- 🔴 **CrashLoopBackOff** - Service keeps failing (check logs!)
- 🔵 **ContainerCreating** - Pod starting up
- ⚫ **Terminating** - Pod shutting down
### Pro Tips
1. **⚡ Fast Rebuild**: For quick iteration, use `kubectl rollout restart deployment/iam-service -n iam-local` after rebuilding image
2. **🔍 Watch Mode**: Use `-w` flag to watch resources update in real-time
3. **📝 YAML Validation**: Run `kubectl apply --dry-run=client -f file.yaml` to validate before applying
4. **🎯 Label Filtering**: Use `-l app=iam-service` to filter resources by label instead of typing pod names
## References
- [Kubernetes Documentation](https://kubernetes.io/docs/)

View File

@@ -227,34 +227,77 @@ docker-compose logs traefik
## Network Architecture
```mermaid
graph TB
Client[👤 Client<br/>Browser] --> Traefik
Traefik[🌐 Traefik<br/>API Gateway<br/>:80, :8080]
Traefik --> IAM[🔐 IAM Service<br/>Authentication<br/>:5001]
Traefik --> Admin[⚙️ Web Admin<br/>Dashboard<br/>:3000]
Traefik --> WebClient[🌍 Web Client<br/>Application<br/>:3001]
IAM --> Redis[(💾 Redis<br/>Cache<br/>:6379)]
IAM --> DB[(🗄️ PostgreSQL<br/>Neon Database)]
classDef client fill:#1a1a2e,stroke:#16213e,stroke-width:2px,color:#eee
classDef gateway fill:#0f3460,stroke:#16213e,stroke-width:3px,color:#eee
classDef service fill:#16213e,stroke:#533483,stroke-width:2px,color:#eee
classDef frontend fill:#1a1a40,stroke:#6c5ce7,stroke-width:2px,color:#eee
classDef data fill:#2d132c,stroke:#801336,stroke-width:2px,color:#eee
class Client client
class Traefik gateway
class IAM service
class Admin,WebClient frontend
class Redis,DB data
```
┌─────────────────────────────────────────────────────────────┐
│ Client │
└───────────────────────────┬─────────────────────────────────┘
┌───────────────┐
│ Traefik │ :80, :8080
│ API Gateway │
└───────┬───────┘
┌───────────────────┼───────────────────┐
│ │ │
▼ ▼ ▼
┌──────────────┐ ┌──────────────┐ ┌──────────────┐
│ iam-service │ │ web-admin │ │ web-client │
│ :5001 │ │ :3000 │ │ :3001 │
└──────┬───────┘ └──────────────┘ └──────────────┘
├─────────────┐
│ │
▼ ▼
┌──────────┐ ┌─────────────┐
│ Redis │ │ PostgreSQL │
│ :6379 │ │ (Neon) │
└──────────┘ └─────────────┘
**Legend:**
- 👤 **Client**: External users via browser
- 🌐 **Gateway**: Traefik API Gateway (auto-routing)
- 🔐 **Backend**: IAM Service (authentication)
- ⚙️ **Frontend**: Web Admin & Client applications
- 💾 **Storage**: Redis cache & PostgreSQL database
## Quick Tips
### 🚨 Common Issues
| Problem | Solution |
|---------|----------|
| **Port conflict** | Check if port 80/5001/6379 is already in use: `lsof -i :<port>` |
| **Service won't start** | Check logs: `docker-compose logs <service-name>` |
| **Database connection** | Verify `DATABASE_URL` in `.env.local` is correct |
| **Redis connection** | Ensure Redis is healthy: `docker-compose exec redis redis-cli ping` |
| **Traefik routing** | Check dashboard at http://localhost:8080 for route status |
### 🎯 Development Workflow
```bash
# Quick restart (code changes)
docker-compose restart iam-service
# Full rebuild (dependency changes)
docker-compose up -d --build iam-service
# Clean restart (database issues)
docker-compose down -v && docker-compose up -d
```
### 🔐 Security Checklist
- ✅ Change default `JWT_SECRET` (min 32 characters)
- ✅ Use environment-specific `.env.local` (never commit)
- ✅ Verify CORS origins match your frontend URLs
- ✅ Enable HTTPS in production (not needed for local)
### 📊 Monitoring
- **Traefik Dashboard**: http://localhost:8080 - View all routes and services
- **Service Health**: http://localhost/api/v1/auth/health - Check service status
- **Redis CLI**: `docker-compose exec redis redis-cli` - Query cache directly
## Resources
- [Traefik Configuration](../../infra/traefik/)

View File

@@ -1,41 +1,33 @@
# Mermaid Diagram Guide / Hướng dẫn Sơ đồ Mermaid
# Mermaid Diagram Guide
## Overview / Tổng quan
## Overview
**EN**: This guide helps you choose the right Mermaid diagram type for your documentation and provides examples for common use cases.
This guide helps you choose the right Mermaid diagram type for your documentation and provides examples for common use cases.
**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.
## Quick Reference
## Quick Reference / Tham chiếu Nhanh
| Diagram Type / Loại | Use For / Sử dụng cho | Complexity / Độ phức tạp |
| Diagram Type | Use For | Complexity |
|----------------------|------------------------|---------------------------|
| **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 | ⭐⭐⭐⭐ |
| **Flowchart** | Workflows, decision trees | ⭐⭐ |
| **Sequence Diagram** | API interactions, request flows | ⭐⭐⭐ |
| **Class Diagram** | Code structure, patterns | ⭐⭐⭐ |
| **Graph** | System architecture, dependencies | ⭐⭐ |
| **ER Diagram** | Database schema | ⭐⭐⭐ |
| **Gantt** | Timeline, project schedule | ⭐⭐ |
| **C4 Diagram** | System context, containers | ⭐⭐⭐⭐ |
---
## 1. Flowcharts / Sơ đồ Luồng
## 1. Flowcharts
### When to Use / Khi nào sử dụng
### When to Use
**EN**: Use flowcharts for:
Use flowcharts for:
- Step-by-step guides and workflows (e.g., **"Onboarding process"**)
- Decision trees and conditional logic (e.g., **"Discount calculation"**)
- Process flows with multiple branches (e.g., **"Order fulfillment"**)
- Troubleshooting procedures (e.g., **"Login issue diagnosis"**)
**VI**: Sử dụng flowcharts cho:
- Hướng dẫn từng bước và quy trình
- Cây quyết định và logic điều kiện
- Luồng quy trình với nhiều nhánh
- Thủ tục khắc phục sự cố
### Basic Flowchart
```mermaid
@@ -48,10 +40,13 @@ flowchart TD
Output --> End([End])
Error --> End
style Start fill:#e1f5ff
style End fill:#d4edda
style Check fill:#fff3cd
style Error fill:#f8d7da
style Start fill:#2C3E50,stroke:#34495E,stroke-width:2px,color:#ECF0F1
style End fill:#27AE60,stroke:#229954,stroke-width:2px,color:#ECF0F1
style Check fill:#F39C12,stroke:#D68910,stroke-width:2px,color:#ECF0F1
style Error fill:#C0392B,stroke:#A93226,stroke-width:2px,color:#ECF0F1
style Process fill:#2980B9,stroke:#1F618D,stroke-width:2px,color:#ECF0F1
style Input fill:#34495E,stroke:#2C3E50,stroke-width:2px,color:#ECF0F1
style Output fill:#34495E,stroke:#2C3E50,stroke-width:2px,color:#ECF0F1
```
**Explanation**: A basic flowchart starting with an input, followed by a validation check. If valid, it proceeds to processing and returns a result; otherwise, it shows an error and ends.
@@ -68,10 +63,10 @@ flowchart TD
Output --> End([End])
Error --> End
style Start fill:#e1f5ff
style End fill:#d4edda
style Check fill:#fff3cd
style Error fill:#f8d7da
style Start fill:#2C3E50,stroke:#34495E,stroke-width:2px,color:#ECF0F1
style End fill:#27AE60,stroke:#229954,stroke-width:2px,color:#ECF0F1
style Check fill:#F39C12,stroke:#D68910,stroke-width:2px,color:#ECF0F1
style Error fill:#C0392B,stroke:#A93226,stroke-width:2px,color:#ECF0F1
```
````
@@ -93,29 +88,32 @@ flowchart LR
C --> I[End]
H --> I
style Processing fill:#f0e1ff
style Processing fill:#34495E,stroke:#2C3E50,stroke-width:2px,color:#ECF0F1
style A fill:#2980B9,stroke:#1F618D,stroke-width:2px,color:#ECF0F1
style B fill:#F39C12,stroke:#D68910,stroke-width:2px,color:#ECF0F1
style C fill:#C0392B,stroke:#A93226,stroke-width:2px,color:#ECF0F1
style D fill:#2980B9,stroke:#1F618D,stroke-width:2px,color:#ECF0F1
style E fill:#2980B9,stroke:#1F618D,stroke-width:2px,color:#ECF0F1
style F fill:#2980B9,stroke:#1F618D,stroke-width:2px,color:#ECF0F1
style G fill:#2980B9,stroke:#1F618D,stroke-width:2px,color:#ECF0F1
style H fill:#27AE60,stroke:#229954,stroke-width:2px,color:#ECF0F1
style I fill:#2C3E50,stroke:#34495E,stroke-width:2px,color:#ECF0F1
```
**Explanation**: A flowchart featuring an authorization check and a dedicated **Subgraph** for detailed request processing steps.
---
## 2. Sequence Diagrams / Sơ đồ Tuần tự
## 2. Sequence Diagrams
### When to Use / Khi nào sử dụng
### When to Use
**EN**: Use sequence diagrams for:
Use sequence diagrams for:
- API communication flows (e.g., **"New order creation API"**)
- Authentication/authorization flows (e.g., **"OAuth2 login flow"**)
- Service-to-service interactions (e.g., **"Microservices sync/async calls"**)
- Request/response cycles (e.g., **"Checkout process"**)
**VI**: Sử dụng sequence diagrams cho:
- Luồng giao tiếp API
- Luồng xác thực/phân quyền
- Tương tác giữa các service
- Chu kỳ request/response
### Basic Sequence Diagram
```mermaid
@@ -183,22 +181,16 @@ sequenceDiagram
---
## 3. Class Diagrams / Sơ đồ Class
## 3. Class Diagrams
### When to Use / Khi nào sử dụng
### When to Use
**EN**: Use class diagrams for:
Use class diagrams for:
- Design patterns and code structure (e.g., **"Singleton Pattern for Logger"**)
- Object-oriented architecture (e.g., **"Domain-Driven Design (DDD) models"**)
- Inheritance and relationships (e.g., **"Repository base and concrete classes"**)
- Module dependencies (e.g., **"Service layer dependencies"**)
**VI**: Sử dụng class diagrams cho:
- Design patterns và cấu trúc code
- Kiến trúc hướng đối tượng
- Kế thừa và mối quan hệ
- Dependencies giữa các module
### Basic Class Diagram
```mermaid
@@ -231,22 +223,16 @@ classDiagram
---
## 4. Graph Diagrams / Sơ đồ Graph
## 4. Graph Diagrams
### When to Use / Khi nào sử dụng
### When to Use
**EN**: Use graph diagrams for:
Use graph diagrams for:
- System architecture overview (e.g., **"Microservices Architecture"**)
- Component relationships (e.g., **"Service-to-database mapping"**)
- Data flow diagrams (e.g., **"Request processing pipeline"**)
- Dependency graphs (e.g., **"Package to package dependencies"**)
**VI**: Sử dụng graph diagrams cho:
- Tổng quan kiến trúc hệ thống
- Mối quan hệ giữa các thành phần
- Sơ đồ luồng dữ liệu
- Đồ thị dependencies
### System Architecture
```mermaid
@@ -260,14 +246,15 @@ graph TD
IAM --> DB
User --> DB
User --> Cache
User --> Cache[(Redis Cache)]
style Gateway fill:#2980b9,stroke:#333,stroke-width:2px,color:#fff
style Auth fill:#8e44ad,stroke:#333,stroke-width:2px,color:#fff
style IAM fill:#8e44ad,stroke:#333,stroke-width:2px,color:#fff
style User fill:#8e44ad,stroke:#333,stroke-width:2px,color:#fff
style DB fill:#f39c12,stroke:#333,stroke-width:2px,color:#fff
style Cache fill:#f39c12,stroke:#333,stroke-width:2px,color:#fff
style Client fill:#34495E,stroke:#2C3E50,stroke-width:2px,color:#ECF0F1
style Gateway fill:#2980B9,stroke:#1F618D,stroke-width:2px,color:#ECF0F1
style Auth fill:#8E44AD,stroke:#7D3C98,stroke-width:2px,color:#ECF0F1
style IAM fill:#8E44AD,stroke:#7D3C98,stroke-width:2px,color:#ECF0F1
style User fill:#8E44AD,stroke:#7D3C98,stroke-width:2px,color:#ECF0F1
style DB fill:#F39C12,stroke:#D68910,stroke-width:2px,color:#ECF0F1
style Cache fill:#E67E22,stroke:#CA6F1E,stroke-width:2px,color:#ECF0F1
```
**Explanation**: A high-level view of the system architecture showing how the Gateway routes requests to different services, all connected to a shared Database and Cache.
@@ -283,33 +270,32 @@ graph LR
Repository --> Prisma[Prisma ORM]
Prisma --> DB[(Database)]
Cache --> Redis[(Redis)]
Service --> Cache[(Redis Cache)]
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:#34495E,stroke:#2C3E50,stroke-width:2px,color:#ECF0F1
style Validation fill:#27AE60,stroke:#229954,stroke-width:2px,color:#ECF0F1
style Controller fill:#2980B9,stroke:#1F618D,stroke-width:2px,color:#ECF0F1
style Service fill:#2980B9,stroke:#1F618D,stroke-width:2px,color:#ECF0F1
style Repository fill:#2980B9,stroke:#1F618D,stroke-width:2px,color:#ECF0F1
style Prisma fill:#8E44AD,stroke:#7D3C98,stroke-width:2px,color:#ECF0F1
style DB fill:#F39C12,stroke:#D68910,stroke-width:2px,color:#ECF0F1
style Cache fill:#E67E22,stroke:#CA6F1E,stroke-width:2px,color:#ECF0F1
```
**Explanation**: A detailed data flow showing Input going through Validation -> Controller -> Service -> Repository -> ORM -> DB, while also interacting with the Cache.
---
## 5. ER Diagrams / Sơ đồ ER
## 5. ER Diagrams
### When to Use / Khi nào sử dụng
### When to Use
**EN**: Use ER diagrams for:
Use ER diagrams for:
- Database schema documentation (e.g., **"User and IAM tables"**)
- Entity relationships (e.g., **"One-to-many between User and Sessions"**)
- Data modeling (e.g., **"Designing new feature entities"**)
- Prisma schema visualization (e.g., **"Mapping code entities to DB tables"**)
**VI**: 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
- Visualization Prisma schema
### Database Schema
```mermaid
@@ -359,22 +345,16 @@ erDiagram
---
## 6. Gantt Charts / Biểu đồ Gantt
## 6. Gantt Charts
### When to Use / Khi nào sử dụng
### When to Use
**EN**: Use Gantt charts for:
Use Gantt charts for:
- Project timelines
- Implementation phases
- Migration schedules
- Deployment plans
**VI**: Sử dụng Gantt charts cho:
- Timeline dự án
- Các giai đoạn triển khai
- Lịch trình migration
- Kế hoạch deployment
### Project Timeline
```mermaid
@@ -395,22 +375,16 @@ gantt
---
## 7. C4 Diagrams / Sơ đồ C4
## 7. C4 Diagrams
### When to Use / Khi nào sử dụng
### When to Use
**EN**: Use C4 diagrams for:
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:
- Bối cảnh hệ thống (cấp cao nhất)
- Sơ đồ container (services, databases)
- Sơ đồ component (modules trong services)
- Sơ đồ code (classes, functions)
### System Context
```mermaid
@@ -433,64 +407,118 @@ C4Context
---
## Styling Tips / Mẹo Styling
## Color Palette Reference
### Color Palette / Bảng màu
### Dark Theme Color System
Our diagrams use a consistent dark color palette based on professional design principles:
```mermaid
graph LR
A["Primary<br/>#e1f5ff"] --> B["Secondary<br/>#fff4e1"]
B --> C["Success<br/>#d4edda"]
C --> D["Warning<br/>#fff3cd"]
D --> E["Error<br/>#f8d7da"]
E --> F["Info<br/>#f0e1ff"]
subgraph Primary["🎨 Primary Colors"]
A1["Dark Blue<br/>#2980B9"]
A2["Purple<br/>#8E44AD"]
A3["Green<br/>#27AE60"]
end
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
subgraph Secondary["🎨 Secondary Colors"]
B1["Orange<br/>#E67E22"]
B2["Yellow<br/>#F39C12"]
B3["Red<br/>#C0392B"]
end
subgraph Neutrals["🎨 Neutral Colors"]
C1["Dark Gray<br/>#2C3E50"]
C2["Medium Gray<br/>#34495E"]
C3["Light Text<br/>#ECF0F1"]
end
style A1 fill:#2980B9,stroke:#1F618D,stroke-width:3px,color:#ECF0F1
style A2 fill:#8E44AD,stroke:#7D3C98,stroke-width:3px,color:#ECF0F1
style A3 fill:#27AE60,stroke:#229954,stroke-width:3px,color:#ECF0F1
style B1 fill:#E67E22,stroke:#CA6F1E,stroke-width:3px,color:#ECF0F1
style B2 fill:#F39C12,stroke:#D68910,stroke-width:3px,color:#ECF0F1
style B3 fill:#C0392B,stroke:#A93226,stroke-width:3px,color:#ECF0F1
style C1 fill:#2C3E50,stroke:#1C2833,stroke-width:3px,color:#ECF0F1
style C2 fill:#34495E,stroke:#2C3E50,stroke-width:3px,color:#ECF0F1
style C3 fill:#ECF0F1,stroke:#BDC3C7,stroke-width:3px,color:#2C3E50
```
**Explanation**: The recommended color palette for consistent diagram styling within the project.
### Color Usage Guidelines
### Style Syntax
| Color | Hex Code | Use For | Example |
|-------|----------|---------|---------|
| **Dark Blue** | `#2980B9` | ✅ Services, Processing, APIs | User Service, API Gateway |
| **Purple** | `#8E44AD` | ✅ Core Components, ORM | Prisma, IAM Service |
| **Green** | `#27AE60` | ✅ Success, Validation, End States | Success Flow, Validated Data |
| **Orange** | `#E67E22` | ⚠️ Cache, Warning States | Redis Cache, Warnings |
| **Yellow** | `#F39C12` | ⚠️ Database, Important Decisions | PostgreSQL, Decision Nodes |
| **Red** | `#C0392B` | ❌ Errors, Failures, Alerts | Error States, Failed Operations |
| **Dark Gray** | `#2C3E50` | 🔘 Start/End, Neutral Elements | Start Node, End Node |
| **Medium Gray** | `#34495E` | 🔘 Subgraphs, Background | Processing Groups, Containers |
| **Light Text** | `#ECF0F1` | 📝 Text Color (always use) | All node text |
### Standard Style Pattern
Always include these three properties for professional appearance:
```markdown
style NodeId fill:#colorcode,stroke:#bordercolor,stroke-width:2px
style NodeName fill:#HexColor,stroke:#DarkerShade,stroke-width:2px,color:#ECF0F1
```
**Examples**:
```markdown
style Start fill:#e1f5ff
style Error fill:#f8d7da
style Process fill:#d4edda,stroke:#28a745,stroke-width:2px
```
**Components:**
- `fill`: Main background color
- `stroke`: Border color (typically darker shade of fill)
- `stroke-width`: Border thickness (use `2px` for standard, `3px` for emphasis)
- `color`: Text color (always use `#ECF0F1` for dark backgrounds)
### Node Type Color Patterns
| Node Type | Fill Color | Stroke Color | Use Case |
|-----------|------------|--------------|----------|
| **Services** | `#2980B9` | `#1F618D` | Auth Service, User Service |
| **API/Gateway** | `#2980B9` | `#1F618D` | Traefik, API Gateway |
| **Database** | `#F39C12` | `#D68910` | PostgreSQL, MySQL |
| **Cache** | `#E67E22` | `#CA6F1E` | Redis, Memcached |
| **ORM/Framework** | `#8E44AD` | `#7D3C98` | Prisma, TypeORM |
| **Success/End** | `#27AE60` | `#229954` | Success Flow, Completion |
| **Error/Failure** | `#C0392B` | `#A93226` | Error States, Failures |
| **Decision** | `#F39C12` | `#D68910` | Validation, Conditionals |
| **Start** | `#2C3E50` | `#1C2833` | Entry Point |
| **Process** | `#34495E` | `#2C3E50` | General Processing |
### Quick Color Selection Guide
**Choose colors based on node function:**
🔵 **Blue (`#2980B9`)** → Services, APIs, Controllers
🟣 **Purple (`#8E44AD`)** → Core Systems, ORM, Frameworks
🟢 **Green (`#27AE60`)** → Success, Validation, Completion
🟠 **Orange (`#E67E22`)** → Cache, Memory, Storage
🟡 **Yellow (`#F39C12`)** → Databases, Decisions, Important Actions
🔴 **Red (`#C0392B`)** → Errors, Failures, Critical Issues
⚫ **Dark Gray (`#2C3E50`)** → Start/End, Neutral States
⚫ **Medium Gray (`#34495E`)** → Containers, Subgraphs, Groups
---
## Best Practices / Best Practices
## Best Practices
### EN: Guidelines
### 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
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
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
6. **Dark Theme**: Always use dark color palette for professional appearance
7. **Text Contrast**: Always use `color:#ECF0F1` for text on dark backgrounds
---
## Common Pitfalls / Lỗi Thường gặp
## Common Pitfalls
### ❌ Too Complex
@@ -517,21 +545,27 @@ graph TD
A[Start] --> B[Process A]
B --> C[Process B]
subgraph "Detailed Processing"
subgraph Detailed["Detailed Processing"]
C --> D[Step 1]
D --> E[Step 2]
end
E --> F[End]
style Detailed fill:#34495E,stroke:#2C3E50,stroke-width:2px,color:#ECF0F1
style A fill:#2C3E50,stroke:#1C2833,stroke-width:2px,color:#ECF0F1
style F fill:#27AE60,stroke:#229954,stroke-width:2px,color:#ECF0F1
style B fill:#2980B9,stroke:#1F618D,stroke-width:2px,color:#ECF0F1
style C fill:#2980B9,stroke:#1F618D,stroke-width:2px,color:#ECF0F1
style D fill:#2980B9,stroke:#1F618D,stroke-width:2px,color:#ECF0F1
style E fill:#2980B9,stroke:#1F618D,stroke-width:2px,color:#ECF0F1
```
---
## Testing Diagrams / Test Sơ đồ
## Testing Diagrams
**EN**: Always test your diagrams before committing:
**VI**: Luôn test sơ đồ trước khi commit:
Always test your diagrams before committing:
```bash
# Install mermaid-cli
@@ -540,7 +574,7 @@ npm install -g @mermaid-js/mermaid-cli
# Test render (SVG)
mmdc -i your-doc.md -o test-output.svg
# Render high-quality PNG with black background
# Render high-quality PNG with dark theme
mmdc -i your-doc.md -o test-output.png -b black -t dark -s 3
# Render ALL diagrams in a markdown file
@@ -556,7 +590,67 @@ mmdc -i your-doc.md
---
## Resources / Tài nguyên
## Quick Tips
### 🔧 Mermaid Common Issues
**Issue**: Diagram not rendering
- ✅ Check for syntax errors (missing arrows, brackets)
- ✅ Ensure proper indentation in subgraphs
- ✅ Validate special characters are escaped
**Issue**: Colors not applying
- ✅ Place style commands after all node definitions
- ✅ Use exact node IDs in style statements
- ✅ Ensure hex colors include `#` prefix
**Issue**: Text overlapping
- ✅ Use shorter labels or `<br/>` for line breaks
- ✅ Adjust diagram direction (TD, LR, RL, BT)
- ✅ Increase spacing between nodes
### 🎨 Color Pattern Quick Reference
```markdown
// Services & APIs
style Node fill:#2980B9,stroke:#1F618D,stroke-width:2px,color:#ECF0F1
// Database
style Node fill:#F39C12,stroke:#D68910,stroke-width:2px,color:#ECF0F1
// Cache
style Node fill:#E67E22,stroke:#CA6F1E,stroke-width:2px,color:#ECF0F1
// Success/End
style Node fill:#27AE60,stroke:#229954,stroke-width:2px,color:#ECF0F1
// Error/Failure
style Node fill:#C0392B,stroke:#A93226,stroke-width:2px,color:#ECF0F1
// Decision Points
style Node fill:#F39C12,stroke:#D68910,stroke-width:2px,color:#ECF0F1
// Start/Neutral
style Node fill:#2C3E50,stroke:#1C2833,stroke-width:2px,color:#ECF0F1
```
### 📊 Visual Indicators
Use emojis to enhance diagram readability:
- 🔵 Services & APIs
- 🟣 Core Systems
- 🟢 Success Paths
- 🟡 Databases
- 🟠 Cache/Storage
- 🔴 Errors
- ⚫ Neutral/Start/End
- ⚠️ Warnings
- ✅ Validated
- ❌ Failed
---
## Resources
- [Mermaid Official Documentation](https://mermaid.js.org/) - Complete reference
- [Mermaid Live Editor](https://mermaid.live/) - Test diagrams online
@@ -564,4 +658,4 @@ mmdc -i your-doc.md
---
**Last Updated**: 2026-01-05
**Last Updated**: 2026-01-08

View File

@@ -11,6 +11,37 @@ This project uses [Neon PostgreSQL](https://neon.tech) for all environments.
-**Free tier**: Perfect for development
-**Connection pooling**: Built-in PgBouncer support
## Architecture Overview
```mermaid
graph TD
Project["📦 Neon Project<br/>goodgo-platform"]
Dev["🔧 Development Branch<br/>main"]
Staging["🧪 Staging Branch<br/>staging"]
Prod["🚀 Production Branch<br/>production"]
LocalDev["💻 Local Dev<br/>.env.local"]
K8sStaging["☸️ Kubernetes<br/>staging namespace"]
K8sProd["☸️ Kubernetes<br/>production namespace"]
Project --> Dev
Project --> Staging
Project --> Prod
Dev -.->|DATABASE_URL| LocalDev
Staging -.->|Secret| K8sStaging
Prod -.->|Secret| K8sProd
style Project fill:#1e293b,stroke:#3b82f6,stroke-width:3px,color:#fff
style Dev fill:#0f172a,stroke:#10b981,stroke-width:2px,color:#fff
style Staging fill:#0f172a,stroke:#f59e0b,stroke-width:2px,color:#fff
style Prod fill:#0f172a,stroke:#ef4444,stroke-width:2px,color:#fff
style LocalDev fill:#475569,stroke:#94a3b8,stroke-width:2px,color:#fff
style K8sStaging fill:#475569,stroke:#94a3b8,stroke-width:2px,color:#fff
style K8sProd fill:#475569,stroke:#94a3b8,stroke-width:2px,color:#fff
```
## Quick Start
### 1. Create Neon Account
@@ -91,6 +122,65 @@ kubectl create secret generic iam-service-secrets \
## Migrations
### Migration Workflow
```mermaid
graph LR
subgraph Local["💻 Local Development"]
Schema["📝 Update Schema<br/>prisma/schema.prisma"]
CreateMig["🔧 Create Migration<br/>migrate dev"]
TestLocal["✅ Test Locally"]
end
subgraph CI["⚙️ CI/CD Pipeline"]
Push["📤 Git Push"]
Build["🔨 Build"]
TestCI["🧪 Run Tests"]
end
subgraph Staging["🧪 Staging"]
MigStaging["📊 Run Migrations<br/>migrate deploy"]
TestStaging["✅ Verify Schema"]
end
subgraph Prod["🚀 Production"]
Approval["👤 Manual Approval"]
MigProd["📊 Run Migrations<br/>migrate deploy"]
Rollback["🔄 Rollback Plan"]
end
Schema --> CreateMig
CreateMig --> TestLocal
TestLocal --> Push
Push --> Build
Build --> TestCI
TestCI --> MigStaging
MigStaging --> TestStaging
TestStaging --> Approval
Approval --> MigProd
MigProd -.->|If Failed| Rollback
style Local fill:#1e293b,stroke:#3b82f6,stroke-width:2px,color:#fff
style CI fill:#1e293b,stroke:#8b5cf6,stroke-width:2px,color:#fff
style Staging fill:#1e293b,stroke:#f59e0b,stroke-width:2px,color:#fff
style Prod fill:#1e293b,stroke:#ef4444,stroke-width:2px,color:#fff
style Schema fill:#0f172a,stroke:#10b981,color:#fff
style CreateMig fill:#0f172a,stroke:#10b981,color:#fff
style TestLocal fill:#0f172a,stroke:#10b981,color:#fff
style Push fill:#475569,stroke:#94a3b8,color:#fff
style Build fill:#475569,stroke:#94a3b8,color:#fff
style TestCI fill:#475569,stroke:#94a3b8,color:#fff
style MigStaging fill:#0f172a,stroke:#f59e0b,color:#fff
style TestStaging fill:#0f172a,stroke:#f59e0b,color:#fff
style Approval fill:#475569,stroke:#94a3b8,color:#fff
style MigProd fill:#0f172a,stroke:#ef4444,color:#fff
style Rollback fill:#7f1d1d,stroke:#ef4444,color:#fff
```
### Development
```bash
@@ -208,6 +298,52 @@ Monitor your databases via Neon Console:
4. **Regular backups**: Use Neon's automatic backups
5. **Monitor usage**: Check Neon Console regularly
## Quick Tips
### 🎨 Mermaid Diagram Color Palette
| Element | Color | Usage |
|---------|-------|-------|
| **Project/Main** | `#1e293b` + `#3b82f6` | Primary containers |
| **Development** | `#0f172a` + `#10b981` | Dev environment (green) |
| **Staging** | `#0f172a` + `#f59e0b` | Staging environment (orange) |
| **Production** | `#0f172a` + `#ef4444` | Prod environment (red) |
| **Infrastructure** | `#475569` + `#94a3b8` | K8s, CI/CD (gray) |
| **Error/Rollback** | `#7f1d1d` + `#ef4444` | Critical actions (dark red) |
### 🚨 Common Mermaid Issues
**Syntax Errors:**
- ✅ Use quotes for labels with special chars: `["Label<br/>text"]`
- ✅ Escape HTML entities: `&amp;` not `&`
- ✅ Use `<br/>` for line breaks inside labels
- ❌ Avoid `<br>` without closing slash
**Rendering Issues:**
- If diagram doesn't render, check for matching brackets `[]` or `{}`
- Verify all style declarations use valid CSS colors
- Ensure subgraph names are unique
### 📊 Visual Indicators
| Icon | Meaning |
|------|---------|
| 📦 | Project/Package |
| 🔧 | Development/Tools |
| 🧪 | Testing/Staging |
| 🚀 | Production/Deploy |
| 💻 | Local Environment |
| ☸️ | Kubernetes |
| ⚙️ | CI/CD Pipeline |
| 📝 | Configuration/Schema |
| 📊 | Database/Data |
| ✅ | Success/Validation |
| ❌ | Error/Failed |
| 🔄 | Rollback/Retry |
| 👤 | Manual Action |
| 📤 | Push/Upload |
| 🔨 | Build Process |
## Resources
- [Neon Documentation](https://neon.tech/docs)

View File

@@ -4,19 +4,97 @@ This guide explains how to use the observability stack (Grafana, Prometheus, Lok
## Architecture Overview
### Components
The stack consists of the following components:
- **Prometheus**: Collects metrics from services.
- **Loki**: Collects logs.
- **Promtail**: Scrapes logs from Docker containers and pushes them to Loki.
- **Grafana**: Visualization dashboard for metrics (from Prometheus) and logs (from Loki).
- **Prometheus**: Metrics collection and storage
- **Loki**: Log aggregation system
- **Promtail**: Log collector agent
- **Grafana**: Unified visualization dashboard
### Architecture Diagram
```mermaid
flowchart LR
subgraph Services["Microservices"]
IAM[IAM Service]
USER[User Service]
TRAEFIK[Traefik Gateway]
end
subgraph Collection["Data Collection"]
PROM[Prometheus]
PROMTAIL[Promtail]
end
subgraph Storage["Data Storage"]
PROM_DB[(Prometheus DB)]
LOKI_DB[(Loki DB)]
end
subgraph Visualization["Visualization"]
GRAFANA[Grafana Dashboard]
end
IAM -->|Metrics| PROM
USER -->|Metrics| PROM
TRAEFIK -->|Metrics| PROM
IAM -.->|Logs| PROMTAIL
USER -.->|Logs| PROMTAIL
TRAEFIK -.->|Logs| PROMTAIL
PROM -->|Store| PROM_DB
PROMTAIL -->|Push| LOKI_DB
PROM_DB -->|Query| GRAFANA
LOKI_DB -->|Query| GRAFANA
style Services fill:#2d3748
style Collection fill:#2c5282
style Storage fill:#2f855a
style Visualization fill:#744210
style IAM fill:#4a5568
style USER fill:#4a5568
style TRAEFIK fill:#4a5568
style PROM fill:#3182ce
style PROMTAIL fill:#3182ce
style PROM_DB fill:#38a169
style LOKI_DB fill:#38a169
style GRAFANA fill:#d69e2e
```
### Data Flow
```mermaid
sequenceDiagram
participant S as Service
participant PT as Promtail
participant P as Prometheus
participant L as Loki
participant G as Grafana
Note over S,G: Metrics Flow
S->>P: Expose /metrics endpoint
P->>P: Scrape metrics (15s interval)
G->>P: Query PromQL
P-->>G: Return metrics data
Note over S,G: Logs Flow
S->>PT: Write logs to stdout
PT->>PT: Parse & Label logs
PT->>L: Push logs via HTTP
G->>L: Query LogQL
L-->>G: Return log data
```
## Getting Started
### Prerequisites
- Docker and Docker Compose installed.
- Existing `microservices-network` (created by the main application stack or manually).
- Docker and Docker Compose installed
- Existing `microservices-network` (created by the main application stack or manually)
### Starting the Stack
@@ -29,7 +107,6 @@ You can easily start the stack using the provided script:
Or manually:
```bash
# Ensure network exists
docker network create microservices-network || true
cd infra/observability
@@ -46,44 +123,171 @@ You should see `grafana`, `prometheus`, `loki`, and `promtail`.
## Accessing Services
| Service | URL | Credentials (if applicable) | Description |
| Service | URL | Credentials | Description |
| :--- | :--- | :--- | :--- |
| **Grafana** | [http://localhost:3001](http://localhost:3001) | `admin` / `admin` | Main dashboard for visualization. |
| **Prometheus** | [http://localhost:9090](http://localhost:9090) | N/A | Raw metrics and target status. |
| **Loki** | [http://localhost:3100](http://localhost:3100) | N/A | Log aggregation API (no UI). |
| **Grafana** | [http://localhost:3001](http://localhost:3001) | `admin` / `admin` | Main dashboard for visualization |
| **Prometheus** | [http://localhost:9090](http://localhost:9090) | N/A | Raw metrics and target status |
| **Loki** | [http://localhost:3100](http://localhost:3100) | N/A | Log aggregation API (no UI) |
## Using Grafana
1. **Login**: Access [http://localhost:3001](http://localhost:3001) and login with `admin`/`admin`.
2. **Explore Data**:
- Go to **Explore** (compass icon) in the sidebar.
- Select **Loki** from the datasource dropdown to search logs.
- Select **Prometheus** from the datasource dropdown to query metrics.
### Initial Setup
1. **Login**: Access [http://localhost:3001](http://localhost:3001) and login with `admin`/`admin`
2. **Change Password**: You'll be prompted to change the default password (recommended)
3. **Verify Datasources**:
- Navigate to **Configuration****Data Sources**
- Ensure both **Prometheus** and **Loki** are connected
### Exploring Data
Go to **Explore** (compass icon) in the sidebar:
- Select **Loki** from the datasource dropdown to search logs
- Select **Prometheus** from the datasource dropdown to query metrics
### Viewing Logs (Loki)
In the **Explore** view with **Loki** selected:
1. Click **Label browser**.
2. Select a label, e.g., `container`.
3. Choose a specific container (e.g., `iam-service` or `traefik`).
4. Click **Show logs**.
1. Click **Label browser**
2. Select a label, e.g., `container`
3. Choose a specific container (e.g., `iam-service` or `traefik`)
4. Click **Show logs**
You can also write LogQL queries manually, for example:
**LogQL Query Examples:**
```logql
{container="iam-service"}
{container="iam-service"} |= "error"
{container="iam-service"} |= "error" | json
```
### Viewing Metrics (Prometheus)
In the **Explore** view with **Prometheus** selected:
1. Type a metric name in the query field (e.g., `up`, `container_memory_usage_bytes`).
2. Click **Run query**.
1. Type a metric name in the query field (e.g., `up`, `container_memory_usage_bytes`)
2. Click **Run query**
**PromQL Query Examples:**
```promql
up
rate(http_requests_total[5m])
container_memory_usage_bytes{container="iam-service"}
```
## Configuration
- **Prometheus**: Rules and targets are configured in `infra/observability/prometheus/prometheus.yml`.
- **Promtail**: Log scraping rules are configured in `infra/observability/promtail/promtail-config.yml`.
- **Grafana**: Datasources and dashboards provisioning are in `infra/observability/grafana/`.
### File Locations
- **Prometheus**: `infra/observability/prometheus/prometheus.yml`
- **Promtail**: `infra/observability/promtail/promtail-config.yml`
- **Grafana**: `infra/observability/grafana/`
### Custom Metrics
To expose custom metrics from your service:
```typescript
import { Counter, Histogram } from 'prom-client';
const requestCounter = new Counter({
name: 'http_requests_total',
help: 'Total HTTP requests',
labelNames: ['method', 'route', 'status']
});
const requestDuration = new Histogram({
name: 'http_request_duration_seconds',
help: 'HTTP request duration',
labelNames: ['method', 'route']
});
```
### Custom Dashboards
Create custom dashboards in Grafana:
1. Click **+** → **Dashboard**
2. Add **Panel**
3. Configure query (Prometheus or Loki)
4. Save dashboard
## Color Palette Reference
This guide uses a dark color palette optimized for readability:
| Category | Color Code | Usage |
|----------|------------|-------|
| **Services** | `#2d3748` | Microservices subgraph |
| **Collection** | `#2c5282` | Data collection components |
| **Storage** | `#2f855a` | Database nodes |
| **Visualization** | `#744210` | Grafana/UI components |
| **Service Nodes** | `#4a5568` | Individual services |
| **Collectors** | `#3182ce` | Prometheus/Promtail |
| **Databases** | `#38a169` | Storage systems |
| **Dashboards** | `#d69e2e` | Grafana node |
## Quick Tips
### Mermaid Common Issues
**DO:**
- Use `flowchart LR` for left-to-right flow
- Use `sequenceDiagram` for time-based interactions
- Apply dark colors for better contrast
- Use descriptive node IDs
**DON'T:**
- Mix `graph` and `flowchart` syntax
- Use special characters in node IDs without quotes
- Forget closing brackets for subgraphs
### LogQL Quick Reference
```logql
{label="value"}
{label="value"} |= "search"
{label="value"} |= "error" | json
{label="value"} | logfmt
```
### PromQL Quick Reference
```promql
metric_name
metric_name{label="value"}
rate(metric_name[5m])
sum(metric_name) by (label)
```
### Visual Indicators
- 📊 **Metrics**: Numerical time-series data
- 📝 **Logs**: Text-based event records
- 🎯 **Query**: Search/filter operations
- 🔍 **Explore**: Investigation interface
- 📈 **Dashboard**: Pre-configured visualizations
## Troubleshooting
### Logs Not Appearing in Loki
1. Check Promtail logs: `docker logs promtail`
2. Verify container labels are correct
3. Ensure services are on `microservices-network`
### Metrics Not Appearing in Prometheus
1. Check Prometheus targets: [http://localhost:9090/targets](http://localhost:9090/targets)
2. Verify service exposes `/metrics` endpoint
3. Check Prometheus scrape config
### Grafana Shows "No Data"
1. Verify datasource connection (Configuration → Data Sources)
2. Check time range in query
3. Ensure data exists in Prometheus/Loki

View File

@@ -42,6 +42,92 @@ When something goes wrong, follow this checklist:
* Can you reach the Gateway? `curl http://localhost/health`
* Can you reach the Dashboard? http://localhost:8080
### Troubleshooting Flowchart
```mermaid
flowchart TD
Start([🔍 Issue Detected]) --> CheckStatus{Check Service<br/>Status}
CheckStatus -->|All Running| CheckLogs[📋 Check Logs]
CheckStatus -->|Some Down| IdentifyService[🎯 Identify Failed<br/>Service]
IdentifyService --> ServiceType{Service Type?}
ServiceType -->|Infrastructure| InfraCheck[🔧 Infrastructure<br/>Check]
ServiceType -->|Application| AppCheck[⚙️ Application<br/>Check]
InfraCheck --> DBCheck{Database?}
InfraCheck --> RedisCheck{Redis?}
InfraCheck --> TraefikCheck{Traefik?}
DBCheck -->|Yes| DBSolution[✅ Check DATABASE_URL<br/>✅ Verify Neon connection<br/>✅ Check IP whitelist]
RedisCheck -->|Yes| RedisSolution[✅ Restart Redis<br/>✅ Check port mapping<br/>✅ Verify connection string]
TraefikCheck -->|Yes| TraefikSolution[✅ Check labels<br/>✅ Verify PathPrefix<br/>✅ Check health status]
AppCheck --> ErrorType{Error Type?}
ErrorType -->|Config| ConfigFix[✅ Check .env variables<br/>✅ Run init-project.sh]
ErrorType -->|Prisma| PrismaFix[✅ Check migrations<br/>✅ Regenerate client<br/>✅ Reset database]
ErrorType -->|Auth| AuthFix[✅ Check token expiry<br/>✅ Verify keys<br/>✅ Sync Docker time]
CheckLogs --> LogAnalysis{Log Shows<br/>Error?}
LogAnalysis -->|Yes| ErrorType
LogAnalysis -->|No| ConnCheck[🌐 Check Connectivity]
ConnCheck --> GatewayTest{Gateway<br/>Reachable?}
GatewayTest -->|No| TraefikCheck
GatewayTest -->|Yes| ServiceTest{Service<br/>Reachable?}
ServiceTest -->|No| AppCheck
ServiceTest -->|Yes| Resolved([✨ Issue Resolved])
DBSolution --> Restart[🔄 Restart Services]
RedisSolution --> Restart
TraefikSolution --> Restart
ConfigFix --> Restart
PrismaFix --> Restart
AuthFix --> Restart
Restart --> Verify{Issue<br/>Fixed?}
Verify -->|Yes| Resolved
Verify -->|No| DeepDebug[🛠️ Deep Debugging<br/>Required]
DeepDebug --> ContainerShell[Access Container Shell]
DeepDebug --> PrismaStudio[Use Prisma Studio]
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
```
---
## Infrastructure Issues
@@ -216,3 +302,122 @@ docker-compose down -v
A: Docker consumes RAM.
1. Stop unused services (e.g., `future-service`).
2. Increase Docker resource limits in Docker Desktop settings.
---
## Quick Tips
### 🎯 Debugging Shortcuts
```bash
# Quick health check all services
docker-compose ps | grep -v "Up"
# Tail logs for all services
docker-compose logs -f --tail=50
# Restart specific service without rebuilding
docker-compose restart iam-service
# Rebuild and restart service
docker-compose up -d --build iam-service
# Check resource usage
docker stats --no-stream
# Clean up unused resources
docker system prune -a --volumes
```
### 🔍 Common Error Patterns
| Error Pattern | Likely Cause | Quick Fix |
|--------------|--------------|-----------|
| `ECONNREFUSED` | Service not running | `docker-compose restart <service>` |
| `P1001` | Database unreachable | Check `DATABASE_URL` and internet |
| `P2002` | Duplicate entry | Check unique constraints |
| `401 Unauthorized` | Token expired/invalid | Refresh token or re-login |
| `404 Not Found` | Wrong route/service down | Check Traefik dashboard |
| `502 Bad Gateway` | Service crashed | Check service logs |
| `Config validation error` | Missing env vars | Run `init-project.sh` |
### 📋 Log Analysis Tips
**What to look for in logs:**
- ✅ `Server listening on port XXXX` = Service started successfully
- ⚠️ `Warning:` = Non-critical issues
- ❌ `Error:` = Critical issues requiring attention
- 🔍 `Trace:` = Detailed execution flow
**Useful grep patterns:**
```bash
# Find all errors
docker-compose logs | grep -i error
# Find specific service errors
docker-compose logs iam-service | grep -i "error\|failed"
# Find database connection issues
docker-compose logs | grep -i "prisma\|database\|p1001\|p1003"
# Find auth issues
docker-compose logs | grep -i "unauthorized\|401\|jwt\|token"
```
### 💾 Resource Management
**Recommended Docker Resources:**
- **RAM**: Minimum 4GB, Recommended 8GB
- **CPU**: Minimum 2 cores, Recommended 4 cores
- **Disk**: Minimum 10GB free space
**Check resource usage:**
```bash
# Overall system
docker system df
# Per container
docker stats --no-stream --format "table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}"
```
**Cleanup commands:**
```bash
# Remove stopped containers
docker container prune
# Remove unused images
docker image prune -a
# Remove unused volumes (⚠️ deletes data!)
docker volume prune
# Nuclear option (⚠️ removes everything!)
docker system prune -a --volumes
```
### 🛡️ Best Practices
1. **Always check logs first** before making changes
2. **Use Traefik Dashboard** (http://localhost:8080) to verify routing
3. **Keep `.env.local` updated** with correct credentials
4. **Don't delete volumes** unless you want to lose data
5. **Restart Docker Desktop** if experiencing weird networking issues
6. **Use `docker-compose down && up`** after `.env` changes
7. **Keep services running** you're actively developing
8. **Stop services** you're not using to save resources
### 🎨 Visual Indicators
When reading logs, look for these patterns:
- 🟢 `[INFO]` = Normal operation
- 🟡 `[WARN]` = Something to watch
- 🔴 `[ERROR]` = Needs immediate attention
- 🔵 `[DEBUG]` = Detailed information
- ⚡ `[TRACE]` = Very detailed execution flow
### 🔗 Related Resources
- [Local Deployment Guide](./local-deployment.md) - Setup instructions
- [Development Guide](./development.md) - Development workflow
- [Kubernetes Local Guide](./kubernetes-local.md) - K8s troubleshooting
- [Neon Database Guide](./neon-database.md) - Database management

View File

@@ -40,17 +40,17 @@ graph TD
Deploy --> Ingress
style Code fill:#3498DB,color:#fff
style Test fill:#27AE60,color:#fff
style Build fill:#2980B9,color:#fff
style Registry fill:#8E44AD,color:#fff
style Deploy fill:#E67E22,color:#fff
style Ingress fill:#2980B9,color:#fff
style Service fill:#3498DB,color:#fff
style Pods fill:#27AE60,color:#fff
style Secrets fill:#E67E22,color:#fff
style Neon fill:#8E44AD,color:#fff
style Redis fill:#F39C12,color:#fff
style Code fill:#1e3a5f,color:#e0e7ff
style Test fill:#065f46,color:#d1fae5
style Build fill:#1e40af,color:#dbeafe
style Registry fill:#581c87,color:#f3e8ff
style Deploy fill:#9a3412,color:#fed7aa
style Ingress fill:#312e81,color:#e0e7ff
style Service fill:#1e40af,color:#dbeafe
style Pods fill:#14532d,color:#d1fae5
style Secrets fill:#78350f,color:#fef3c7
style Neon fill:#4c1d95,color:#f3e8ff
style Redis fill:#854d0e,color:#fef3c7
```
---

View File

@@ -1,6 +1,6 @@
# Hướng Dẫn Development
>Hướng dẫn toàn diện về tiêu chuẩn và quy trình đóng góp vào GoodGo Microservices Platform
Hướng dẫn toàn diện về tiêu chuẩn và quy trình đóng góp vào GoodGo Microservices Platform.
## Mục lục
@@ -149,20 +149,20 @@ graph TD
ErrorHandler --> Response[Error Response]
ErrorCheck -->|Không| Success[Success Response]
style Start fill:#27AE60,color:#fff,stroke:#27AE60,stroke-width:2px
style Done fill:#27AE60,color:#fff,stroke:#27AE60,stroke-width:2px
style DTO fill:#3498DB,color:#fff
style Repo fill:#2980B9,color:#fff
style Service fill:#8E44AD,color:#fff
style Controller fill:#E67E22,color:#fff
style Route fill:#2980B9,color:#fff
style Middleware fill:#3498DB,color:#fff
style Test fill:#27AE60,color:#fff
style ErrorCheck fill:#E67E22,color:#fff
style ThrowError fill:#C0392B,color:#fff
style ErrorHandler fill:#C0392B,color:#fff
style Response fill:#7F8C8D,color:#fff
style Success fill:#27AE60,color:#fff
style Start fill:#1e3a2e,color:#4ade80,stroke:#4ade80,stroke-width:3px
style Done fill:#1e3a2e,color:#4ade80,stroke:#4ade80,stroke-width:3px
style DTO fill:#1e293b,color:#60a5fa
style Repo fill:#1e293b,color:#3b82f6
style Service fill:#2e1a47,color:#a78bfa
style Controller fill:#2d1b0e,color:#fb923c
style Route fill:#1e293b,color:#3b82f6
style Middleware fill:#1e293b,color:#60a5fa
style Test fill:#1e3a2e,color:#4ade80
style ErrorCheck fill:#2d1b0e,color:#fb923c
style ThrowError fill:#3f1a1a,color:#f87171
style ErrorHandler fill:#3f1a1a,color:#f87171
style Response fill:#27272a,color:#a1a1aa
style Success fill:#1e3a2e,color:#4ade80
```
### Tạo API Endpoint Mới
@@ -237,24 +237,24 @@ graph TB
AddTests --> RunUnit
Coverage -->|Có| ReadyMerge[Ready to Merge]
style Unit fill:#27AE60,color:#fff
style Integration fill:#3498DB,color:#fff
style E2E fill:#8E44AD,color:#fff
style Code fill:#2980B9,color:#fff
style CheckLint fill:#E67E22,color:#fff
style UnitPass fill:#27AE60,color:#fff
style IntPass fill:#3498DB,color:#fff
style E2EPass fill:#8E44AD,color:#fff
style Coverage fill:#F39C12,color:#fff
style RunUnit fill:#27AE60,color:#fff
style RunIntegration fill:#3498DB,color:#fff
style RunE2E fill:#8E44AD,color:#fff
style ReadyMerge fill:#27AE60,color:#fff,stroke:#27AE60,stroke-width:2px
style FixLint fill:#C0392B,color:#fff
style FixUnit fill:#C0392B,color:#fff
style FixIntegration fill:#C0392B,color:#fff
style FixE2E fill:#C0392B,color:#fff
style AddTests fill:#F39C12,color:#fff
style Unit fill:#1e3a2e,color:#4ade80
style Integration fill:#1e293b,color:#60a5fa
style E2E fill:#2e1a47,color:#a78bfa
style Code fill:#1e293b,color:#3b82f6
style CheckLint fill:#2d1b0e,color:#fb923c
style UnitPass fill:#1e3a2e,color:#4ade80
style IntPass fill:#1e293b,color:#60a5fa
style E2EPass fill:#2e1a47,color:#a78bfa
style Coverage fill:#2d1b0e,color:#fbbf24
style RunUnit fill:#1e3a2e,color:#4ade80
style RunIntegration fill:#1e293b,color:#60a5fa
style RunE2E fill:#2e1a47,color:#a78bfa
style ReadyMerge fill:#1e3a2e,color:#4ade80,stroke:#4ade80,stroke-width:3px
style FixLint fill:#3f1a1a,color:#f87171
style FixUnit fill:#3f1a1a,color:#f87171
style FixIntegration fill:#3f1a1a,color:#f87171
style FixE2E fill:#3f1a1a,color:#f87171
style AddTests fill:#2d1b0e,color:#fbbf24
```
### Unit Tests (`*.test.ts`)

View File

@@ -225,33 +225,37 @@ docker-compose logs traefik
## Kiến Trúc Network
```mermaid
graph TB
Client([Client])
Traefik[Traefik<br/>API Gateway<br/>:80, :8080]
IAM[iam-service<br/>:5001]
Admin[web-admin<br/>:3000]
WebClient[web-client<br/>:3001]
Redis[(Redis<br/>:6379)]
Postgres[(PostgreSQL<br/>Neon)]
Client --> Traefik
Traefik --> IAM
Traefik --> Admin
Traefik --> WebClient
IAM --> Redis
IAM --> Postgres
style Client fill:#1a1a2e,stroke:#4a4e69,stroke-width:2px,color:#fff
style Traefik fill:#0f3460,stroke:#16213e,stroke-width:3px,color:#fff
style IAM fill:#533483,stroke:#301934,stroke-width:2px,color:#fff
style Admin fill:#533483,stroke:#301934,stroke-width:2px,color:#fff
style WebClient fill:#533483,stroke:#301934,stroke-width:2px,color:#fff
style Redis fill:#c9184a,stroke:#590d22,stroke-width:2px,color:#fff
style Postgres fill:#c9184a,stroke:#590d22,stroke-width:2px,color:#fff
```
┌─────────────────────────────────────────────────────────────┐
│ Client │
└───────────────────────────┬─────────────────────────────────┘
┌───────────────┐
│ Traefik │ :80, :8080
│ API Gateway │
└───────┬───────┘
┌───────────────────┼───────────────────┐
│ │ │
▼ ▼ ▼
┌──────────────┐ ┌──────────────┐ ┌──────────────┐
│ iam-service │ │ web-admin │ │ web-client │
│ :5001 │ │ :3000 │ │ :3001 │
└──────┬───────┘ └──────────────┘ └──────────────┘
├─────────────┐
│ │
▼ ▼
┌──────────┐ ┌─────────────┐
│ Redis │ │ PostgreSQL │
│ :6379 │ │ (Neon) │
└──────────┘ └─────────────┘
```
**Chú Giải:**
- 🌐 **Client**: Người dùng/trình duyệt bên ngoài
- 🚪 **Traefik**: API Gateway và router
- 🔧 **Services**: Microservices backend
- 💾 **Storage**: Redis cache và PostgreSQL database
## Tài Liệu Tham Khảo