feat: Bổ sung tài liệu kiến trúc, các mẫu hướng dẫn và phân tích, cùng với hướng dẫn Mermaid song ngữ.

This commit is contained in:
Ho Ngoc Hai
2026-01-07 09:21:19 +07:00
parent 4f48eadea8
commit 7217c48253
26 changed files with 8577 additions and 90 deletions

View File

View File

@@ -0,0 +1,272 @@
# Documentation Audit Matrix
## Summary Statistics
**Total Documentation Files**: 87
- **English**: 43 files
- **Vietnamese**: 44 files
**By Category**:
| Category | EN Files | VI Files | Total | % of Total |
|----------|----------|----------|-------|------------|
| Architecture | 3 | 3 | 6 | 7% |
| Guides | 10 | 10 | 20 | 23% |
| Skills/Patterns | 27 | 0 | 27 | 31% |
| Runbooks | 2 | 2 | 4 | 5% |
| Onboarding | 1 | 1 | 2 | 2% |
**Note**: Skills EN/VI count is currently being verified
---
## Architecture Documentation (6 files)
| File | Has Mermaid? | EN Complete? | VI Complete? | Matches Code? | Priority | Notes |
|------|--------------|--------------|--------------|---------------|----------|-------|
| `en/architecture/system-design.md` | ❓ | ⚠️ | N/A | ❓ | **HIGHEST** | Needs comprehensive system diagram |
| `en/architecture/service-communication.md` | ❓ | ⚠️ | N/A | ❓ | **HIGHEST** | Needs sequence diagrams for inter-service calls |
| `en/architecture/iam-proposal.md` | ❓ | ⚠️ | N/A | ❓ | **HIGHEST** | Needs RBAC/auth flow diagrams |
| `vi/architecture/system-design.md` | ❓ | N/A | ⚠️ | ❓ | **HIGHEST** | Must match EN version |
| `vi/architecture/service-communication.md` | ❓ | N/A | ⚠️ | ❓ | **HIGHEST** | Must match EN version |
| `vi/architecture/iam-proposal.md` | ❓ | N/A | ⚠️ | ❓ | **HIGHEST** | Must match EN version |
**Key Updates Needed**:
1. Add C4 context diagrams for system architecture
2. Add service mesh diagrams showing Traefik routing
3. Add sequence diagrams for authentication/authorization flows
4. Update based on actual `_template` and `iam-service` implementations
5. Add database ERD diagrams
6. Ensure EN/VI parity
---
## Guides Documentation (20 files)
### English Guides (10 files)
| File | Has Mermaid? | Complete? | Matches Code? | Priority | Recent Updates |
|------|--------------|-----------|---------------|----------|----------------|
| `en/guides/getting-started.md` | ❓ | ⚠️ | ❓ | **HIGH** | Needs onboarding workflow diagram |
| `en/guides/local-development.md` | ❓ | ⚠️ | ❓ | **HIGH** | Needs setup flowchart, Docker compose diagram |
| `en/guides/kubernetes-local.md` | ✅ | ✅ | ✅ | **MEDIUM** | **Recently updated** (commit 4f48ead) with workflow diagram ✓ |
| `en/guides/deployment.md` | ❓ | ⚠️ | ❓ | **HIGH** | Needs CI/CD pipeline diagram |
| `en/guides/development.md` | ❓ | ⚠️ | ❓ | **MEDIUM** | Needs development workflow diagram |
| `en/guides/iam-migration.md` | ❓ | ⚠️ | ❌ | **MEDIUM** | Needs migration steps diagram |
| `en/guides/neon-database.md` | ❓ | ⚠️ | ❓ | **MEDIUM** | Needs database setup flowchart |
| `en/guides/observability.md` | ❓ | ⚠️ | ❓ | **MEDIUM** | Needs observability stack diagram |
| `en/guides/troubleshooting.md` | ❓ | ⚠️ | ❓ | **MEDIUM** | Needs decision tree diagrams |
| `en/guides/local-deployment.md` | ❓ | ⚠️ | ❓ | **MEDIUM** | Verify if duplicate of `local-development.md` |
### Vietnamese Guides (10 files)
All VI guides should mirror EN structure with equivalent content.
| File | Status | Priority |
|------|--------|----------|
| `vi/guides/*.md` (all 10) | ❓ Must check parity with EN | **HIGH** |
**Key Updates Needed**:
1. **`getting-started.md`**: Add quick start workflow, prerequisite checklist, setup verification steps
2. **`local-development.md`**: Add Docker Compose architecture diagram, environment variable matrix
3. **`deployment.md`**: Add deployment pipeline flowchart, rollback procedure diagram
4. **`kubernetes-local.md`**: ✅ Already has diagrams, verify accuracy only
5. All guides: Ensure bilingual parity, verify all commands work
---
## Skills/Patterns Documentation (54 files estimated)
### Breakdown by Topic (English only shown, each has VI equivalent)
#### API & Communication (6 files)
| File | Priority | Diagrams Needed? | Code Examples Source |
|------|----------|------------------|----------------------|
| `api-design.md` | **HIGH** | ✅ RESTful API flow, response format | `_template/src/routes/` |
| `api-gateway-advanced.md` | MEDIUM | ✅ Gateway architecture | `infra/traefik/` |
| `api-versioning-strategy.md` | MEDIUM | ✅ Versioning decision tree | N/A |
| `inter-service-communication.md` | MEDIUM | ✅ Service mesh, gRPC vs REST | IAM examples |
| (2 more files) | | | |
#### Data & Database (6 files)
| File | Priority | Diagrams Needed? | Code Examples Source |
|------|----------|------------------|----------------------|
| `database-prisma.md` | **HIGH** | ✅ Prisma workflow, migration process | `_template/prisma/` |
| `caching-patterns.md` | **HIGH** | ✅ Multi-layer cache flow | `iam-service/src/core/cache/` |
| `data-consistency-patterns.md` | MEDIUM | ✅ Saga pattern, event sourcing | N/A |
| `repository-pattern.md` | **HIGH** | ✅ Repository pattern flow | `_template/src/modules/common/` |
| (2 more files) | | | |
#### Security & Auth (4 files)
| File | Priority | Diagrams Needed? | Code Examples Source |
|------|----------|------------------|----------------------|
| `security.md` | **HIGHEST** | ✅ Security layers, JWT flow, zero-trust | `iam-service/src/core/security/` |
| `middleware-patterns.md` | **HIGH** | ✅ Middleware execution order | `_template/src/middlewares/` |
| (2 more files) | | | |
#### Testing (2 files)
| File | Priority | Diagrams Needed? | Code Examples Source |
|------|----------|------------------|----------------------|
| `testing-patterns.md` | **HIGH** | ✅ Testing strategy pyramid | `_template/__tests__/` |
| (1 more file) | | | |
#### DevOps (8 files)
| File | Priority | Diagrams Needed? | Code Examples Source |
|------|----------|------------------|----------------------|
| `deployment-kubernetes.md` | MEDIUM | ✅ K8s architecture | `deployments/*/kubernetes/` |
| `cicd-advanced-patterns.md` | MEDIUM | ✅ CI/CD pipeline | `.github/workflows/` |
| `infrastructure-as-code.md` | MEDIUM | ✅ IaC workflow | N/A |
| `observability-monitoring.md` | MEDIUM | ✅ Observability stack | `_template/src/modules/metrics/` |
| (4 more files) | | | |
#### Other Patterns (6+ files)
| File | Priority | Diagrams Needed? |
|------|----------|------------------|
| `project-rules.md` | **HIGHEST** | ✅ Project structure, workflow decision tree |
| `service-layer-patterns.md` | **HIGH** | ✅ Service pattern flow |
| `error-handling-patterns.md` | **HIGH** | ✅ Error flow diagram |
| `event-driven-architecture.md` | MEDIUM | ✅ Event flow |
| `resilience-patterns.md` | MEDIUM | ✅ Circuit breaker, retry flow |
| `performance-optimization.md` | MEDIUM | ✅ Optimization decision tree |
**Key Updates Needed**:
1. **All skills docs**: Add relevant Mermaid diagrams
2. **Code examples**: Update to use actual code from `_template` and `iam-service`
3. **Bilingual parity**: Ensure EN/VI equivalence
4. **New examples**: Add advanced patterns from `iam-service` where applicable
---
## Runbooks Documentation (4 files)
| File | Has Mermaid? | Complete? | Priority | Notes |
|------|--------------|-----------|----------|-------|
| `en/runbooks/incident-response.md` | ❓ | ⚠️ | **HIGH** | Needs incident response flowchart, escalation matrix |
| `en/runbooks/rollback-procedure.md` | ❓ | ⚠️ | **HIGH** | Needs rollback decision tree, verification checklist |
| `vi/runbooks/incident-response.md` | ❓ | ⚠️ | **HIGH** | Must match EN |
| `vi/runbooks/rollback-procedure.md` | ❓ | ⚠️ | **HIGH** | Must match EN |
**Key Updates Needed**:
1. Add incident severity decision tree
2. Add rollback procedure flowchart
3. Add verification checklist diagrams
4. Ensure operational accuracy (test procedures!)
---
## Onboarding Documentation (2 files)
| File | Has Mermaid? | Complete? | Priority | Notes |
|------|--------------|-----------|----------|-------|
| `en/onboarding/new-developer-guide.md` | ❓ | ⚠️ | **MEDIUM** | Needs onboarding journey timeline, setup workflow |
| `vi/onboarding/new-developer-guide.md` | ❓ | ⚠️ | **MEDIUM** | Must match EN |
**Key Updates Needed**:
1. Add onboarding timeline (Day 1-30)
2. Add setup workflow diagram
3. Add learning path diagram
4. Test guide with new developer!
---
## Gaps Analysis
### Missing Diagrams (Estimated)
Based on initial scan:
- **Architecture docs**: 6 files, need 15+ diagrams total
- **Guides**: 20 files, need 20-30 diagrams total
- **Skills**: 54 files, need 50-80 diagrams total
- **Runbooks**: 4 files, need 8-12 diagrams total
- **Onboarding**: 2 files, need 4-6 diagrams total
**Total diagrams to create**: **~100-150 Mermaid diagrams**
### Outdated Information
**Sources of Truth** for updates:
1. **`_template/`**: 38 TypeScript files
- Module structure (4 modules)
- Basic patterns
- Configuration examples
2. **`iam-service/`**: 176 TypeScript files
- Production patterns (14 modules)
- Advanced features
- Real-world implementations
3. **Recent Git Commits**: 32 feature commits to review
- UI/UX updates (Mood Board, Auth pages)
- IAM enhancements (RBAC, Kubernetes configs)
- Infrastructure updates (Redis, Traefik)
### Coverage Gaps
Missing documentation for:
1. **Event sourcing pattern** (used in `iam-service/src/core/events/`)
2. **Zero-trust architecture** (implemented in `iam-service/src/core/security/`)
3. **Multi-layer caching** (needs detailed doc with flow diagrams)
4. **RBAC advanced patterns** (permission wildcards, temporary assignments)
5. **Compliance framework integration** (GDPR, SOC2 reporting)
---
## Next Steps
### Immediate Actions (Phase 1.3 completion)
1.**Wait for Mermaid diagram count** (command in progress)
2.**Scan for outdated code examples**
- Compare code in docs vs actual source
- Identify deprecated patterns
3.**Create priority matrix**
- High priority: Architecture + Core Skills + Critical Guides
- Medium priority: Remaining Guides + Skills
- Low priority: Nice-to-have enhancements
### Phase 2 Preparation
Create templates for:
- Architecture documentation
- Guide documentation
- Skill/pattern documentation
- Runbook documentation
Create Mermaid diagram library for common patterns:
- System architecture (C4 model)
- Sequence diagrams (authentication flows)
- Flowcharts (decision trees, workflows)
- Data flow diagrams
- Class diagrams (patterns)
---
## Status Codes Legend
-**Complete**: Has diagrams, up-to-date, EN/VI parity
- ⚠️ **Needs Update**: Missing diagrams or outdated
-**Unknown**: Needs verification
-**Major Issues**: Significantly outdated or missing
- N/A: Not applicable
---
## Update Strategy
### High Priority (Phase 3)
1. Architecture docs (6 files) - Foundation for everything
2. Core guides (getting-started, local-development, deployment) - Daily use
3. Core skills (project-rules, api-design, database-prisma, security) - Most referenced
### Medium Priority (Phase 4)
4. Remaining guides (8 files) - Important but less frequently used
5. Remaining skills (20+ files) - Complete coverage
6. Runbooks (4 files) - Operational readiness
### Low Priority (Continuous)
7. Onboarding (2 files) - Nice to have polish
8. Additional enhancements - Based on feedback
---
**Last Updated**: 2026-01-05 (Phase 1 Analysis)
**Completion Estimate**: Phase 1 is 90% complete, waiting for final Mermaid diagram statistics

View File

@@ -0,0 +1,2 @@
4f48ead docs: Nâng cấp hướng dẫn triển khai Kubernetes cục bộ với sơ đồ quy trình, hướng dẫn chi tiết và chú thích song ngữ.
e785d64 docs: Thêm báo cáo trạng thái triển khai xác thực và điều chỉnh hiệu ứng kính trong CSS.

31
analysis/features.txt Normal file
View File

@@ -0,0 +1,31 @@
d8d013e feat: Xóa bỏ file `test.sql` không còn cần thiết.
5c7c6cc feat: Thêm trang Mood Board mới và cập nhật giao diện người dùng, đồng thời loại bỏ các script cũ.
3998bc5 feat: giới thiệu component `AuthCard` để chuẩn hóa giao diện trang xác thực và cập nhật biến thể nút.
ffebc93 feat: triển khai các cải tiến giao diện người dùng và bổ sung tài liệu báo cáo hoàn thiện theme.
26fa062 feat: Cập nhật giao diện xác thực với thiết kế tối giản X.ai, loại bỏ nền vũ trụ và hiệu ứng động, điều chỉnh màu sắc nút và trạng thái focus, đồng thời
d079072 feat: Cải thiện trải nghiệm người dùng trên các trang xác thực bằng cách thêm hiệu ứng kínhmorphism và chức năng hiển thị mật khẩu, đồng thời cập nhật giao diện cho phù hợp với phong cách tối giản.
d678d3a feat: Cập nhật giao diện các trang xác thực với nền vũ trụ và hiệu ứng kínhmorphism, cải thiện trải nghiệm người dùng và thêm chức năng hiển thị mật khẩu cho trường nhập liệu.
14c7839 feat: Thêm component AuthControls chứa bộ chuyển đổi theme và ngôn ngữ vào các trang xác thực.
b00b5ea feat: Tích hợp bộ chuyển đổi chủ đề và ngôn ngữ vào thanh điều hướng, cập nhật hook i18n, và đặt chủ đề tối làm mặc định.
df5545e feat: Thêm các tiện ích an toàn cho khu vực di động, cải thiện cấu trúc footer và cập nhật layout cho trải nghiệm ứng dụng gốc.
d404689 feat: Cải thiện giao diện trang chủ với thành phần Banner thông báo, cập nhật cấu trúc điều hướng và tối ưu hóa màu sắc cho phong cách tối giản.
863e821 feat: Cập nhật các thành phần UI với cấu trúc dựa trên tính năng, thêm các thành phần glassmorphism, và cải thiện cấu hình đường dẫn trong tsconfig.
5a71b11 feat: Thêm các component Popover, Tooltip và refactor Switch sử dụng Radix UI, đồng thời cập nhật biến màu và dependencies.
92f4918 feat: Cải thiện giao diện trang chủ với hiệu ứng lơ lửng, mesh gradient pastel động và cập nhật phong cách các thành phần UI.
403b167 feat: Triển khai nền mesh gradient động và làm mới giao diện người dùng phần hero.
5db698b feat: Thêm thành phần footer, loại bỏ biểu tượng cờ khỏi bộ chuyển đổi ngôn ngữ, và cải thiện an toàn SSR cho ngữ cảnh chủ đề.
b831058 feat: Thêm header điều hướng responsive, bộ chuyển đổi ngôn ngữ, thành phần UI chuyển đổi chủ đề và phím tắt chuyển đổi chủ đề.
7cf4111 feat: Thêm các thành phần UI cho trạng thái tải (loading states), trạng thái rỗng (empty states) và tích hợp tài sản thương hiệu.
c54a9de feat: Vô hiệu hóa tạm thời Redis cache và sử dụng in-memory cache làm fallback.
101c333 feat: Cải thiện cấu hình Redis client với tùy chọn kết nối ổn định hơn, chiến lược thử lại nâng cao và xử lý sự kiện kết nối tốt hơn.
e3cc83b feat: Thêm chuyển hướng từ /auth/login sang /login
a383d87 feat: Cấu hình lại ứng dụng IAM, cập nhật cấu trúc routes, tích hợp RBAC và thêm các bài kiểm tra tích hợp.
ccfb2a7 feat: Thêm định nghĩa schema cho yêu cầu truy cập, đánh giá truy cập, chính sách, báo cáo tuân thủ và phiên vào tài liệu Swagger.
67fef54 feat: Thêm hướng dẫn triển khai dịch vụ lên Kubernetes cục bộ bằng tiếng Việt và tiếng Anh, đồng thời cập nhật tài liệu phát triển hiện có.
300b79e feat: Thêm cấu hình và script triển khai Kubernetes cục bộ cho dịch vụ IAM.
202b998 feat: Thêm cấu hình môi trường cục bộ và hoàn thành các tác vụ tăng cường bảo mật cho IAM service, bao gồm tạo dịch vụ mã hóa.
fcbe176 feat: Tối ưu Dockerfile của `iam-service` bằng cách lọc cài đặt pnpm, tinh chỉnh loại bỏ dev dependencies và thiết lập workspace đúng cách.
c05ce82 feat: Thêm bước generate Prisma Client rõ ràng vào Dockerfile của iam-service.
7154c37 feat: Cải thiện dịch vụ mã hóa AES-256-GCM và tích hợp khóa mã hóa vào cấu hình môi trường để bảo vệ dữ liệu nhạy cảm.
6abea5b feat: Bổ sung nhiều tài liệu quy tắc mới về thiết kế, kiến trúc và phát triển, đồng thời loại bỏ các quy tắc cũ về kiến trúc và đặt tên.
0d48ded feat: Khởi tạo Prisma client, bổ sung các bài kiểm tra đơn vị và tích hợp, đồng thời điều chỉnh cấu hình dịch vụ.

50
analysis/git-history.txt Normal file
View File

@@ -0,0 +1,50 @@
* 4f48ead docs: Nâng cấp hướng dẫn triển khai Kubernetes cục bộ với sơ đồ quy trình, hướng dẫn chi tiết và chú thích song ngữ.
* d8d013e feat: Xóa bỏ file `test.sql` không còn cần thiết.
* 5c7c6cc feat: Thêm trang Mood Board mới và cập nhật giao diện người dùng, đồng thời loại bỏ các script cũ.
* 3998bc5 feat: giới thiệu component `AuthCard` để chuẩn hóa giao diện trang xác thực và cập nhật biến thể nút.
* dfa045e refactor: Cập nhật các thành phần UI để sử dụng các lớp Tailwind CSS ngữ nghĩa cho việc tạo chủ đề tốt hơn và xóa tài liệu thiết kế.
* ffebc93 feat: triển khai các cải tiến giao diện người dùng và bổ sung tài liệu báo cáo hoàn thiện theme.
* e785d64 docs: Thêm báo cáo trạng thái triển khai xác thực và điều chỉnh hiệu ứng kính trong CSS.
* b0df44f refactor: di chuyển các trường nhập liệu sang sử dụng `Controller` của React Hook Form.
* 29de865 refactor: Cập nhật các trường nhập liệu form để sử dụng React Hook Form Controller và sửa lỗi không khớp hydration của nút chuyển đổi chủ đề.
* 62a008e refactor: Xóa bỏ import Card và `watch` không sử dụng từ useForm trong các trang xác thực.
* 686a092 refactor: Tách cấu hình viewport thành một export riêng biệt.
* 26fa062 feat: Cập nhật giao diện xác thực với thiết kế tối giản X.ai, loại bỏ nền vũ trụ và hiệu ứng động, điều chỉnh màu sắc nút và trạng thái focus, đồng thời
* d079072 feat: Cải thiện trải nghiệm người dùng trên các trang xác thực bằng cách thêm hiệu ứng kínhmorphism và chức năng hiển thị mật khẩu, đồng thời cập nhật giao diện cho phù hợp với phong cách tối giản.
* d678d3a feat: Cập nhật giao diện các trang xác thực với nền vũ trụ và hiệu ứng kínhmorphism, cải thiện trải nghiệm người dùng và thêm chức năng hiển thị mật khẩu cho trường nhập liệu.
* 2e26f71 style: Điều chỉnh hiệu ứng glassmorphism và animation để phù hợp với phong cách X.ai minimalist, loại bỏ các animation phức tạp và giảm độ mờ của hiệu ứng glass.
* 14c7839 feat: Thêm component AuthControls chứa bộ chuyển đổi theme và ngôn ngữ vào các trang xác thực.
* b00b5ea feat: Tích hợp bộ chuyển đổi chủ đề và ngôn ngữ vào thanh điều hướng, cập nhật hook i18n, và đặt chủ đề tối làm mặc định.
* d2da321 fix: Ngăn chặn lỗi hydration của i18n bằng cách tái cấu trúc logic phát hiện locale và trì hoãn áp dụng locale phía client.
* 2d783af refactor: Thay thế hook dịch thuật tùy chỉnh bằng hook useTranslations từ next-intl, cập nhật các thành phần liên quan đến dịch thuật và điều hướng sau khi đăng nhập thành công.
* df5545e feat: Thêm các tiện ích an toàn cho khu vực di động, cải thiện cấu trúc footer và cập nhật layout cho trải nghiệm ứng dụng gốc.
* d404689 feat: Cải thiện giao diện trang chủ với thành phần Banner thông báo, cập nhật cấu trúc điều hướng và tối ưu hóa màu sắc cho phong cách tối giản.
* f989a2f chore: Xóa các tệp cấu hình và thành phần không còn sử dụng trong ứng dụng client-example, bao gồm các tệp .eslintrc, .gitignore, .npmrc, và nhiều thành phần UI khác.
* 863e821 feat: Cập nhật các thành phần UI với cấu trúc dựa trên tính năng, thêm các thành phần glassmorphism, và cải thiện cấu hình đường dẫn trong tsconfig.
* 5a71b11 feat: Thêm các component Popover, Tooltip và refactor Switch sử dụng Radix UI, đồng thời cập nhật biến màu và dependencies.
* 92f4918 feat: Cải thiện giao diện trang chủ với hiệu ứng lơ lửng, mesh gradient pastel động và cập nhật phong cách các thành phần UI.
* 403b167 feat: Triển khai nền mesh gradient động và làm mới giao diện người dùng phần hero.
* 5db698b feat: Thêm thành phần footer, loại bỏ biểu tượng cờ khỏi bộ chuyển đổi ngôn ngữ, và cải thiện an toàn SSR cho ngữ cảnh chủ đề.
* b831058 feat: Thêm header điều hướng responsive, bộ chuyển đổi ngôn ngữ, thành phần UI chuyển đổi chủ đề và phím tắt chuyển đổi chủ đề.
* 7cf4111 feat: Thêm các thành phần UI cho trạng thái tải (loading states), trạng thái rỗng (empty states) và tích hợp tài sản thương hiệu.
* c54a9de feat: Vô hiệu hóa tạm thời Redis cache và sử dụng in-memory cache làm fallback.
* 101c333 feat: Cải thiện cấu hình Redis client với tùy chọn kết nối ổn định hơn, chiến lược thử lại nâng cao và xử lý sự kiện kết nối tốt hơn.
* 96dc13c fix: Cấu hình thủ công Traefik và cập nhật phiên bản để khắc phục sự cố Docker provider cục bộ.
* e3cc83b feat: Thêm chuyển hướng từ /auth/login sang /login
* d4f6115 refactor: Cập nhật cấu hình các tuyến đường (routes) của dịch vụ IAM và API xác thực phía client, đồng thời loại bỏ tệp sao lưu RBAC cũ.
* a383d87 feat: Cấu hình lại ứng dụng IAM, cập nhật cấu trúc routes, tích hợp RBAC và thêm các bài kiểm tra tích hợp.
* ccfb2a7 feat: Thêm định nghĩa schema cho yêu cầu truy cập, đánh giá truy cập, chính sách, báo cáo tuân thủ và phiên vào tài liệu Swagger.
* 7e7a7a5 refactor: Modularize IAM service routes into dedicated modules and add home page description
* 76b1c9b refactor: chuẩn hóa xử lý lỗi bằng cách giới thiệu tiện ích `getErrorMessage` và cập nhật kiểu `catch` thành `unknown`.
* 19e5e9b refactor: Cập nhật các import thư viện sang named imports cho `express-rate-limit`, `jsonwebtoken` và `dompurify`.
* 67fef54 feat: Thêm hướng dẫn triển khai dịch vụ lên Kubernetes cục bộ bằng tiếng Việt và tiếng Anh, đồng thời cập nhật tài liệu phát triển hiện có.
* 15a77a6 chore: Điều chỉnh đường dẫn script triển khai cục bộ và cập nhật chính sách kéo ảnh IAM service thành IfNotPresent.
* f5d04e1 chore: Cập nhật trạng thái các tác vụ trong kế hoạch kiểm toán dịch vụ IAM thành `skipped`.
* 300b79e feat: Thêm cấu hình và script triển khai Kubernetes cục bộ cho dịch vụ IAM.
* 202b998 feat: Thêm cấu hình môi trường cục bộ và hoàn thành các tác vụ tăng cường bảo mật cho IAM service, bao gồm tạo dịch vụ mã hóa.
* f315a7a refactor: Replaced dynamic rate limit creation with pre-configured role-based limiters.
* fc33f02 build: Thêm binary targets cho Prisma, chuyển rate limiter sang memory store, và cập nhật Dockerfile để sử dụng pnpm hoisting cùng openssl runtime.
* fcbe176 feat: Tối ưu Dockerfile của `iam-service` bằng cách lọc cài đặt pnpm, tinh chỉnh loại bỏ dev dependencies và thiết lập workspace đúng cách.
* c05ce82 feat: Thêm bước generate Prisma Client rõ ràng vào Dockerfile của iam-service.
* 7154c37 feat: Cải thiện dịch vụ mã hóa AES-256-GCM và tích hợp khóa mã hóa vào cấu hình môi trường để bảo vệ dữ liệu nhạy cảm.
* 9aed3da refactor: Đổi tên các model Prisma `userPermissions`, `userRoles`, `riskAssessment` và bỏ `backupCode` trong IAM service.

View File

@@ -0,0 +1,625 @@
# IAM Service Architecture Analysis
## Overview / Tổng quan
**Service**: `iam-service` - Enterprise-Grade Identity & Access Management
**TypeScript Files**: 176 files
**Status**: Production Ready (95% implementation)
**Last Updated**: Jan 4, 2026
## Module Structure / Cấu trúc Module
### Production Modules (14 modules)
```
src/modules/
├── common/ # Shared utilities, base classes
├── feature/ # Feature flags (inherited from template)
├── health/ # Health check endpoints
├── metrics/ # Prometheus metrics
├── auth/ # Core authentication (login, register, logout)
├── rbac/ # Role-Based Access Control
├── token/ # JWT & Refresh token management
├── session/ # Session management with device tracking
├── mfa/ # Multi-Factor Authentication (TOTP)
├── social/ # Social OAuth (Google, Facebook, GitHub)
├── oidc/ # OpenID Connect (Provider + Client)
├── identity/ # Identity management (users, profiles, orgs)
├── access/ # Access management (requests, reviews, analytics)
└── governance/ # Governance & compliance (reports, policies, risk)
```
### Module Breakdown
#### Core Authentication Modules
##### 1. Auth Module
**Purpose**: Core authentication flows
**Key Features**:
- Email/password registration & login
- Password reset & change
- Bcrypt hashing (cost factor 12)
- JWT token generation
- CSRF protection
**Endpoints**:
```
POST /api/v1/auth/register
POST /api/v1/auth/login
POST /api/v1/auth/logout
POST /api/v1/auth/refresh
POST /api/v1/auth/change-password
GET /api/v1/auth/me
```
##### 2. Token Module
**Purpose**: JWT and refresh token management
**Features**:
- Access tokens (15min lifetime)
- Refresh tokens (7 days lifetime)
- Token rotation with family tracking
- Secure HTTP-only cookies
- Token blacklisting (on logout)
##### 3. Session Module
**Purpose**: User session management
**Features**:
- Device fingerprinting
- IP address tracking
- Location analysis
- Multiple concurrent sessions
- Session listing & termination
**Endpoints**:
```
GET /api/v1/sessions # List user sessions
DELETE /api/v1/sessions/:id # Terminate specific session
DELETE /api/v1/sessions/all # Terminate all sessions
```
##### 4. MFA Module
**Purpose**: Multi-Factor Authentication
**Features**:
- TOTP (Time-based One-Time Password)
- QR code generation
- Backup codes
- Device management
- Recovery procedures
**Endpoints**:
```
POST /api/v1/mfa/totp/enable
POST /api/v1/mfa/totp/verify
POST /api/v1/mfa/totp/validate
POST /api/v1/mfa/totp/disable
GET /api/v1/mfa/devices
```
##### 5. Social Module
**Purpose**: Social OAuth integration
**Supported Providers**:
- Google OAuth 2.0
- Facebook Login
- GitHub OAuth
**Flow**:
```
User → Redirect to Provider → Callback → Create/Link Account → JWT Token
```
**Endpoints**:
```
GET /api/v1/auth/social/google
GET /api/v1/auth/social/facebook
GET /api/v1/auth/social/github
GET /api/v1/auth/social/google/callback
GET /api/v1/auth/social/facebook/callback
GET /api/v1/auth/social/github/callback
```
##### 6. OIDC Module
**Purpose**: OpenID Connect Provider & Client
**Features**:
- OIDC Provider implementation
- OIDC Client for SSO
- Discovery endpoint
- UserInfo endpoint
- Token introspection
#### Authorization Modules
##### 7. RBAC Module
**Purpose**: Role-Based Access Control
**Permission Model**: `resource:action:scope`
**Features**:
- Role management (CRUD)
- Permission management
- User-role assignments (with expiration)
- User-permission overrides (direct permissions)
- Permission caching (5min TTL)
- Group-based permissions
**Key Entities**:
- **Role**: Named collection of permissions (e.g., ADMIN, MANAGER, USER)
- **Permission**: Granular access (e.g., `users:create:org`, `posts:delete:own`)
- **UserRole**: User-role assignment (can expire)
- **UserPermission**: Direct permission grants (override roles)
**Endpoints**:
```
GET /api/v1/rbac/roles
POST /api/v1/rbac/roles
GET /api/v1/rbac/permissions
POST /api/v1/users/:id/roles
DELETE /api/v1/users/:id/roles/:roleId
POST /api/v1/users/:id/permissions
```
**Permission Check Flow**:
```
Request → Check Direct Permissions → Check Role Permissions → Check Group Permissions → Allow/Deny
```
#### Identity Management Modules
##### 8. Identity Module
**Purpose**: User lifecycle & profile management
**Features**:
- User CRUD operations
- Extended user profiles
- Email/phone/document verification
- Multi-tenant organizations
- Groups with hierarchical structure
- Bulk user import/export
- User deactivation/reactivation
**Database Models**:
- `User` - Core user accounts
- `UserProfile` - Extended user information
- `Organization` - Multi-tenant organizations
- `Group` - User groups within orgs
- `GroupMember` - Group membership
- `IdentityVerification` - Verification records
**Endpoints**:
```
GET /api/v1/identity/users
POST /api/v1/identity/users
GET /api/v1/identity/users/:id
PUT /api/v1/identity/users/:id
POST /api/v1/identity/users/:id/deactivate
POST /api/v1/identity/users/:id/reactivate
GET /api/v1/identity/users/:id/profile
PUT /api/v1/identity/users/:id/profile
POST /api/v1/identity/users/:id/avatar
```
#### Access Management Modules
##### 9. Access Module
**Purpose**: Access request workflows & reviews
**Features**:
- Access request workflows with multi-person approval
- Access reviews & certification campaigns
- Access analytics & usage reporting
- Anomaly detection
- Just-In-Time (JIT) access
- Temporary access grants
**Database Models**:
- `AccessRequest` - Access request workflows
- `AccessRequestApprover` - Multi-person approval chains
- `AccessReview` - Access certification campaigns
- `AccessReviewItem` - Individual review items
**Endpoints**:
```
POST /api/v1/access/requests
GET /api/v1/access/requests
POST /api/v1/access/requests/:id/approve
POST /api/v1/access/requests/:id/reject
POST /api/v1/access/reviews
GET /api/v1/access/reviews
POST /api/v1/access/reviews/:id/items/:itemId/review
GET /api/v1/access/analytics/usage
```
##### 10. Governance Module
**Purpose**: Compliance & governance reporting
**Features**:
- GDPR compliance reporting
- SOC2 compliance reporting
- ISO27001 compliance reporting
- HIPAA compliance support
- Policy templates & versioning
- Risk scoring & management
- Audit log analysis
**Database Models**:
- `ComplianceReport` - Compliance reports (GDPR, SOC2, ISO27001, HIPAA)
- `PolicyTemplate` - Reusable policy templates
- `RiskScore` - User risk scoring
**Endpoints**:
```
POST /api/v1/governance/compliance/reports
GET /api/v1/governance/compliance/reports
POST /api/v1/governance/compliance/reports/:id/generate
GET /api/v1/governance/risk/scores
POST /api/v1/governance/risk/calculate
GET /api/v1/governance/policies/templates
```
## Core Services / Core Services
### 1. Multi-Layer Cache Service
**Location**: `src/core/cache/`
**Pattern**: L1 (Memory) → L2 (Redis) → L3 (Database)
**Implementation**:
- **L1 Cache**: NodeCache (in-memory), 60s TTL, 10k keys max
- **L2 Cache**: Redis, 5-15min TTL, distributed
- **L3**: Prisma with connection pooling
**Cached Data**:
| Data Type | L1 TTL | L2 TTL | Use Case |
|-----------|--------|--------|----------|
| User Data | 60s | 15min | Profile, permissions |
| Permissions | 60s | 5min | Authorization checks |
| User Roles | 60s | 5min | Role assignments |
| Token Validation | N/A | Token lifetime | JWT blacklist |
**Cache Invalidation**:
```typescript
// Pattern-based invalidation
await cacheService.invalidatePattern('user:123:*');
// Event-driven invalidation
onUserUpdate invalidateCache('user:${userId}')
onPermissionChange invalidateCache('user:${userId}:permissions')
```
### 2. Audit Service (Event Sourcing)
**Location**: `src/core/events/`
**Purpose**: Complete audit trail for compliance
**Features**:
- Event sourcing for all authentication and authorization events
- 7-year retention for compliance (GDPR, SOC2)
- Correlation ID tracking
- Event replay capability
**Event Types**:
```typescript
enum AuditEventType {
LOGIN_SUCCESS = 'LOGIN_SUCCESS',
LOGIN_FAILURE = 'LOGIN_FAILURE',
LOGOUT = 'LOGOUT',
TOKEN_REFRESH = 'TOKEN_REFRESH',
PASSWORD_CHANGE = 'PASSWORD_CHANGE',
ROLE_ASSIGNED = 'ROLE_ASSIGNED',
PERMISSION_GRANTED = 'PERMISSION_GRANTED',
ACCESS_DENIED = 'ACCESS_DENIED',
SESSION_CREATED = 'SESSION_CREATED',
SESSION_TERMINATED = 'SESSION_TERMINATED',
MFA_ENABLED = 'MFA_ENABLED',
// ... many more
}
```
**Database Model**:
```prisma
model AuthEvent {
id String @id @default(cuid())
eventType String // AuditEventType
userId String?
email String?
ipAddress String?
userAgent String?
success Boolean
metadata Json?
correlationId String?
createdAt DateTime @default(now())
@@index([userId, createdAt])
@@index([eventType, createdAt])
@@index([correlationId])
}
```
### 3. Security Service (Zero-Trust Validator)
**Location**: `src/core/security/`
**Purpose**: Zero-trust security validation
**Features**:
- Device fingerprinting
- IP address analysis
- Location validation
- Behavioral analysis
- Risk-based authentication
- Anomaly detection
**Zero-Trust Checks**:
```
1. Valid JWT token? ✓
2. Token not blacklisted? ✓
3. Session still active? ✓
4. Device fingerprint matches? ✓
5. IP address in allowed range? ✓
6. No suspicious behavior detected? ✓
→ ALLOW REQUEST
```
### 4. Encryption Service
**Location**: `src/core/security/encryption.service.ts`
**Algorithm**: AES-256-GCM
**Purpose**: Encrypt PII at rest
**Features**:
- Symmetric encryption for sensitive data
- IV (Initialization Vector) per encryption
- Authentication tag for integrity
- Key rotation support
**Usage**:
```typescript
// Encrypt sensitive data
const encrypted = encryptionService.encrypt(ssn);
// Store: "iv:tag:ciphertext"
// Decrypt when needed
const ssn = encryptionService.decrypt(encrypted);
```
## Middleware Stack / Stack Middleware
```typescript
// Execution Order (from main.ts)
1. Helmet // Security headers
2. CORS // Cross-origin config
3. Rate Limiting // Dynamic rate limiting (by role)
4. Correlation ID // Request tracing
5. Request Logger // Structured logging
6. Zero-Trust Validator // Security validation
7. Body Parsers // JSON, URL-encoded
8. Cookie Parser // Parse cookies
9. Metrics // Prometheus instrumentation
10. Routes // API routes
11. Not Found Handler // 404 handling
12. Error Handler // Global error handling (LAST)
```
### Dynamic Rate Limiting
**Implementation**: Redis-backed distributed rate limiting
**Limits by Role**:
```typescript
const rateLimitsByRole = {
anonymous: { windowMs: 15 * 60 * 1000, max: 50 }, // 50 req/15min
user: { windowMs: 15 * 60 * 1000, max: 100 }, // 100 req/15min
moderator: { windowMs: 15 * 60 * 1000, max: 300 }, // 300 req/15min
admin: { windowMs: 15 * 60 * 1000, max: 500 }, // 500 req/15min
superadmin: { windowMs: 15 * 60 * 1000, max: 1000 }, // 1000 req/15min
};
```
**Login-Specific Limit**:
```typescript
const loginLimiter = {
windowMs: 15 * 60 * 1000,
max: 5, // 5 login attempts per 15 minutes
message: 'Too many login attempts, please try again later',
};
```
## Database Schema / Schema Database
**Database**: PostgreSQL 14+
**ORM**: Prisma
**Total Models**: 30+
### Core Models
#### Authentication
- `User` - User accounts (email, password, MFA status)
- `Session` - Active sessions (device, IP, location)
- `RefreshToken` - Refresh tokens (with family tracking)
- `AuthEvent` - Audit log (event sourcing)
- `SocialAccount` - Linked OAuth accounts
- `MFADevice` - TOTP and WebAuthn devices
#### Authorization
- `Role` - Named roles (ADMIN, MANAGER, USER)
- `Permission` - Granular permissions (`resource:action:scope`)
- `UserRole` - User-role assignments (with expiration)
- `RolePermission` - Role-permission mappings
- `UserPermission` - Direct user permissions (override roles)
- `Policy` - ABAC policies (JSON Logic conditions)
#### Identity
- `Organization` - Multi-tenant organizations
- `Group` - User groups within organizations
- `GroupMember` - Group membership (with roles)
- `UserProfile` - Extended user information
- `IdentityVerification` - Email/phone/document verification
#### Access Management
- `AccessRequest` - Access request workflows
- `AccessRequestApprover` - Multi-person approval chains
- `AccessReview` - Access certification campaigns
- `AccessReviewItem` - Individual review items
#### Governance
- `ComplianceReport` - GDPR, SOC2, ISO27001, HIPAA reports
- `PolicyTemplate` - Reusable policy templates
- `RiskScore` - User risk scores
## API Surface / Bề mặt API
**Total Endpoints**: 50+
**Base Path**: `/api/v1`
### Endpoint Categories
| Category | Endpoints | Module |
|----------|-----------|--------|
| Authentication | 10+ | auth, token, session |
| Social Auth | 6 | social |
| OIDC | 5+ | oidc |
| MFA | 5 | mfa |
| RBAC | 8 | rbac |
| Identity | 12+ | identity |
| Access | 8+ | access |
| Governance | 6+ | governance |
| Health | 3 | health |
| Metrics | 1 | metrics |
## Security Features / Tính năng Bảo mật
### Defense-in-Depth Layers
1. **Network Layer**:
- HTTPS/TLS enforcement
- CORS configuration
- Rate limiting (distributed)
2. **Application Layer**:
- Helmet (security headers)
- Input validation (Zod)
- SQL injection prevention (Prisma ORM)
- XSS prevention (CSP)
3. **Authentication Layer**:
- Bcrypt (cost factor 12)
- JWT with short lifetime (15min)
- Refresh token rotation
- MFA (TOTP)
- Social OAuth
4. **Authorization Layer**:
- RBAC (role-based)
- ABAC (attribute-based)
- Direct permissions (override roles)
- Permission caching
5. **Data Layer**:
- AES-256-GCM encryption for PII
- Token hashing (SHA-256)
- Password hashing (bcrypt)
6. **Audit Layer**:
- Event sourcing
- Correlation IDs
- 7-year retention
- Compliance reporting
## Performance Optimizations / Tối ưu Hiệu suất
### Caching Strategy
- **Cache Hit Rate**: 80-90% for permissions
- **Response Time**: P95 < 100ms
- **Token Validation**: < 1ms (L1 cache hit)
- **Permission Check**: < 5ms (L2 cache hit)
### Database Optimizations
- Connection pooling (Prisma default: 10)
- Indexed queries (25+ indexes)
- Selective field fetching
- Batch operations where possible
### Redis Optimizations
- Connection pooling
- Pipeline operations
- Pub/Sub for cache invalidation
- Distributed rate limiting
## Observability / Khả năng quan sát
### Metrics (Prometheus)
- HTTP request duration (by endpoint, status)
- HTTP request count
- Active sessions (gauge)
- Cache hit/miss ratio
- Database query duration
- Authentication success/failure rate
- Authorization checks (allow/deny)
### Logging (Winston)
- Structured JSON logs
- Correlation IDs in every log
- Request/response logging
- Error stack traces (dev only)
- Audit event logging
### Tracing (OpenTelemetry + Jaeger)
- HTTP request spans
- Database query spans
- Cache operation spans
- External API call spans
- Authentication flow spans
### Health Checks
- `/health/live` - Liveness (is process running?)
- `/health/ready` - Readiness (can serve traffic? checks DB + Redis)
- `/health` - Full health (with dependency status)
## Production Readiness / Sẵn sàng Production
- ✅ Multi-layer caching (L1/L2/L3)
- ✅ Zero-trust architecture
- ✅ Device fingerprinting
- ✅ Dynamic rate limiting
- ✅ Event sourcing for audit
- ✅ Compliance reporting (GDPR, SOC2, ISO27001, HIPAA)
- ✅ Multi-factor authentication
- ✅ Social OAuth integration
- ✅ OpenID Connect
- ✅ RBAC + ABAC authorization
- ✅ Encryption for PII
- ✅ Comprehensive logging
- ✅ Prometheus metrics
- ✅ Jaeger tracing
- ✅ Health checks (K8s compatible)
- ✅ Docker deployment
- ✅ Kubernetes manifests
- ✅ Graceful shutdown
- ✅ Connection pooling
## Comparison with Template / So sánh với Template
| Feature | Template | IAM Service |
|---------|----------|-------------|
| **Modules** | 4 | 14 |
| **TypeScript Files** | 38 | 176 |
| **Database Models** | 1 (example) | 30+ |
| **API Endpoints** | 5 (example) | 50+ |
| **Authentication** | ❌ | ✅ (7 methods) |
| **Authorization** | ❌ | ✅ (RBAC + ABAC) |
| **Caching** | ❌ | ✅ (3-layer) |
| **Rate Limiting** | ❌ | ✅ (Dynamic by role) |
| **Audit Logging** | Basic | ✅ (Event sourcing) |
| **Security** | Basic (Helmet) | ✅ (Zero-trust) |
| **MFA** | ❌ | ✅ (TOTP) |
| **Social OAuth** | ❌ | ✅ (3 providers) |
| **OIDC** | ❌ | ✅ (Provider + Client) |
| **Compliance** | ❌ | ✅ (4 frameworks) |
| **Encryption** | ❌ | ✅ (AES-256-GCM) |
## Summary / Tóm tắt
`iam-service` is an **enterprise-grade IAM platform** built on top of the `_template` foundation, demonstrating:
- **Complete authentication system** (password, social, OIDC, MFA)
- **Advanced authorization** (RBAC + ABAC + direct permissions)
- **Zero-trust security** (device fingerprinting, behavioral analysis)
- **High performance** (multi-layer caching, 80-90% cache hit rate)
- **Compliance-ready** (GDPR, SOC2, ISO27001, HIPAA reporting)
- **Production-hardened** (95% implementation complete)
It showcases **real-world patterns** for:
- Distributed caching
- Event sourcing
- Zero-trust architecture
- Multi-tenant support
- Access governance
- Compliance automation

View File

@@ -0,0 +1,650 @@
# Pattern Comparison: Template vs IAM Service
## Overview
This document compares implementation patterns between `_template` (baseline microservice) and `iam-service` (production implementation) to guide documentation updates.
## Module Structure Pattern
### Template Pattern (Simple)
```
src/modules/
├── common/ # Base repository, shared types
├── feature/ # Example CRUD module
├── health/ # Health checks
└── metrics/ # Prometheus metrics
```
### IAM Pattern (Production)
```
src/modules/
├── common/ # Base repository, shared types (same)
├── feature/ # Example CRUD module (inherited)
├── health/ # Health checks (same)
├── metrics/ # Prometheus metrics (same)
├── auth/ # + Core authentication
├── rbac/ # + Authorization
├── token/ # + Token management
├── session/ # + Session management
├── mfa/ # + Multi-factor auth
├── social/ # + Social OAuth
├── oidc/ # + OpenID Connect
├── identity/ # + Identity management
├── access/ # + Access workflows
└── governance/ # + Compliance & reporting
```
**Documentation Impact**:
- Template docs should focus on **foundational patterns**
- IAM docs should show **advanced patterns** and **real-world implementation**
---
## Controller Pattern
### Template (Basic)
```typescript
// src/modules/feature/feature.controller.ts
export class FeatureController {
constructor(private service: FeatureService) {}
async create(req: Request, res: Response, next: NextFunction) {
try {
const dto = CreateFeatureDto.parse(req.body);
const result = await this.service.create(dto);
res.status(201).json({ success: true, data: result });
} catch (error) {
next(error);
}
}
}
```
### IAM (Production with Auth)
```typescript
// src/modules/identity/identity.controller.ts
export class IdentityController {
constructor(
private service: IdentityService,
private auditService: AuditService
) {}
@RequireAuth()
@RequirePermission('users', 'create')
@RateLimit('strict')
async create(req: Request, res: Response, next: NextFunction) {
try {
const dto = CreateUserDto.parse(req.body);
const result = await this.service.create(dto);
// Audit logging
await this.auditService.log('USER_CREATED', req.user.id, {
userId: result.id,
correlationId: req.correlationId,
});
res.status(201).json({ success: true, data: result });
} catch (error) {
next(error);
}
}
}
```
**Pattern Differences**:
1. **Decorators**: IAM uses decorators for auth, permissions, rate limiting
2. **Audit Logging**: IAM logs all operations
3. **Dependency Injection**: IAM injects multiple services (Service + AuditService)
**Documentation Impact**:
- Template docs: Show basic controller pattern
- IAM docs: Show auth decorators, audit logging, multi-service injection
---
## Service Pattern
### Template (Simple Business Logic)
```typescript
// src/modules/feature/feature.service.ts
export class FeatureService {
constructor(private repository: FeatureRepository) {}
async create(data: CreateFeatureDto) {
// Business validation
const existing = await this.repository.findByName(data.name);
if (existing) {
throw new ConflictError('Feature already exists');
}
return await this.repository.create(data);
}
}
```
### IAM (with Caching & Complex Logic)
```typescript
// src/modules/rbac/rbac.service.ts
export class RBACService {
constructor(
private repository: RBACRepository,
private cacheService: CacheService,
private auditService: AuditService
) {}
async checkPermission(
userId: string,
resource: string,
action: string
): Promise<boolean> {
// Try cache first (L1 → L2)
const cacheKey = `user:${userId}:permissions`;
const cached = await this.cacheService.get<string[]>(cacheKey);
let permissions: string[];
if (cached) {
permissions = cached;
} else {
// Cache miss - fetch from DB
const userRoles = await this.repository.getUserRoles(userId);
const rolePermissions = await this.repository.getRolePermissions(userRoles);
const directPermissions = await this.repository.getUserPermissions(userId);
permissions = [...rolePermissions, ...directPermissions];
// Cache for 5 minutes
await this.cacheService.set(cacheKey, permissions, 300);
}
// Check permission
const required = `${resource}:${action}`;
const hasPermission = permissions.some(p => this.matchesPermission(p, required));
// Audit log
await this.auditService.log(
hasPermission ? 'ACCESS_GRANTED' : 'ACCESS_DENIED',
userId,
{ resource, action }
);
return hasPermission;
}
private matchesPermission(granted: string, required: string): boolean {
// Handle wildcards: users:*:* matches users:create:org
const grantedParts = granted.split(':');
const requiredParts = required.split(':');
return grantedParts.every((part, i) =>
part === '*' || part === requiredParts[i]
);
}
}
```
**Pattern Differences**:
1. **Caching**: IAM uses multi-layer caching
2. **Complex Logic**: Permission matching with wildcards
3. **Audit Logging**: Every operation logged
4. **Performance**: Cache-first approach for frequently accessed data
**Documentation Impact**:
- Template docs: Simple business logic
- IAM docs: Caching strategies, complex permission logic, audit logging
---
## Repository Pattern
### Template (Basic CRUD)
```typescript
// src/modules/feature/feature.repository.ts
export class FeatureRepository extends BaseRepository<Feature> {
constructor(prisma: PrismaClient) {
super(prisma, 'feature');
}
async findByName(name: string): Promise<Feature | null> {
return this.prisma.feature.findUnique({ where: { name } });
}
}
```
### IAM (with Joins & Complex Queries)
```typescript
// src/modules/rbac/rbac.repository.ts
export class RBACRepository extends BaseRepository<Role> {
constructor(prisma: PrismaClient) {
super(prisma, 'role');
}
async getUserRoles(userId: string): Promise<string[]> {
const userRoles = await this.prisma.userRole.findMany({
where: {
userId,
OR: [
{ expiresAt: null },
{ expiresAt: { gt: new Date() } }
]
},
include: { role: true }
});
return userRoles.map(ur => ur.role.name);
}
async getRolePermissions(roleNames: string[]): Promise<string[]> {
const rolePermissions = await this.prisma.rolePermission.findMany({
where: { role: { name: { in: roleNames } } },
include: { permission: true }
});
return rolePermissions.map(rp => rp.permission.code);
}
async getUserPermissions(userId: string): Promise<string[]> {
const userPermissions = await this.prisma.userPermission.findMany({
where: { userId },
include: { permission: true }
});
return userPermissions.map(up => up.permission.code);
}
}
```
**Pattern Differences**:
1. **Complex Joins**: IAM uses nested includes
2. **Conditional Logic**: Expiration checking
3. **Data Aggregation**: Combining data from multiple sources
**Documentation Impact**:
- Template docs: Basic CRUD with unique lookups
- IAM docs: Complex joins, conditional queries, data aggregation
---
## Middleware Pattern
### Template (Basic)
```typescript
// src/middlewares/logger.middleware.ts
export const loggerMiddleware = (
req: Request,
res: Response,
next: NextFunction
) => {
const start = Date.now();
res.on('finish', () => {
const duration = Date.now() - start;
logger.info('Request completed', {
method: req.method,
url: req.url,
statusCode: res.statusCode,
duration,
});
});
next();
};
```
### IAM (with Correlation IDs & Audit)
```typescript
// src/middlewares/logger.middleware.ts
export const loggerMiddleware = (
req: Request,
res: Response,
next: NextFunction
) => {
const start = Date.now();
const correlationId = req.correlationId || generateCorrelationId();
// Attach to request for downstream use
req.correlationId = correlationId;
res.setHeader('x-correlation-id', correlationId);
res.on('finish', () => {
const duration = Date.now() - start;
logger.info('Request completed', {
correlationId,
method: req.method,
url: req.url,
statusCode: res.statusCode,
duration,
userId: req.user?.id,
ipAddress: req.ip,
userAgent: req.headers['user-agent'],
});
// Audit logging for sensitive endpoints
if (req.url.startsWith('/api/v1/auth') || req.url.startsWith('/api/v1/rbac')) {
auditService.log('API_REQUEST', req.user?.id, {
method: req.method,
url: req.url,
statusCode: res.statusCode,
correlationId,
});
}
});
next();
};
```
**Pattern Differences**:
1. **Correlation IDs**: IAM propagates correlation IDs
2. **Enhanced Context**: User ID, IP, user agent
3. **Audit Integration**: Sensitive endpoints get audit logs
**Documentation Impact**:
- Template docs: Basic request logging
- IAM docs: Distributed tracing, audit integration, correlation IDs
---
## Configuration Pattern
### Template (Simple Zod Validation)
```typescript
// src/config/app.config.ts
import { z } from 'zod';
const envSchema = z.object({
PORT: z.coerce.number().default(5000),
NODE_ENV: z.enum(['development', 'production', 'test']).default('development'),
DATABASE_URL: z.string().url(),
REDIS_URL: z.string().url().optional(),
});
const env = envSchema.parse(process.env);
export const appConfig = {
port: env.PORT,
env: env.NODE_ENV,
database: { url: env.DATABASE_URL },
redis: { url: env.REDIS_URL },
};
```
### IAM (with Nested Configs & Secrets)
```typescript
// src/config/app.config.ts
import { z } from 'zod';
const envSchema = z.object({
// Server
PORT: z.coerce.number().default(3001),
NODE_ENV: z.enum(['development', 'production', 'test']).default('development'),
// Database
DATABASE_URL: z.string().url(),
DATABASE_POOL_SIZE: z.coerce.number().default(10),
// Redis
REDIS_HOST: z.string().default('localhost'),
REDIS_PORT: z.coerce.number().default(6379),
REDIS_PASSWORD: z.string().optional(),
REDIS_DB: z.coerce.number().default(0),
// JWT
JWT_SECRET: z.string().min(32),
JWT_REFRESH_SECRET: z.string().min(32),
JWT_ACCESS_EXPIRY: z.string().default('15m'),
JWT_REFRESH_EXPIRY: z.string().default('7d'),
// Encryption
ENCRYPTION_KEY: z.string().min(32).optional(),
// OAuth
GOOGLE_CLIENT_ID: z.string().optional(),
GOOGLE_CLIENT_SECRET: z.string().optional(),
FACEBOOK_APP_ID: z.string().optional(),
FACEBOOK_APP_SECRET: z.string().optional(),
GITHUB_CLIENT_ID: z.string().optional(),
GITHUB_CLIENT_SECRET: z.string().optional(),
// Feature Flags
MFA_ENABLED: z.coerce.boolean().default(true),
SOCIAL_AUTH_ENABLED: z.coerce.boolean().default(true),
TRACING_ENABLED: z.coerce.boolean().default(false),
});
const env = envSchema.parse(process.env);
export const appConfig = {
server: {
port: env.PORT,
env: env.NODE_ENV,
},
database: {
url: env.DATABASE_URL,
poolSize: env.DATABASE_POOL_SIZE,
},
redis: {
host: env.REDIS_HOST,
port: env.REDIS_PORT,
password: env.REDIS_PASSWORD,
db: env.REDIS_DB,
},
jwt: {
secret: env.JWT_SECRET,
refreshSecret: env.JWT_REFRESH_SECRET,
accessExpiry: env.JWT_ACCESS_EXPIRY,
refreshExpiry: env.JWT_REFRESH_EXPIRY,
},
encryption: {
key: env.ENCRYPTION_KEY,
},
oauth: {
google: {
clientId: env.GOOGLE_CLIENT_ID,
clientSecret: env.GOOGLE_CLIENT_SECRET,
},
facebook: {
appId: env.FACEBOOK_APP_ID,
appSecret: env.FACEBOOK_APP_SECRET,
},
github: {
clientId: env.GITHUB_CLIENT_ID,
clientSecret: env.GITHUB_CLIENT_SECRET,
},
},
features: {
mfa: env.MFA_ENABLED,
socialAuth: env.SOCIAL_AUTH_ENABLED,
tracing: env.TRACING_ENABLED,
},
};
```
**Pattern Differences**:
1. **Nested Configuration**: IAM groups related configs
2. **Secrets Management**: JWT, encryption, OAuth secrets
3. **Feature Flags**: Runtime feature toggles
4. **Complex Validation**: Min length requirements, optional fields
**Documentation Impact**:
-Template docs: Show basic Zod validation
- IAM docs: Show nested configs, secrets management, feature flags
---
## Testing Pattern
### Template (Simple Unit Test)
```typescript
// src/modules/feature/__tests__/feature.service.test.ts
describe('FeatureService', () => {
let service: FeatureService;
let mockRepository: any;
beforeEach(() => {
mockRepository = {
findByName: jest.fn(),
create: jest.fn(),
};
service = new FeatureService(mockRepository);
});
it('should create feature', async () => {
mockRepository.findByName.mockResolvedValue(null);
mockRepository.create.mockResolvedValue({ id: '1', name: 'test' });
const result = await service.create({ name: 'test' });
expect(result).toEqual({ id: '1', name: 'test' });
expect(mockRepository.create).toHaveBeenCalledWith({ name: 'test' });
});
it('should throw conflict error if feature exists', async () => {
mockRepository.findByName.mockResolvedValue({ id: '1', name: 'test' });
await expect(service.create({ name: 'test' }))
.rejects
.toThrow(ConflictError);
});
});
```
### IAM (with Mocking Complete Dependencies)
```typescript
// src/modules/rbac/__tests__/rbac.service.test.ts
describe('RBACService', () => {
let service: RBACService;
let mockRepository: any;
let mockCacheService: any;
let mockAuditService: any;
beforeEach(() => {
mockRepository = {
getUserRoles: jest.fn(),
getRolePermissions: jest.fn(),
getUserPermissions: jest.fn(),
};
mockCacheService = {
get: jest.fn(),
set: jest.fn(),
};
mockAuditService = {
log: jest.fn(),
};
service = new RBACService(
mockRepository,
mockCacheService,
mockAuditService
);
});
describe('checkPermission', () => {
it('should return true if user has permission (cache hit)', async () => {
mockCacheService.get.mockResolvedValue(['users:create:*', 'posts:read:*']);
const result = await service.checkPermission('user1', 'users', 'create');
expect(result).toBe(true);
expect(mockCacheService.get).toHaveBeenCalledWith('user:user1:permissions');
expect(mockRepository.getUserRoles).not.toHaveBeenCalled(); // Cache hit
expect(mockAuditService.log).toHaveBeenCalledWith(
'ACCESS_GRANTED',
'user1',
{ resource: 'users', action: 'create' }
);
});
it('should return false if user lacks permission (cache miss)', async () => {
mockCacheService.get.mockResolvedValue(null); // Cache miss
mockRepository.getUserRoles.mockResolvedValue(['user']);
mockRepository.getRolePermissions.mockResolvedValue(['posts:read:*']);
mockRepository.getUserPermissions.mockResolvedValue([]);
const result = await service.checkPermission('user1', 'users', 'delete');
expect(result).toBe(false);
expect(mockCacheService.set).toHaveBeenCalledWith(
'user:user1:permissions',
['posts:read:*'],
300
);
expect(mockAuditService.log).toHaveBeenCalledWith(
'ACCESS_DENIED',
'user1',
{ resource: 'users', action: 'delete' }
);
});
it('should handle wildcard permissions', async () => {
mockCacheService.get.mockResolvedValue(['users:*:*']);
const result = await service.checkPermission('user1', 'users', 'create');
expect(result).toBe(true);
});
});
});
```
**Pattern Differences**:
1. **Multiple Dependencies**: IAM mocks repository, cache, audit
2. **Cache Behavior**: Tests cache hit and cache miss scenarios
3. **Audit Verification**: Ensures audit logs are created
4. **Complex Logic**: Tests wildcard permission matching
**Documentation Impact**:
- Template docs: Simple mocking, basic test cases
- IAM docs: Complex mocking, cache behavior, audit verification
---
## Summary Table
| Pattern | Template | IAM | Docs to Update |
|---------|----------|-----|----------------|
| **Controller** | Basic try-catch | + Auth decorators, audit | `api-design.md`, `middleware-patterns.md` |
| **Service** | Simple logic | + Caching, complex logic | `service-layer-patterns.md`, `caching-patterns.md` |
| **Repository** | Basic CRUD | + Complex joins, aggregation | `repository-pattern.md`, `database-prisma.md` |
| **Middleware** | Basic logging | + Correlation IDs, audit | `middleware-patterns.md`, `observability-monitoring.md` |
| **Configuration** | Simple Zod | + Nested configs, secrets | `configuration-management.md` |
| **Testing** | Simple mocks | + Multi-dependency mocks | `testing-patterns.md` |
| **Caching** | None | Multi-layer (L1/L2/L3) | `caching-patterns.md` (NEW examples) |
| **Security** | Helmet only | + Zero-trust, encryption | `security.md` (NEW examples) |
| **Authorization** | None | RBAC + ABAC | NEW skill docs needed |
| **Audit Logging** | None | Event sourcing | `observability-monitoring.md` |
---
## Recommended Documentation Updates
### High Priority
1. **Update `caching-patterns.md`** with IAM multi-layer caching
2. **Update `security.md`** with zero-trust, encryption, JWT patterns
3. **Update `service-layer-patterns.md`** with caching integration
4. **Update `middleware-patterns.md`** with correlation IDs, audit
5. **Update `testing-patterns.md`** with complex mocking examples
### Medium Priority
6. **Update `repository-pattern.md`** with complex joins
7. **Update `api-design.md`** with auth middleware patterns
8. **Update `configuration-management.md`** with secrets management
9. **Update `observability-monitoring.md`** with audit logging
### New Content Needed
10. **RBAC patterns** (currently basic in user rules)
11. **Event sourcing** (audit logging implementation)
12. **Zero-trust architecture** (security validation)
---
## Code Example Sources
All code examples in docs should reference:
- **Template**: For foundational patterns
- **IAM Service**: For production patterns
**Example Mapping**:
- `_template/src/modules/feature/feature.service.ts` → Basic service pattern
- `iam-service/src/modules/rbac/rbac.service.ts` → Advanced service with caching
- `iam-service/src/core/cache/multi-layer-cache.ts` → Caching implementation
- `iam-service/src/core/security/zero-trust-validator.ts` → Security patterns

View File

@@ -0,0 +1,235 @@
# Template Architecture Analysis
## Overview / Tổng quan
**Service**: `_template` - Standard Microservice Template
**TypeScript Files**: 38 files
**Last Updated**: Dec 27, 2024
## Module Structure / Cấu trúc Module
### Core Modules (4 modules)
```
src/modules/
├── common/ # Shared utilities, base classes
├── feature/ # Example feature module (for demonstration)
├── health/ # Health check endpoints
└── metrics/ # Prometheus metrics
```
### Module Breakdown
#### 1. Common Module
**Purpose**: Shared utilities and base classes for all modules
**Key Files**:
- `repository.ts` - Base repository pattern with Prisma
- `types.ts` - Shared TypeScript types
#### 2. Feature Module (Example)
**Purpose**: Demonstrates standard module structure
**Key Files**:
- `feature.controller.ts` - Express route handlers
- `feature.service.ts` - Business logic layer
- `feature.repository.ts` - Data access via Prisma
- `feature.dto.ts` - Zod validation schemas
- `feature.module.ts` - Module wiring and router export
- `__tests__/` - Unit and E2E tests
**Pattern**:
```
Controller → Service → Repository → Prisma → PostgreSQL
```
#### 3. Health Module
**Purpose**: Kubernetes liveness/readiness probes
**Endpoints**:
- `GET /health` - Overall health check
- `GET /health/live` - Liveness probe (is process running?)
- `GET /health/ready` - Readiness probe (can serve traffic?)
#### 4. Metrics Module
**Purpose**: Prometheus metrics exposure
**Endpoint**:
- `GET /metrics` - Prometheus format metrics
**Metrics**:
- HTTP request duration (histogram)
- HTTP request count (counter)
- Active requests (gauge)
- Error count (counter)
## Middleware Stack / Stack Middleware
```typescript
// Execution Order (from main.ts)
1. Correlation ID Middleware // Generate/propagate correlation IDs
2. Request Logger Middleware // Log incoming requests
3. Metrics Middleware // Track request metrics
4. Error Handler Middleware // Global error handling (LAST)
```
**Key Middlewares**:
- `correlation.middleware.ts` - Request tracing with x-correlation-id
- `logger.middleware.ts` - Structured logging with Winston
- `metrics.middleware.ts` - Prometheus instrumentation
- `error.middleware.ts` - Centralized error handling
## Configuration / Cấu hình
**Config Files** (with Zod validation):
- `app.config.ts` - App-level config (PORT, NODE_ENV, API_VERSION)
- `database.config.ts` - Prisma database configuration
- `redis.config.ts` - Redis cache configuration
**Environment Variables**:
| Variable | Required | Description |
|----------|----------|-------------|
| `PORT` | No | Server port (default: 5000) |
| `NODE_ENV` | No | Environment (default: development) |
| `DATABASE_URL` | **Yes** | PostgreSQL connection string |
| `REDIS_URL` | No | Redis connection (default: redis://localhost:6379) |
| `SERVICE_NAME` | No | Service identifier |
| `API_VERSION` | No | API version (default: v1) |
## Database Layer / Tầng Database
**ORM**: Prisma
**Database**: PostgreSQL
**Pattern**: Repository Pattern with Base Repository
**Example Model** (from prisma/schema.prisma):
```prisma
model Feature {
id String @id @default(cuid())
name String @unique
description String?
enabled Boolean @default(true)
config Json?
tags String[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@map("features")
}
```
## API Routes / Routes API
**Base Path**: `/api/v1`
**Routing Strategy**:
```typescript
// src/routes/index.ts
/api/v1
/features Feature Module
/health Health Module
/metrics Metrics Module
```
## Testing Strategy / Chiến lược Testing
**Test Structure**:
```
src/
├── modules/
│ └── feature/
│ └── __tests__/
│ ├── feature.service.test.ts # Unit tests
│ └── feature.e2e.test.ts # E2E tests
└── __tests__/
└── setupTests.ts # Test configuration
```
**Testing Stack**:
- **Framework**: Jest
- **E2E**: Supertest
- **Coverage**: 70%+ requirement
## Observability / Khả năng quan sát
### Logging
- **Library**: Winston
- **Format**: Structured JSON
- **Levels**: error, warn, info, debug
- **Context**: Correlation IDs in every log
### Metrics
- **Library**: prom-client (Prometheus)
- **Endpoint**: `/metrics`
- **Types**: Counter, Gauge, Histogram
### Tracing
- **Library**: OpenTelemetry (planned)
- **Backend**: Jaeger (optional)
- **Env Var**: `TRACING_ENABLED`
## Docker Support / Hỗ trợ Docker
**Dockerfile Features**:
- Multi-stage build (builder → runner)
- Non-root user (node:node)
- Production dependencies only
- Health check support
**Image Size**: ~200MB (optimized)
## Key Patterns Demonstrated / Patterns Chính
1. **Controller-Service-Repository Pattern**
- Clear separation of concerns
- Testable layers
2. **Dependency Injection via Constructor**
- Easy mocking for tests
- Clear dependencies
3. **Zod Validation**
- Runtime type safety
- Environment validation
4. **Error Handling**
- Custom error classes
- Global error middleware
5. **Correlation IDs**
- Request tracing
- Distributed debugging
## Security Features / Tính năng Bảo mật
- **Helmet**: HTTP security headers
- **CORS**: Configurable CORS
- **Input Validation**: Zod schemas
- **SQL Injection Prevention**: Prisma ORM (parameterized queries)
## Deployment Ready / Sẵn sàng Deploy
- ✅ Dockerfile with multi-stage build
- ✅ Health check endpoints (K8s compatible)
- ✅ Prometheus metrics
- ✅ Structured logging
- ✅ Graceful shutdown
- ✅ Connection pooling (Prisma)
## Gaps / Điểm còn thiếu
Compared to full production service (iam-service):
- ❌ No caching layer (no Redis integration shown)
- ❌ No authentication middleware
- ❌ No rate limiting
- ❌ No circuit breaker pattern
- ❌ No event sourcing
- ❌ No advanced RBAC
**Note**: These are intentionally omitted to keep template simple. They are demonstrated in `iam-service`.
## Summary / Tóm tắt
`_template` is a **minimal, production-ready microservice template** that demonstrates:
- Clean architecture (Controller-Service-Repository)
- TypeScript best practices
- Testing setup
- Basic observability (logging, metrics, health checks)
- Docker deployment
It serves as a **starting point** for new services, with `iam-service` showing how to expand into a full production service with advanced features.

View File

@@ -1,26 +1,21 @@
# Documentation
# GoodGo Platform Documentation
This directory contains documentation for the GoodGo Microservices Platform, organized by language.
Welcome to the GoodGo Platform documentation. This directory contains comprehensive documentation for the entire platform.
## Structure
## Documentation Structure
```
docs/
├── en/ # English documentation
│ ├── api/
│ ├── architecture/
│ ├── guides/
── onboarding/
│ ├── runbooks/
── skills/ # Cursor AI skills documentation
├── vi/ # Vietnamese documentation (Tiếng Việt)
├── api/
── architecture/
│ ├── guides/
│ ├── onboarding/
│ ├── runbooks/
│ └── skills/ # Tài liệu Cursor AI skills
└── README.md # This file
├── en/ # English documentation
│ ├── templates/ # Documentation templates (EN)
│ ├── architecture/ # System architecture and design
│ ├── guides/ # Step-by-step guides
── skills/ # Development patterns and skills
└── vi/ # Vietnamese documentation
── templates/ # Documentation templates (VI)
├── architecture/ # Kiến trúc hệ thống
├── guides/ # Hướng dẫn từng bước
── skills/ # Patterns và kỹ thuật phát triển
```
## Available Documentation
@@ -60,11 +55,27 @@ See [Skills Index](./en/skills/README.md) for complete list and quick reference.
## Contributing
When adding new documentation:
1. Add the English version to `/en`
2. Add the Vietnamese translation to `/vi`
3. Keep both versions in sync
1. Choose appropriate template from `/en/templates/` or `/vi/templates/`
2. Add English version to `/en` directory
3. Add Vietnamese translation to `/vi` directory
4. Keep both versions in sync
5. Update this README if adding new categories
### Documentation Templates
- **English Templates**: [`docs/en/templates/`](./en/templates/)
- `architecture.md` - Architecture documentation
- `guide.md` - Step-by-step guides
- `skill-pattern.md` - Coding patterns and skills
- `README.md` - Template usage guide
- **Vietnamese Templates**: [`docs/vi/templates/`](./vi/templates/)
- `architecture.md` - Tài liệu kiến trúc
- `guide.md` - Hướng dẫn từng bước
- `skill-pattern.md` - Coding patterns và skills
- `README.md` - Hướng dẫn sử dụng templates
When updating Cursor Skills:
1. Update the skill source file in `.cursor/skills/{skill-name}/SKILL.md`
2. Update the documentation in `docs/en/skills/{skill-name}.md` and `docs/vi/skills/{skill-name}.md`
3. Update the skills index files if needed
1. Update skill source in `.cursor/skills/{skill-name}/SKILL.md`
2. Update documentation in `docs/en/skills/{skill-name}.md` and `docs/vi/skills/{skill-name}.md`
3. Update skills index files if needed

View File

@@ -0,0 +1,337 @@
# Caching Architecture / Kiến trúc Caching
> **EN**: Multi-layer caching strategy for optimal performance
> **VI**: Chiến lược caching nhiều tầng để tối ưu hiệu suất
## Overview Diagram / Sơ đồ Tổng quan
```mermaid
graph TD
Request[API Request] --> L1{L1 Cache<br/>Memory}
L1 -->|Hit| Return1[Return<br/>< 1ms]
L1 -->|Miss| L2{L2 Cache<br/>Redis}
L2 -->|Hit| WarmL1[Warm L1]
WarmL1 --> Return2[Return<br/>< 5ms]
L2 -->|Miss| DB[(Database)]
DB --> StoreL2[Store L2 + L1]
StoreL2 --> Return3[Return<br/>< 50ms]
style L1 fill:#d4edda
style L2 fill:#fff4e1
style DB fill:#f0e1ff
```
## Architecture Description / Mô tả Kiến trúc
### EN: Multi-Layer Caching
GoodGo platform uses 2-layer caching for performance:
**L1 Cache (Memory)**:
- In-memory cache per service instance
- Very fast access (< 1ms)
- Limited capacity (10k keys default)
- Short TTL (60 seconds default, max 5 minutes)
- Not shared across instances
**L2 Cache (Redis)**:
- Shared distributed cache
- Fast access (< 5ms)
- Large capacity
- Longer TTL (configurable, typically 5-15 minutes)
- Shared across all service instances
**Cache Flow**:
```
Request → L1 → L2 → Database
↓ ↓ ↓ ↓
40-50% 80-90% 10-20% Cache miss
hit rate hit rate rate
```
### VI: Caching Nhiều Tầng
Nền tảng GoodGo sử dụng caching 2 tầng để tối ưu hiệu suất:
**L1 Cache (Memory)**:
- In-memory cache trên mỗi service instance
- Truy cập rất nhanh (< 1ms)
- Dung lượng giới hạn (10k keys mặc định)
- TTL ngắn (60 giây mặc định, tối đa 5 phút)
- Không share giữa instances
**L2 Cache (Redis)**:
- Shared distributed cache
- Truy cập nhanh (< 5ms)
- Dung lượng lớn
- TTL dài hơn (configurable, thường 5-15 phút)
- Share giữa tất cả service instances
## Cache Implementation / Triển khai Cache
### Multi-Layer Cache Service
```typescript
// Multi-layer cache implementation
export class MultiLayerCache {
private l1Cache: NodeCache;
private l2Cache: Redis;
constructor() {
// L1: Memory cache
this.l1Cache = new NodeCache({
stdTTL: 60, // 60 seconds default
maxKeys: 10000, // Max 10k keys
checkperiod: 120 // Check for expired keys every 2min
});
// L2: Redis cache
this.l2Cache = new Redis({
host: process.env.REDIS_HOST,
port: parseInt(process.env.REDIS_PORT),
db: 0
});
}
async get<T>(key: string): Promise<T | null> {
// Try L1 first
const l1Value = this.l1Cache.get<T>(key);
if (l1Value) {
logger.debug('L1 cache hit', { key });
return l1Value;
}
// Try L2
const l2Value = await this.l2Cache.get(key);
if (l2Value) {
logger.debug('L2 cache hit', { key });
const parsed = JSON.parse(l2Value) as T;
// Warm L1 cache
this.l1Cache.set(key, parsed);
return parsed;
}
logger.debug('Cache miss', { key });
return null;
}
async set(key: string, value: any, ttl: number = 300): Promise<void> {
// Store in both L1 and L2
this.l1Cache.set(key, value, Math.min(ttl, 300)); // L1 max 5min
await this.l2Cache.setex(key, ttl, JSON.stringify(value));
}
async del(key: string): Promise<void> {
this.l1Cache.del(key);
await this.l2Cache.del(key);
}
async invalidatePattern(pattern: string): Promise<void> {
// L1: Clear all (simple approach)
this.l1Cache.flushAll();
// L2: Delete by pattern
const keys = await this.l2Cache.keys(pattern);
if (keys.length > 0) {
await this.l2Cache.del(...keys);
}
}
}
```
### Cache Key Naming / Quy ước Đặt tên Key
**Pattern**: `{service}:{entity}:{identifier}:{sub-resource}`
**Examples**:
```typescript
// User cache keys
const keys = {
user: (userId: string) => `iam:user:${userId}`,
userPermissions: (userId: string) => `iam:user:${userId}:permissions`,
userRoles: (userId: string) => `iam:user:${userId}:roles`,
session: (sessionId: string) => `iam:session:${sessionId}`,
};
// Usage
const user = await cache.get(keys.user('user_123'));
const permissions = await cache.get(keys.userPermissions('user_123'));
```
## TTL Strategies / Chiến lược TTL
```mermaid
graph LR
subgraph "TTL Tiers"
Short[Short TTL<br/>60-300s<br/>Frequently changing]
Medium[Medium TTL<br/>300-1800s<br/>Moderately changing]
Long[Long TTL<br/>1800-3600s<br/>Rarely changing]
end
Short --> Permissions[User Permissions]
Short --> Sessions[Session Data]
Medium --> UserProfiles[User Profiles]
Medium --> OrgData[Organization Data]
Long --> Config[Static Config]
Long --> RefData[Reference Data]
style Short fill:#f8d7da
style Medium fill:#fff3cd
style Long fill:#d4edda
```
**TTL Guidelines**:
| Data Type | TTL | Reason |
|-----------|-----|--------|
| User permissions | 5 min | Security-sensitive |
| Session data | Varies | Based on session length |
| User profiles | 10 min | Moderate update frequency |
| Organization data | 15 min | Infrequent updates |
| Static config | 30-60 min | Very stable |
| Reference data | 1-2 hours | Almost never changes |
## Cache Invalidation / Vô hiệu hóa Cache
```mermaid
sequenceDiagram
participant API
participant Service
participant Cache
participant DB
API->>Service: Update User
Service->>DB: UPDATE user
DB-->>Service: Success
Service->>Cache: Invalidate user:123
Service->>Cache: Invalidate user:123:permissions
Service->>Cache: Invalidate user:123:roles
Cache-->>Service: Cleared
Service-->>API: Success
Note over Service,Cache: Next request will fetch fresh data
```
**Invalidation Strategies**:
```typescript
// 1. Single key invalidation
async updateUser(userId: string, data: UpdateUserDto): Promise<User> {
const user = await userRepository.update(userId, data);
// Invalidate user cache
await cache.del(cacheKeys.user(userId));
return user;
}
// 2. Pattern-based invalidation
async updateUserRole(userId: string, roleId: string): Promise<void> {
await userRoleRepository.assign(userId, roleId);
// Invalidate all user-related cache
await cache.invalidatePattern(`iam:user:${userId}:*`);
}
// 3. Time-based invalidation (TTL expiry)
// Automatically handled by cache
```
## Cache Warming / Làm ấm Cache
```typescript
// Preload frequently accessed data
async warmCache(): Promise<void> {
logger.info('Starting cache warming');
// Warm user permissions for active users
const activeUsers = await userRepository.findActive({ limit: 1000 });
for (const user of activeUsers) {
const permissions = await rbacService.getUserPermissions(user.id);
await cache.set(
cacheKeys.userPermissions(user.id),
permissions,
300 // 5 minutes
);
}
logger.info('Cache warming completed', { count: activeUsers.length });
}
// Run on service startup
warmCache().catch(err => logger.error('Cache warming failed', { err }));
```
## Performance Metrics / Chỉ số Hiệu suất
**Cache Hit Rates**:
```typescript
// Track cache performance
export class CacheMetrics {
private hits = new Counter({
name: 'cache_hits_total',
help: 'Total cache hits',
labelNames: ['layer', 'key_prefix']
});
private misses = new Counter({
name: 'cache_misses_total',
help: 'Total cache misses',
labelNames: ['layer', 'key_prefix']
});
recordHit(layer: 'l1' | 'l2', key: string): void {
const prefix = key.split(':')[0];
this.hits.inc({ layer, key_prefix: prefix });
}
recordMiss(key: string): void {
const prefix = key.split(':')[0];
this.misses.inc({ layer: 'db', key_prefix: prefix });
}
}
```
**Expected Performance**:
| Metric | L1 Cache | L2 Cache | Database |
|--------|----------|----------|----------|
| Latency | < 1ms | < 5ms | < 50ms |
| Hit Rate | 40-50% | 80-90% | - |
| Capacity | 10k keys | Unlimited | - |
## Best Practices / Best Practices
**DO**:
- ✅ Use cache for frequently accessed data
- ✅ Set appropriate TTLs based on data change frequency
- ✅ Invalidate cache on data updates
- ✅ Use cache key namespacing
- ✅ Monitor cache hit rates
- ✅ Warm cache on startup for critical data
**DON'T**:
- ❌ Cache data that changes very frequently
- ❌ Set TTL too long (stale data risk)
- ❌ Set TTL too short (negates cache benefit)
- ❌ Cache sensitive data without encryption
- ❌ Ignore cache invalidation on updates
- ❌ Use cache as primary data store
## Related Documentation / Tài liệu Liên quan
- [System Design](./system-design.md) - Overall architecture with caching
- [Data Consistency Patterns](./data-consistency-patterns.md) - Cache invalidation patterns
---
**Last Updated**: 2024-01-15
**Authors**: GoodGo Architecture Team

View File

@@ -0,0 +1,725 @@
# Data Consistency Patterns / Patterns Đồng bộ Dữ liệu
> **EN**: Patterns for maintaining data consistency in distributed microservices architecture
> **VI**: Các patterns để duy trì tính nhất quán dữ liệu trong kiến trúc microservices phân tán
## Overview Diagram / Sơ đồ Tổng quan
```mermaid
graph TD
subgraph "Consistency Patterns"
Saga[Saga Pattern<br/>Distributed Transactions]
Outbox[Outbox Pattern<br/>Reliable Events]
Idempotency[Idempotency<br/>Retry Safety]
OptimisticLock[Optimistic Locking<br/>Concurrent Updates]
CQRS[CQRS<br/>Read/Write Separation]
end
Service1[Service A] --> Saga
Service2[Service B] --> Outbox
Service3[Service C] --> Idempotency
Saga --> EventualConsistency[Eventual Consistency]
Outbox --> EventualConsistency
Idempotency --> EventualConsistency
OptimisticLock --> StrongConsistency[Strong Consistency]
CQRS --> EventualConsistency
style Saga fill:#e1f5ff
style Outbox fill:#fff4e1
style Idempotency fill:#f0e1ff
style CQRS fill:#d4edda
```
## Architecture Description / Mô tả Kiến trúc
### EN: Architecture Overview
GoodGo platform uses multiple consistency patterns to handle distributed data:
**Core Challenges**:
- No distributed transactions (2PC too slow)
- Services own their data (database per service)
- Network failures can cause partial completion
- Need to maintain data integrity across services
**Pattern Selection**:
- **Saga**: For multi-service workflows
- **Outbox**: For guaranteed event publishing
- **Idempotency**: For safe retries
- **Optimistic Locking**: For concurrent updates
- **CQRS**: For read/write optimization
### VI: Tổng quan Kiến trúc
Nền tảng GoodGo sử dụng nhiều consistency patterns để xử lý dữ liệu phân tán:
**Thách thức Cốt lõi**:
- Không có distributed transactions (2PC quá chậm)
- Services sở hữu dữ liệu riêng (database per service)
- Network failures có thể gây partial completion
- Cần maintain data integrity giữa các services
**Lựa chọn Pattern**:
- **Saga**: Cho workflows nhiều services
- **Outbox**: Cho event publishing đảm bảo
- **Idempotency**: Cho retries an toàn
- **Optimistic Locking**: Cho concurrent updates
- **CQRS**: Cho tối ưu read/write
## System Context / Bối cảnh Hệ thống
```mermaid
C4Context
title System Context for Data Consistency in GoodGo Platform
Person(user, "User", "End user performing actions")
System_Boundary(goodgo, "GoodGo Microservices") {
System(order_service, "Order Service", "Manages orders with Saga")
System(payment_service, "Payment Service", "Processes payments")
System(inventory_service, "Inventory Service", "Manages stock")
System(saga_orchestrator, "Saga Orchestrator", "Coordinates distributed transactions")
System(outbox_processor, "Outbox Processor", "Publishes events reliably")
}
System_Ext(db_order, "Order DB", "PostgreSQL with Outbox table")
System_Ext(db_payment, "Payment DB", "PostgreSQL with version field")
System_Ext(db_inventory, "Inventory DB", "PostgreSQL")
System_Ext(kafka, "Event Bus", "Kafka - Event streaming")
System_Ext(redis, "Cache", "Redis - Idempotency keys")
Rel(user, order_service, "Places order", "HTTPS")
Rel(order_service, saga_orchestrator, "Starts saga", "Internal")
Rel(saga_orchestrator, payment_service, "Process payment", "HTTP")
Rel(saga_orchestrator, inventory_service, "Reserve stock", "HTTP")
Rel(order_service, db_order, "Writes + Outbox", "SQL")
Rel(payment_service, db_payment, "Updates with version", "SQL")
Rel(inventory_service, db_inventory, "Reads/Writes", "SQL")
Rel(outbox_processor, db_order, "Polls outbox", "SQL")
Rel(outbox_processor, kafka, "Publishes events", "Kafka Protocol")
Rel(order_service, redis, "Checks idempotency key", "Redis Protocol")
UpdateRelStyle(saga_orchestrator, payment_service, $lineColor="red", $textColor="red")
UpdateRelStyle(saga_orchestrator, inventory_service, $lineColor="red", $textColor="red")
```
**EN**: The GoodGo platform uses a database-per-service architecture where each service owns its data. Data consistency across services is achieved through patterns like Saga (for coordinated workflows), Outbox (for reliable event publishing), Idempotency (for safe retries), and Optimistic Locking (for concurrent updates). These patterns enable eventual consistency while maintaining data integrity.
**VI**: Nền tảng GoodGo sử dụng kiến trúc database-per-service nơi mỗi service sở hữu dữ liệu riêng. Tính nhất quán dữ liệu giữa các services đạt được thông qua các patterns như Saga (cho workflows phối hợp), Outbox (cho event publishing đáng tin cậy), Idempotency (cho retries an toàn), và Optimistic Locking (cho concurrent updates). Các patterns này cho phép eventual consistency đồng thời duy trì data integrity.
## Saga Pattern / Pattern Saga
```mermaid
sequenceDiagram
participant Orchestrator
participant OrderService
participant PaymentService
participant InventoryService
Orchestrator->>OrderService: 1. Create Order
OrderService-->>Orchestrator: Order Created
Orchestrator->>PaymentService: 2. Process Payment
PaymentService-->>Orchestrator: Payment Success
Orchestrator->>InventoryService: 3. Reserve Inventory
alt Inventory Reserved
InventoryService-->>Orchestrator: Success
Orchestrator->>Orchestrator: Complete Saga ✓
else Inventory Failed
InventoryService-->>Orchestrator: Failed ✗
Orchestrator->>PaymentService: Compensate: Refund
PaymentService-->>Orchestrator: Refunded
Orchestrator->>OrderService: Compensate: Cancel Order
OrderService-->>Orchestrator: Cancelled
end
```
**EN Description**: Saga manages distributed transactions as sequence of local transactions with compensation.
**VI Mô tả**: Saga quản lý distributed transactions dưới dạng chuỗi local transactions với compensation.
**Implementation**:
```typescript
// Saga orchestrator
class OrderSaga {
async execute(orderData: OrderData): Promise<void> {
const sagaContext = {
orderId: null,
paymentId: null,
inventoryId: null
};
try {
// Step 1: Create order
sagaContext.orderId = await orderService.create(orderData);
// Step 2: Process payment
sagaContext.paymentId = await paymentService.process(orderData.payment);
// Step 3: Reserve inventory
sagaContext.inventoryId = await inventoryService.reserve(orderData.items);
// All success - commit
await this.completeSaga(sagaContext);
} catch (error) {
// Compensate in reverse order
await this.compensate(sagaContext, error);
throw error;
}
}
private async compensate(context: SagaContext, error: Error): Promise<void> {
if (context.inventoryId) {
await inventoryService.release(context.inventoryId);
}
if (context.paymentId) {
await paymentService.refund(context.paymentId);
}
if (context.orderId) {
await orderService.cancel(context.orderId);
}
}
}
```
## Outbox Pattern / Pattern Outbox
```mermaid
sequenceDiagram
participant Service
participant DB as Database
participant OutboxTable as Outbox Table
participant Processor as Outbox Processor
participant Kafka
Service->>DB: Begin Transaction
Service->>DB: Update Business Data
Service->>OutboxTable: Insert Event
Service->>DB: Commit Transaction
loop Every 5 seconds
Processor->>OutboxTable: SELECT unpublished events
OutboxTable-->>Processor: Events
Processor->>Kafka: Publish Events
Kafka-->>Processor: Ack
Processor->>OutboxTable: Mark as published
end
```
**EN**: Guarantees event publishing by storing events in database within same transaction as business data.
**VI**: Đảm bảo event publishing bằng cách lưu events trong database cùng transaction với business data.
**Implementation**:
```typescript
// Store event in outbox
async createUser(userData: CreateUserDto): Promise<User> {
return await prisma.$transaction(async (tx) => {
// Business operation
const user = await tx.user.create({ data: userData });
// Store event in outbox (same transaction)
await tx.outbox.create({
data: {
aggregateId: user.id,
aggregateType: 'User',
eventType: 'user.created.v1',
payload: JSON.stringify(user),
createdAt: new Date()
}
});
return user;
});
}
// Outbox processor (runs periodically)
async processOutbox(): Promise<void> {
const events = await prisma.outbox.findMany({
where: { publishedAt: null },
take: 100
});
for (const event of events) {
try {
await kafkaProducer.send({
topic: event.eventType,
messages: [{ value: event.payload }]
});
await prisma.outbox.update({
where: { id: event.id },
data: { publishedAt: new Date() }
});
} catch (error) {
logger.error('Failed to publish event', { event, error });
}
}
}
```
## Idempotency Pattern / Pattern Idempotency
```mermaid
graph LR
Request1[Request with<br/>Idempotency Key]
Request2[Retry with<br/>Same Key]
Request1 --> Check{Key Exists?}
Check -->|No| Process[Process Request]
Check -->|Yes| Return[Return Cached Result]
Process --> Store[Store Result<br/>with Key]
Store --> Response1[Response]
Request2 --> Check
Return --> Response2[Same Response]
style Check fill:#fff3cd
style Store fill:#d4edda
```
**EN**: Ensures operations can be safely retried without side effects by using idempotency keys.
**VI**: Đảm bảo operations có thể retry an toàn mà không có side effects bằng cách sử dụng idempotency keys.
**Implementation**:
```typescript
// Idempotency middleware
async function idempotentOperation<T>(
key: string,
operation: () => Promise<T>,
ttl: number = 86400 // 24 hours
): Promise<T> {
// Check if already processed
const cached = await redis.get(`idempotency:${key}`);
if (cached) {
return JSON.parse(cached);
}
// Process operation
const result = await operation();
// Store result
await redis.setex(`idempotency:${key}`, ttl, JSON.stringify(result));
return result;
}
// Usage in controller
async createPayment(req: Request, res: Response): Promise<void> {
const idempotencyKey = req.headers['idempotency-key'] as string;
if (!idempotencyKey) {
return res.status(400).json({ error: 'Idempotency-Key header required' });
}
const result = await idempotentOperation(
idempotencyKey,
() => paymentService.process(req.body)
);
res.json({ success: true, data: result });
}
```
## Optimistic Locking / Khóa Lạc quan
```mermaid
sequenceDiagram
participant User1
participant User2
participant Service
participant DB
User1->>Service: Read (version=1)
User2->>Service: Read (version=1)
User1->>Service: Update (version=1)
Service->>DB: UPDATE WHERE version=1
DB-->>Service: Success, version→2
Service-->>User1: Success
User2->>Service: Update (version=1)
Service->>DB: UPDATE WHERE version=1
DB-->>Service: No rows updated
Service-->>User2: Conflict - version mismatch
User2->>Service: Read (version=2)
User2->>Service: Update (version=2)
Service-->>User2: Success
```
**EN**: Prevents lost updates by checking version on update.
**VI**: Ngăn chặn lost updates bằng cách kiểm tra version khi update.
**Implementation**:
```prisma
// Prisma schema
model User {
id String @id @default(cuid())
email String @unique
name String
version Int @default(1) // Version field
}
```
```typescript
// Update with optimistic locking
async updateUser(userId: string, data: UpdateUserDto, currentVersion: number): Promise<User> {
const result = await prisma.user.updateMany({
where: {
id: userId,
version: currentVersion // Check version
},
data: {
...data,
version: { increment: 1 } // Increment version
}
});
if (result.count === 0) {
throw new ConflictError('Version mismatch - data was modified by another user');
}
return await prisma.user.findUnique({ where: { id: userId } });
}
```
## CQRS Pattern
```mermaid
graph LR
subgraph "Write Side"
Command[Command] --> WriteModel[Write Model<br/>Normalized]
WriteModel --> Events[Domain Events]
end
subgraph "Read Side"
Events --> Projection[Event Projection]
Projection --> ReadModel[Read Model<br/>Denormalized]
Query[Query] --> ReadModel
end
WriteModel --> DB1[(Write DB)]
ReadModel --> DB2[(Read DB<br/>Optimized)]
style WriteModel fill:#f0e1ff
style ReadModel fill:#d4edda
```
**EN**: Separates read and write models for optimal performance.
**VI**: Tách biệt read và write models để tối ưu hiệu suất.
## Performance Characteristics / Đặc điểm Hiệu suất
**EN**: Performance metrics and optimization strategies for data consistency patterns.
**VI**: Chỉ số hiệu suất và chiến lược tối ưu cho patterns đồng bộ dữ liệu.
| Pattern / Pattern | Latency Impact / Tác động Độ trễ | Throughput / Thông lượng | Notes / Ghi chú |
|-------------------|----------------------------------|--------------------------|-----------------|
| **Saga Execution / Thực thi Saga** | 500ms - 2s | 100-500 sagas/s | Depends on number of steps and compensation |
| **Outbox Processing / Xử lý Outbox** | < 100ms | 10,000 events/s | Async processing, minimal user impact |
| **Idempotency Check / Kiểm tra Idempotency** | < 10ms | 50,000 checks/s | Redis lookup, very fast |
| **Optimistic Lock Update / Cập nhật Optimistic Lock** | < 50ms | 5,000 updates/s | Single DB operation with version check |
| **CQRS Projection / CQRS Projection** | 100ms - 1s | 1,000 events/s | Event processing to read model |
| **Compensation Execution / Thực thi Compensation** | 200ms - 1s | Varies | Rollback operations in saga |
### Performance Optimization Strategies / Chiến lược Tối ưu Hiệu suất
**Saga Pattern**:
- Minimize number of steps (< 5 steps ideal)
- Parallel execution where possible
- Cache service responses
- Set appropriate timeouts (30s default)
**Outbox Pattern**:
- Batch process outbox events (100-500 per batch)
- Index `publishedAt` column for performance
- Archive processed events periodically
- Use connection pooling for Kafka
**Idempotency**:
- Use Redis for fast key lookups
- Set TTL to 24-48 hours
- Hash long idempotency keys
- Clean expired keys regularly
**Optimistic Locking**:
- Works best for low-contention scenarios
- Implement retry with exponential backoff
- Monitor conflict rates (should be < 5%)
- Consider pessimistic locking if conflicts > 10%
## Security Considerations / Cân nhắc Bảo mật
**EN**: Security measures for protecting data consistency operations.
**VI**: Biện pháp bảo mật để bảo vệ các operations đồng bộ dữ liệu.
### Saga Security / Bảo mật Saga
**Compensation Protection / Bảo vệ Compensation**:
- Validate saga execution permissions at each step
- Encrypt sensitive data in saga context
- Log all saga executions for audit
- Implement timeout to prevent hanging sagas
```typescript
// EN: Secure saga context
// VI: Saga context bảo mật
interface SecureSagaContext {
sagaId: string;
userId: string; // EN: User who initiated / VI: User khởi tạo
permissions: string[]; // EN: Required permissions / VI: Quyền yêu cầu
encryptedData: string; // EN: Encrypted sensitive data / VI: Dữ liệu nhạy cảm đã mã hóa
auditLog: AuditEntry[]; // EN: Audit trail / VI: Audit trail
}
```
### Outbox Security / Bảo mật Outbox
**Event Payload Encryption / Mã hóa Event Payload**:
- Encrypt PII (Personally Identifiable Information) before storing in outbox
- Use AES-256-GCM for event payload encryption
- Decrypt only when publishing to Kafka
- Rotate encryption keys quarterly
**Access Control / Kiểm soát Truy cập**:
- Restrict outbox table access to outbox processor only
- Use database roles and permissions
- Monitor outbox table access patterns
### Idempotency Security / Bảo mật Idempotency
**Key Security / Bảo mật Key**:
- Use cryptographic hashing for idempotency keys (SHA-256)
- Include user context in key generation
- Validate key ownership before processing
- Clear keys on user logout for sensitive operations
```typescript
// EN: Secure idempotency key generation
// VI: Tạo idempotency key bảo mật
function generateIdempotencyKey(
operation: string,
userId: string,
data: any
): string {
const payload = JSON.stringify({ operation, userId, data });
return crypto.createHash('sha256').update(payload).digest('hex');
}
```
### Optimistic Locking Security / Bảo mật Optimistic Lock
**Version Tampering Prevention / Ngăn chặn Giả mạo Version**:
- Validate version field on server-side only
- Never accept version from client directly
- Log version conflicts for security monitoring
- Rate limit update attempts per user
## Deployment / Triển khai
**EN**: How data consistency patterns are deployed and scaled.
**VI**: Cách các patterns đồng bộ dữ liệu được triển khai và mở rộng.
```mermaid
graph TD
subgraph "Production Deployment"
subgraph "Order Service Cluster"
OS1[Order Service\nPod 1]
OS2[Order Service\nPod 2]
OS3[Order Service\nPod 3]
end
subgraph "Saga Orchestrator"
SO1[Saga Orchestrator\nPod 1]
SO2[Saga Orchestrator\nPod 2]
end
subgraph "Outbox Processor"
OP1[Outbox Processor\nPod 1]
OP2[Outbox Processor\nPod 2]
end
OS1 & OS2 & OS3 --> DB[(Order DB\nwith Outbox)]
OS1 & OS2 & OS3 --> Redis[(Redis\nIdempotency Keys)]
SO1 & SO2 --> PS[Payment Service]
SO1 & SO2 --> IS[Inventory Service]
OP1 & OP2 --> DB
OP1 & OP2 --> Kafka[Kafka Cluster\n5 brokers]
end
style SO1 fill:#e1f5ff
style SO2 fill:#e1f5ff
style OP1 fill:#fff4e1
style OP2 fill:#fff4e1
style DB fill:#d4edda
style Kafka fill:#ffe1e1
```
### Deployment Configuration / Cấu hình Triển khai
| Component / Thành phần | Replicas | Resources | HA Strategy |
|------------------------|----------|-----------|-------------|
| **Saga Orchestrator** | 2-3 | 512Mi RAM, 500m CPU | Leader election with etcd |
| **Outbox Processor** | 2-5 | 256Mi RAM, 250m CPU | Distributed lock per event batch |
| **Services with Outbox** | 3+ | Varies | Standard service scaling |
| **Redis (Idempotency)** | 3 nodes | 1Gi RAM each | Redis Cluster with replication |
### Scaling Strategy / Chiến lược Mở rộng
**Saga Orchestrator**:
- Scale based on pending saga count
- Use queue-based load distribution
- Monitor saga execution duration
**Outbox Processor**:
- Scale with database sharding (1 processor per shard)
- Increase batch size before adding replicas
- Monitor outbox table size and age
**Idempotency Store (Redis)**:
- Scale Redis cluster horizontally
- Use consistent hashing for key distribution
- Monitor memory usage (should be < 70%)
## Monitoring & Observability / Giám sát & Khả năng quan sát
**EN**: Monitoring strategies for data consistency patterns.
**VI**: Chiến lược giám sát cho patterns đồng bộ dữ liệu.
### Key Metrics / Chỉ số Chính
**Saga Metrics**:
- `saga_executions_total` - Total saga executions (success/failure)
- `saga_duration_seconds` - Saga execution time histogram
- `saga_compensations_total` - Total compensation executions
- `saga_timeout_total` - Sagas that timed out
- `saga_pending_count` - Sagas currently executing
**Outbox Metrics**:
- `outbox_events_total` - Events written to outbox
- `outbox_published_total` - Events published to Kafka
- `outbox_processing_lag_seconds` - Time from write to publish
- `outbox_table_size` - Outbox table row count
- `outbox_failed_events_total` - Failed event publications
**Idempotency Metrics**:
- `idempotency_checks_total` - Total idempotency checks
- `idempotency_hits_total` - Duplicate requests prevented
- `idempotency_key_ttl_seconds` - Average key TTL
- `idempotency_redis_errors_total` - Redis failures
**Optimistic Lock Metrics**:
- `optimistic_lock_conflicts_total` - Version conflicts detected
- `optimistic_lock_retries_total` - Retry attempts after conflict
- `optimistic_lock_success_rate` - Update success percentage
### Alerts / Cảnh báo
**Critical Alerts**:
```yaml
# Saga timeout rate too high
alert: HighSagaTimeoutRate
expr: rate(saga_timeout_total[5m]) > 0.05
for: 5m
severity: critical
# Outbox processing lag
alert: OutboxProcessingLag
expr: outbox_processing_lag_seconds > 300
for: 10m
severity: critical
# High optimistic lock conflict rate
alert: HighOptimisticLockConflicts
expr: rate(optimistic_lock_conflicts_total[5m]) / rate(optimistic_lock_attempts_total[5m]) > 0.1
for: 5m
severity: warning
```
### Monitoring Dashboard / Dashboard Giám sát
**Grafana Panels**:
1. **Saga Orchestration Overview**:
- Saga execution rate (success/failure)
- Average saga duration
- Compensation rate
- Pending saga count
2. **Outbox Processing Health**:
- Outbox publishing rate
- Processing lag (P95, P99)
- Failed events
- Table size trend
3. **Idempotency Effectiveness**:
- Duplicate prevention rate
- Redis hit rate
- Key distribution
4. **Data Consistency SLA**:
- Overall consistency rate (target: 99.9%)
- Mean time to consistency (MTTC)
- Conflict resolution success rate
### Distributed Tracing / Tracing Phân tán
**Trace Saga Execution**:
```typescript
// EN: Traced saga step
// VI: Saga step được trace
async function executeStepWithTracing(
step: SagaStep,
context: SagaContext
): Promise<void> {
const tracer = trace.getTracer('saga-orchestrator');
const span = tracer.startSpan(`saga.step.${step.name}`, {
attributes: {
'saga.id': context.sagaId,
'saga.step': step.name,
'saga.attempt': context.currentAttempt
}
});
try {
await step.execute(context);
span.setStatus({ code: SpanStatusCode.OK });
} catch (error) {
span.setStatus({ code: SpanStatusCode.ERROR, message: error.message });
span.recordException(error);
throw error;
} finally {
span.end();
}
}
```
## Related Documentation / Tài liệu Liên quan
- [Event-Driven Architecture](./event-driven-architecture.md) - Event sourcing and Kafka
- [System Design](./system-design.md) - Overall architecture
- [Microservices Communication](./microservices-communication.md) - Service communication patterns
- [Resilience Patterns](../skills/resilience-patterns.md) - Circuit breaker, retry for saga steps
- [Caching Patterns](../skills/caching-patterns.md) - Caching for idempotency keys
- [Database Prisma](../skills/database-prisma.md) - Prisma transactions for outbox pattern
---
**Last Updated**: 2026-01-07
**Authors**: GoodGo Architecture Team
**Reviewers**: To be assigned

View File

@@ -0,0 +1,162 @@
# Event-Driven Architecture / Kiến trúc Hướng Sự kiện
> **EN**: Event-driven architecture for asynchronous communication using Apache Kafka
> **VI**: Kiến trúc hướng sự kiện cho giao tiếp bất đồng bộ sử dụng Apache Kafka
## Overview Diagram / Sơ đồ Tổng quan
```mermaid
graph TD
subgraph "Event Producers"
IAM[IAM Service]
Service1[Service A]
end
subgraph "Event Broker"
Kafka[Apache Kafka]
Topics[Topics: user.events, auth.events]
end
subgraph "Event Consumers"
Consumer1[Notification Service]
Consumer2[Audit Service]
end
IAM -->|Publish| Kafka
Service1 -->|Publish| Kafka
Kafka --> Topics
Topics -->|Subscribe| Consumer1
Topics -->|Subscribe| Consumer2
style Kafka fill:#e1f5ff
style Topics fill:#fff4e1
```
## Architecture Description / Mô tả Kiến trúc
### EN: English Section
The GoodGo platform implements Event-Driven Architecture (EDA) for asynchronous communication between microservices.
**Core Principles**:
1. **Event-First Design**: All state changes emit domain events
2. **Loose Coupling**: Services communicate through events
3. **Eventual Consistency**: Accept temporary inconsistency
4. **Event Sourcing**: Store changes as event sequence
5. **CQRS Pattern**: Separate read/write operations
**Technology Stack**:
- Apache Kafka - Event streaming platform
- Schema Registry - Avro schemas for validation
- KafkaJS - Node.js client library
- Event Sourcing - Custom implementation in IAM
### VI: Vietnamese Section
Nền tảng GoodGo triển khai Kiến trúc Hướng Sự kiện (EDA) cho giao tiếp bất đồng bộ giữa microservices.
**Nguyên tắc Cốt lõi**:
1. **Event-First Design**: Mọi thay đổi trạng thái phát ra domain events
2. **Loose Coupling**: Services giao tiếp qua events
3. **Eventual Consistency**: Chấp nhận inconsistency tạm thời
4. **Event Sourcing**: Lưu thay đổi dưới dạng chuỗi event
5. **CQRS Pattern**: Tách biệt read/write operations
**Công nghệ**:
- Apache Kafka - Nền tảng event streaming
- Schema Registry - Avro schemas để validation
- KafkaJS - Thư viện Node.js client
- Event Sourcing - Triển khai tùy chỉnh trong IAM
## Event Flow / Luồng Sự kiện
```mermaid
sequenceDiagram
participant Producer as IAM Service
participant Kafka as Kafka Broker
participant Consumer as Notification Service
Producer->>Kafka: Publish Event (user.created)
Kafka->>Consumer: Deliver Event
Consumer->>Consumer: Process Event
Consumer-->>Kafka: Acknowledge
```
**EN Steps**: Publish → Distribute → Consume → Retry (if failed) → DLQ (after max retries) → Acknowledge
**VI Các Bước**: Publish → Distribute → Consume → Retry (nếu thất bại) → DLQ (sau retry tối đa) → Acknowledge
## Event Structure / Cấu trúc Sự kiện
```typescript
interface BaseEvent {
eventId: string; // UUID
eventType: string; // user.created.v1
eventVersion: string; // 1.0.0
timestamp: string; // ISO 8601
source: string; // iam-service
correlationId?: string; // Request correlation
data: unknown; // Event payload
}
```
**Example**:
```json
{
"eventId": "550e8400-e29b-41d4-a716-446655440000",
"eventType": "user.created.v1",
"timestamp": "2024-01-15T10:30:00Z",
"source": "iam-service",
"data": {
"userId": "user_123",
"email": "user@example.com"
}
}
```
## Kafka Topics / Kafka Topics
```mermaid
graph LR
UserCreated[user.created<br/>Partitions: 3]
AuthLogin[auth.login.success<br/>Partitions: 5]
AuditEvents[audit.events<br/>Partitions: 10]
style UserCreated fill:#e1f5ff
style AuthLogin fill:#fff4e1
style AuditEvents fill:#f8d7da
```
**Naming Convention**: `{domain}.{action}.{version}`
**Examples**:
- `user.created.v1`
- `auth.login.success.v1`
- `audit.event.logged.v1`
## Error Handling / Xử lý Lỗi
```mermaid
graph TD
Event[Event] --> Process[Process]
Process -->|Success| Ack[Acknowledge]
Process -->|Failure| Retry[Retry 3x]
Retry -->|Max Retries| DLQ[Dead Letter Queue]
DLQ --> Alert[Alert Team]
```
**Strategy**:
1. Retry with exponential backoff (100ms → 200ms → 400ms)
2. Max 3 attempts
3. Move to DLQ after max retries
4. Manual review and reprocess
## Related Documentation / Tài liệu Liên quan
- [System Design](./system-design.md) - Overall architecture
- [IAM Architecture](./iam-proposal.md) - Event sourcing implementation
---
**Last Updated**: 2024-01-15
**Authors**: GoodGo Architecture Team

View File

@@ -0,0 +1,383 @@
# Microservices Communication / Giao tiếp Microservices
> **EN**: Communication patterns and protocols for inter-service communication
> **VI**: Các patterns và protocols giao tiếp giữa các services
## Overview Diagram / Sơ đồ Tổng quan
```mermaid
graph TD
Client[Client Apps] --> Gateway[API Gateway<br/>Traefik]
Gateway --> ServiceA[Service A]
Gateway --> ServiceB[Service B]
ServiceA <-->|REST/HTTP| ServiceB
ServiceA -->|Events| Kafka[Kafka Broker]
ServiceB <-.->|Sub| Kafka
ServiceA --> SD[Service Discovery<br/>Docker DNS / K8s DNS]
ServiceB --> SD
style Gateway fill:#e1f5ff
style Kafka fill:#fff4e1
style SD fill:#d4edda
```
## System Context / Bối cảnh Hệ thống
```mermaid
C4Context
title System Context Diagram for GoodGo Microservices Communication
Person(client_web, "Web Client", "Browser/Mobile App")
Person(client_api, "API Consumer", "External API clients")
System_Boundary(goodgo, "GoodGo Platform") {
System(gateway, "API Gateway", "Traefik - Routes requests to services")
System(services, "Microservices", "IAM, User, Order, Product services")
System(kafka, "Event Bus", "Kafka - Async communication")
System(discovery, "Service Discovery", "Docker DNS / K8s DNS")
}
System_Ext(db, "Database", "Neon PostgreSQL")
System_Ext(cache, "Cache", "Redis")
System_Ext(external_api, "External APIs", "Payment, Email, SMS")
Rel(client_web, gateway, "Uses", "HTTPS")
Rel(client_api, gateway, "Calls", "HTTPS/REST")
Rel(gateway, services, "Routes to", "HTTP")
Rel(services, kafka, "Pub/Sub", "Kafka Protocol")
Rel(services, discovery, "Lookup", "DNS")
Rel(services, db, "Reads/Writes", "PostgreSQL")
Rel(services, cache, "Gets/Sets", "Redis Protocol")
Rel(services, external_api, "Integrates", "HTTPS")
```
**EN**: The GoodGo platform uses a microservices architecture where all client requests flow through an API Gateway (Traefik), which routes them to appropriate microservices. Services communicate synchronously via REST/HTTP for request-response patterns and asynchronously via Kafka for event-driven workflows. Service discovery is handled by Docker DNS in local environments and Kubernetes DNS in production.
**VI**: Nền tảng GoodGo sử dụng kiến trúc microservices nơi tất cả client requests đi qua API Gateway (Traefik), được route đến các microservices phù hợp. Các services giao tiếp đồng bộ qua REST/HTTP cho patterns request-response và bất đồng bộ qua Kafka cho workflows event-driven. Service discovery được xử lý bởi Docker DNS trong môi trường local và Kubernetes DNS trong production.
## Communication Protocols / Protocols Giao tiếp
### Protocol Comparison / So sánh Protocols
| Protocol | Latency | Complexity | Use Case |
|----------|---------|------------|----------|
| **REST** | Medium | Low | External APIs, CRUD |
| **gRPC** | Low | High | Internal high-performance |
| **Events** | Async | Medium | Decoupled workflows |
| **GraphQL** | Medium | Medium | Complex data fetching |
### REST/HTTP Pattern
```mermaid
sequenceDiagram
participant Client
participant Gateway as API Gateway
participant ServiceA as Service A
participant ServiceB as Service B
Client->>Gateway: GET /api/v1/users/123
Gateway->>ServiceA: Forward Request
ServiceA->>ServiceB: GET /internal/permissions/123
ServiceB-->>ServiceA: Permissions
ServiceA-->>Gateway: User + Permissions
Gateway-->>Client: JSON Response
```
**EN**: Synchronous request-response using HTTP/REST.
**VI**: Request-response đồng bộ sử dụng HTTP/REST.
**Implementation**:
```typescript
// Service-to-service HTTP client
import axios from 'axios';
export class UserServiceClient {
private client = axios.create({
baseURL: process.env.USER_SERVICE_URL,
timeout: 5000,
headers: {
'x-service-auth': process.env.INTERNAL_API_KEY
}
});
async getUser(userId: string): Promise<User> {
const response = await this.client.get(`/users/${userId}`);
return response.data;
}
}
```
### Event-Driven Pattern
```mermaid
sequenceDiagram
participant ServiceA
participant Kafka
participant ServiceB
participant ServiceC
ServiceA->>Kafka: Publish: user.created
Kafka->>ServiceB: Deliver event
Kafka->>ServiceC: Deliver event
par Parallel Processing
ServiceB->>ServiceB: Send welcome email
ServiceC->>ServiceC: Create user profile
end
```
**EN**: Asynchronous event-based communication via Kafka.
**VI**: Giao tiếp bất đồng bộ dựa trên events qua Kafka.
### Service Discovery / Khám phá Dịch vụ
**Local (Docker Compose)**:
```yaml
# Services discover via Docker DNS
http://service-name:port
http://iam-service:3001
```
**Kubernetes**:
```yaml
# Services discover via K8s DNS
http://service-name.namespace.svc.cluster.local
http://iam-service.default.svc.cluster.local:3001
```
## API Gateway Pattern / Pattern API Gateway
```mermaid
graph LR
Client --> Gateway[API Gateway<br/>Traefik]
subgraph "Gateway Features"
Gateway --> Route[Routing]
Gateway --> LB[Load Balancing]
Gateway --> Auth[Authentication]
Gateway --> Rate[Rate Limiting]
Gateway --> CORS
end
Route --> Service1[Service 1]
Route --> Service2[Service 2]
LB --> Service1A[Instance A]
LB --> Service1B[Instance B]
style Gateway fill:#e1f5ff
```
**EN**: Single entry point for all client requests with routing, auth, rate limiting.
**VI**: Điểm vào duy nhất cho tất cả client requests với routing, auth, rate limiting.
## Performance Characteristics / Đặc điểm Hiệu suất
**EN**: Performance expectations and optimization strategies for inter-service communication.
**VI**: Kỳ vọng hiệu suất và chiến lược tối ưu cho giao tiếp giữa các services.
| Metric / Chỉ số | Target / Mục tiêu | Notes / Ghi chú |
|------------------|-------------------|-----------------|
| **REST API Response Time / Thời gian phản hồi REST API** | < 100ms | P95 for internal service-to-service calls |
| **Event Publishing Latency / Độ trễ publish event** | < 50ms | Time to publish to Kafka |
| **Service Discovery Lookup / Service discovery lookup** | < 10ms | DNS resolution time |
| **Gateway Routing Overhead / Chi phí routing của Gateway** | < 20ms | Additional latency added by Traefik |
| **Throughput / Thông lượng** | 10,000 req/s | Per service instance |
| **Kafka Event Processing / Xử lý Kafka event** | < 500ms | P95 end-to-end event processing |
**Optimization Strategies / Chiến lược Tối ưu**:
- **Connection Pooling**: Reuse HTTP connections between services
- **Circuit Breaker**: Prevent cascading failures with Opossum library
- **Retry with Backoff**: Exponential backoff for transient failures
- **Compression**: Enable gzip for large payloads
- **Caching**: Cache service discovery results and responses
## Security Considerations / Cân nhắc Bảo mật
**EN**: Security measures for protecting inter-service communication.
**VI**: Biện pháp bảo mật để bảo vệ giao tiếp giữa các services.
### Service-to-Service Authentication / Xác thực Service-to-Service
- **Internal API Keys**: Services authenticate using `x-service-auth` header
- **JWT Tokens**: For user context propagation between services
- **Mutual TLS (mTLS)**: Optional for production environments (Kubernetes service mesh)
### Network Security / Bảo mật Mạng
- **Network Policies**: Kubernetes NetworkPolicies restrict service-to-service traffic
- **Service Mesh**: Istio/Linkerd for advanced security policies (optional)
- **Private Networks**: Services communicate within private VPC/cluster network
### Data Protection / Bảo vệ Dữ liệu
- **Encryption in Transit**: TLS 1.2+ for all external communication
- **Event Payload Encryption**: Sensitive data encrypted before publishing to Kafka
- **API Gateway**: Traefik handles SSL termination and request validation
### Security Best Practices / Best Practices Bảo mật
```typescript
// EN: Service client with authentication
// VI: Service client với xác thực
export class SecureServiceClient {
private client = axios.create({
baseURL: process.env.SERVICE_URL,
timeout: 5000,
headers: {
'x-service-auth': process.env.INTERNAL_API_KEY,
'x-correlation-id': generateCorrelationId()
},
httpsAgent: new https.Agent({
rejectUnauthorized: true // EN: Verify SSL certificates / VI: Xác minh SSL certificates
})
});
}
```
## Deployment / Triển khai
**EN**: How microservices communication is deployed and scaled across environments.
**VI**: Cách giao tiếp microservices được triển khai và mở rộng qua các môi trường.
```mermaid
graph TD
subgraph "Production Cluster"
LB[Load Balancer] --> Gateway[API Gateway\n3 replicas]
Gateway --> ServiceA1[Service A\nInstance 1]
Gateway --> ServiceA2[Service A\nInstance 2]
Gateway --> ServiceB1[Service B\nInstance 1]
Gateway --> ServiceB2[Service B\nInstance 2]
ServiceA1 & ServiceA2 --> Kafka[Kafka Cluster\n3 brokers]
ServiceB1 & ServiceB2 --> Kafka
ServiceA1 & ServiceA2 --> DB[(PostgreSQL\nPrimary + Replica)]
ServiceB1 & ServiceB2 --> DB
ServiceA1 & ServiceA2 --> Redis[(Redis Cluster\n3 nodes)]
ServiceB1 & ServiceB2 --> Redis
end
style Gateway fill:#e1f5ff
style Kafka fill:#fff4e1
style DB fill:#d4edda
style Redis fill:#ffe1e1
```
### Deployment Environments / Môi trường Triển khai
| Environment | Gateway | Services | Kafka | Service Discovery |
|-------------|---------|----------|-------|-------------------|
| **Local** | Traefik (Docker) | Single instance per service | Single broker | Docker DNS |
| **Staging** | Traefik (2 replicas) | 2 replicas per service | 3 brokers | Kubernetes DNS |
| **Production** | Traefik (3+ replicas) | 3+ replicas per service | 5+ brokers | Kubernetes DNS + Service Mesh |
### Scaling Strategy / Chiến lược Mở rộng
- **Horizontal Pod Autoscaler (HPA)**: Auto-scale based on CPU/memory
- **Kafka Partitions**: Scale event processing by increasing partitions
- **Load Balancing**: Kubernetes Service load balances across pod replicas
- **Gateway Scaling**: Traefik scales independently from backend services
## Monitoring & Observability / Giám sát & Khả năng quan sát
**EN**: How to monitor and observe microservices communication.
**VI**: Cách giám sát và quan sát giao tiếp microservices.
### Key Metrics / Chỉ số Chính
**Service-to-Service Metrics**:
- `http_request_duration_seconds` - Request latency histogram
- `http_requests_total` - Total requests counter
- `http_request_errors_total` - Failed requests counter
- `service_client_timeout_total` - Timeout counter
**Gateway Metrics**:
- `traefik_service_requests_total` - Requests per service
- `traefik_service_request_duration_seconds` - Routing latency
- `traefik_service_retries_total` - Retry attempts
**Kafka Metrics**:
- `kafka_producer_record_send_total` - Events published
- `kafka_consumer_lag` - Consumer lag
- `kafka_consumer_records_consumed_total` - Events consumed
### Health Checks / Kiểm tra Sức khỏe
**Service Endpoints**:
```typescript
// EN: Liveness - is service running?
// VI: Liveness - service có đang chạy không?
app.get('/health/live', (req, res) => {
res.json({ status: 'ok', timestamp: new Date().toISOString() });
});
// EN: Readiness - can service handle traffic?
// VI: Readiness - service có thể xử lý traffic không?
app.get('/health/ready', async (req, res) => {
const checks = {
database: await checkDatabase(),
redis: await checkRedis(),
kafka: await checkKafka()
};
const healthy = Object.values(checks).every(c => c);
res.status(healthy ? 200 : 503).json({ ready: healthy, checks });
});
```
**Kubernetes Probes**:
```yaml
livenessProbe:
httpGet:
path: /health/live
port: 3000
initialDelaySeconds: 30
periodSeconds: 10
readinessProbe:
httpGet:
path: /health/ready
port: 3000
initialDelaySeconds: 5
periodSeconds: 5
```
### Distributed Tracing / Tracing Phân tán
- **OpenTelemetry**: Instrument all service-to-service calls
- **Jaeger**: Visualize distributed traces
- **Correlation IDs**: Propagate via `x-correlation-id` header for request tracking
### Monitoring Dashboard / Dashboard Giám sát
**Grafana Panels**:
- Service Communication Overview (request rate, latency, errors)
- Gateway Performance (routing time, backend health)
- Event Bus Health (Kafka lag, throughput)
- Service Dependencies (service map from traces)
## Related Documentation
- [System Design](./system-design.md) - Overall architecture
- [Event-Driven Architecture](./event-driven-architecture.md) - Event patterns
- [API Gateway Advanced](../skills/api-gateway-advanced.md) - Gateway patterns
- [Inter-Service Communication](../skills/inter-service-communication.md) - Communication patterns
- [Resilience Patterns](../skills/resilience-patterns.md) - Circuit breaker, retry
---
**Last Updated**: 2026-01-07
**Authors**: GoodGo Architecture Team
**Reviewers**: To be assigned

View File

@@ -0,0 +1,334 @@
# Observability Architecture / Kiến trúc Khả năng Quan sát
> **EN**: Comprehensive observability with metrics, logging, and tracing
> **VI**: Khả năng quan sát toàn diện với metrics, logging và tracing
## Overview Diagram / Sơ đồ Tổng quan
```mermaid
graph TD
subgraph "Services"
Service1[Service A]
Service2[Service B]
end
subgraph "Metrics"
Service1 -->|/metrics| Prom[Prometheus]
Service2 -->|/metrics| Prom
Prom --> Grafana[Grafana<br/>Dashboards]
end
subgraph "Logging"
Service1 -->|JSON Logs| Loki
Service2 -->|JSON Logs| Loki
Loki --> GrafanaLogs[Grafana<br/>Log Explorer]
end
subgraph "Tracing"
Service1 -->|Spans| Jaeger
Service2 -->|Spans| Jaeger
Jaeger --> JaegerUI[Jaeger UI]
end
style Prom fill:#d4edda
style Loki fill:#fff4e1
style Jaeger fill:#e1f5ff
```
## Three Pillars of Observability / Ba Trụ cột
### 1. Metrics (Prometheus + Grafana)
```mermaid
graph LR
Service[Service] -->|Expose /metrics| Prom[Prometheus]
Prom -->|Scrape every 15s| Metrics[Time Series DB]
Metrics --> Grafana[Grafana]
Grafana --> Dashboard1[Request Dashboard]
Grafana --> Dashboard2[Error Dashboard]
Grafana --> Dashboard3[Performance Dashboard]
style Prom fill:#d4edda
style Grafana fill:#e1f5ff
```
**EN**: Numerical measurements over time (requests/sec, latency, errors).
**VI**: Các phép đo số theo thời gian (requests/sec, latency, errors).
**Implementation**:
```typescript
import { Counter, Histogram, Gauge } from 'prom-client';
// HTTP request metrics
export const httpRequestDuration = new Histogram({
name: 'http_request_duration_seconds',
help: 'Duration of HTTP requests in seconds',
labelNames: ['method', 'route', 'status'],
buckets: [0.001, 0.01, 0.05, 0.1, 0.5, 1, 2, 5]
});
export const httpRequestTotal = new Counter({
name: 'http_requests_total',
help: 'Total HTTP requests',
labelNames: ['method', 'route', 'status']
});
export const activeRequests = new Gauge({
name: 'http_requests_active',
help: 'Number of active HTTP requests'
});
// Middleware to track metrics
export function metricsMiddleware(req, res, next) {
const start = Date.now();
activeRequests.inc();
res.on('finish', () => {
const duration = (Date.now() - start) / 1000;
httpRequestDuration.observe(
{ method: req.method, route: req.route?.path || req.path, status: res.statusCode },
duration
);
httpRequestTotal.inc({
method: req.method,
route: req.route?.path || req.path,
status: res.statusCode
});
activeRequests.dec();
});
next();
}
```
### 2. Logging (Winston + Loki)
```mermaid
sequenceDiagram
participant Service
participant Winston as Winston Logger
participant Loki
participant Grafana
Service->>Winston: Log event
Winston->>Winston: Format JSON
Winston->>Winston: Add metadata<br/>(correlation ID, trace ID)
Winston->>Loki: Push logs
Loki->>Loki: Index & store
User->>Grafana: Query logs
Grafana->>Loki: LogQL query
Loki-->>Grafana: Log results
```
**EN**: Structured logging with correlation IDs for request tracing.
**VI**: Structured logging với correlation IDs để tracing requests.
**Implementation**:
```typescript
import winston from 'winston';
export const logger = winston.createLogger({
level: process.env.LOG_LEVEL || 'info',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.errors({ stack: true }),
winston.format.json()
),
defaultMeta: {
service: process.env.SERVICE_NAME || 'unknown-service',
environment: process.env.NODE_ENV || 'development'
},
transports: [
new winston.transports.Console(),
// Loki transport (if configured)
]
});
// Logger middleware
export function loggerMiddleware(req, res, next) {
const correlationId = req.headers['x-correlation-id'] || generateId();
req.correlationId = correlationId;
req.logger = logger.child({ correlationId });
req.logger.info('Incoming request', {
method: req.method,
path: req.path,
ip: req.ip
});
res.on('finish', () => {
req.logger.info('Request completed', {
method: req.method,
path: req.path,
status: res.statusCode,
duration: Date.now() - req.startTime
});
});
next();
}
```
### 3. Tracing (OpenTelemetry + Jaeger)
```mermaid
graph LR
Request[Incoming Request] --> Trace[Create Trace]
Trace --> SpanA[Span: HTTP Request]
SpanA --> SpanB[Span: DB Query]
SpanA --> SpanC[Span: Cache Check]
SpanA --> SpanD[Span: External API]
SpanB --> Jaeger[Jaeger]
SpanC --> Jaeger
SpanD --> Jaeger
Jaeger --> Timeline[Trace Timeline]
style Trace fill:#e1f5ff
style Jaeger fill:#d4edda
```
**EN**: Distributed tracing to track requests across services.
**VI**: Distributed tracing để track requests giữa các services.
**Implementation**:
```typescript
import { trace, SpanStatusCode } from '@opentelemetry/api';
// Create traced function
export function traced<T>(
name: string,
fn: () => Promise<T>
): Promise<T> {
const tracer = trace.getTracer('app');
const span = tracer.startSpan(name);
return fn()
.then(result => {
span.setStatus({ code: SpanStatusCode.OK });
return result;
})
.catch(error => {
span.setStatus({
code: SpanStatusCode.ERROR,
message: error.message
});
span.recordException(error);
throw error;
})
.finally(() => {
span.end();
});
}
// Usage
async getUserWithTracing(userId: string): Promise<User> {
return traced('getUserById', async () => {
return await userRepository.findById(userId);
});
}
```
## Health Checks / Kiểm tra Sức khỏe
```typescript
// Liveness probe - is service running?
app.get('/health/live', (req, res) => {
res.json({ status: 'ok', timestamp: new Date().toISOString() });
});
// Readiness probe - is service ready for traffic?
app.get('/health/ready', async (req, res) => {
const checks = {
database: await checkDatabase(),
redis: await checkRedis(),
disk: await checkDiskSpace()
};
const ready = Object.values(checks).every(check => check === true);
res.status(ready ? 200 : 503).json({
ready,
checks,
timestamp: new Date().toISOString()
});
});
async function checkDatabase(): Promise<boolean> {
try {
await prisma.$queryRaw`SELECT 1`;
return true;
} catch {
return false;
}
}
```
## Alerting Rules / Quy tắc Cảnh báo
```yaml
# Prometheus alerting rules
groups:
- name: service_alerts
interval: 30s
rules:
# High error rate
- alert: HighErrorRate
expr: |
rate(http_requests_total{status=~"5.."}[5m]) > 0.05
for: 2m
labels:
severity: warning
annotations:
summary: "High error rate detected"
description: "Error rate is {{ $value }} (> 5%)"
# High latency
- alert: HighLatency
expr: |
histogram_quantile(0.95, http_request_duration_seconds_bucket) > 1
for: 5m
labels:
severity: warning
annotations:
summary: "High latency detected"
description: "P95 latency is {{ $value }}s"
# Service down
- alert: ServiceDown
expr: up == 0
for: 1m
labels:
severity: critical
annotations:
summary: "Service is down"
```
## Performance Targets / Mục tiêu Hiệu suất
| Metric | Target | Alert Threshold |
|--------|--------|-----------------|
| Response Time (P95) | < 200ms | > 500ms |
| Response Time (P99) | < 500ms | > 1s |
| Error Rate | < 1% | > 5% |
| Availability | > 99.9% | < 99% |
| Cache Hit Rate | > 80% | < 50% |
## Related Documentation / Tài liệu Liên quan
- [System Design](./system-design.md) - Overall architecture
- [Caching Architecture](./caching-architecture.md) - Cache metrics
---
**Last Updated**: 2024-01-15
**Authors**: GoodGo Architecture Team

View File

@@ -0,0 +1,347 @@
# Security Architecture / Kiến trúc Bảo mật
> **EN**: Comprehensive security architecture for GoodGo platform with zero-trust model, RBAC, and compliance
> **VI**: Kiến trúc bảo mật toàn diện cho nền tảng GoodGo với mô hình zero-trust, RBAC và compliance
## Overview Diagram / Sơ đồ Tổng quan
```mermaid
graph TD
Request[Client Request] --> TLS[TLS/HTTPS Layer]
TLS --> RateLimit[Rate Limiting]
RateLimit --> JWT[JWT Validation]
JWT --> RBAC[RBAC Authorization]
RBAC --> ZeroTrust[Zero-Trust Checks]
ZeroTrust --> Service[Service Logic]
Service --> Encrypt[Data Encryption<br/>AES-256-GCM]
Encrypt --> DB[(Encrypted Data)]
Service --> Audit[Audit Logging]
Audit --> AuditDB[(Audit Trail<br/>7-year retention)]
style TLS fill:#d4edda
style JWT fill:#e1f5ff
style Encrypt fill:#f8d7da
style Audit fill:#fff4e1
```
## Architecture Description / Mô tả Kiến trúc
### EN: English Section
The GoodGo Security Architecture implements defense-in-depth with multiple security layers:
**Security Principles**:
1. **Zero Trust**: Never trust, always verify
2. **Least Privilege**: Minimum required permissions
3. **Defense in Depth**: Multiple security layers
4. **Audit Everything**: Complete audit trail
5. **Encryption**: Data encrypted at rest and in transit
**Key Components**:
- JWT Authentication (15min access, 7d refresh)
- RBAC + ABAC Authorization
- Zero-Trust Device Validation
- AES-256-GCM Encryption
- Event Sourcing for Audit Trail
- Compliance (GDPR, SOC2, ISO27001, HIPAA)
### VI: Vietnamese Section
Kiến trúc Bảo mật GoodGo triển khai defense-in-depth với nhiều tầng bảo mật:
**Nguyên tắc Bảo mật**:
1. **Zero Trust**: Không bao giờ tin tưởng, luôn xác minh
2. **Least Privilege**: Quyền tối thiểu cần thiết
3. **Defense in Depth**: Nhiều tầng bảo mật
4. **Audit Everything**: Audit trail hoàn chỉnh
5. **Encryption**: Mã hóa dữ liệu at rest và in transit
**Thành phần Chính**:
- JWT Authentication (15min access, 7 ngày refresh)
- RBAC + ABAC Authorization
- Zero-Trust Device Validation
- AES-256-GCM Encryption
- Event Sourcing cho Audit Trail
- Compliance (GDPR, SOC2, ISO27001, HIPAA)
## Authentication Flow / Luồng Xác thực
```mermaid
sequenceDiagram
participant Client
participant API as API Gateway
participant IAM as IAM Service
participant DB as Database
participant Cache as Redis
Client->>API: Login Request<br/>(email + password)
API->>IAM: Forward Request
IAM->>DB: Verify Credentials
DB-->>IAM: User + Hash
IAM->>IAM: bcrypt.compare()<br/>(cost 12)
alt Valid Credentials
IAM->>IAM: Generate Tokens<br/>(Access + Refresh)
IAM->>DB: Store Refresh Token<br/>(hashed SHA-256)
IAM->>Cache: Cache Permissions<br/>(5min TTL)
IAM-->>API: Tokens + User
API-->>Client: Set httpOnly Cookies
else Invalid
IAM-->>Client: 401 Unauthorized
end
```
**EN: Authentication Details**:
**1. Password Hashing**:
- Algorithm: bcrypt with cost factor 12
- Never store plaintext passwords
- Minimum password: 8 chars with complexity rules
**2. JWT Tokens**:
- Access Token: 15 minutes expiry
- Refresh Token: 7 days expiry
- Algorithm: RS256 (asymmetric signing)
- Payload: userId, roles, permissions
**3. Token Storage**:
- Access: httpOnly cookie (secure, sameSite)
- Refresh: Database SHA-256 hash
- Rotation: New refresh token on each use
**4. MFA Support**:
- TOTP (Time-based One-Time Password)
- Backup codes (10 single-use)
- Recovery email verification
**VI: Chi tiết Xác thực**:
**1. Password Hashing**:
- Thuật toán: bcrypt với cost factor 12
- Không bao giờ lưu plaintext passwords
- Password tối thiểu: 8 ký tự với quy tắc phức tạp
**2. JWT Tokens**:
- Access Token: 15 phút expiry
- Refresh Token: 7 ngày expiry
- Thuật toán: RS256 (asymmetric signing)
- Payload: userId, roles, permissions
**3. Token Storage**:
- Access: httpOnly cookie (secure, sameSite)
- Refresh: Database SHA-256 hash
- Rotation: Refresh token mới mỗi lần sử dụng
**4 MFA Support**:
- TOTP (Time-based One-Time Password)
- Backup codes (10 single-use)
- Recovery email verification
## Authorization Model / Mô hình Phân quyền
```mermaid
graph TD
User[User] --> Roles[Roles]
User --> DirectPerms[Direct Permissions]
Roles --> RolePerms[Role Permissions]
RolePerms --> Check{Permission Check}
DirectPerms --> Check
Check -->|Granted| Resource[Access Resource]
Check -->|Denied| Reject[403 Forbidden]
subgraph "Permission Model"
Perm[Permission<br/>resource:action:scope]
end
style Check fill:#e1f5ff
style Perm fill:#fff4e1
```
**EN: RBAC (Role-Based Access Control)**
**1. Role Hierarchy**:
```
SuperAdmin > OrgAdmin > Manager > User > Guest
```
**2. Permission Format**: `resource:action:scope`
- Resource: `users`, `roles`, `permissions`
- Action: `create`, `read`, `update`, `delete`
- Scope: `own`, `org`, `global`
**Examples**:
- `users:read:own` - Read own user profile
- `users:update:org` - Update users in organization
- `roles:create:global` - Create roles globally
**3. Permission Caching**:
```typescript
// Cache key: user:{userId}:permissions
// TTL: 5 minutes
// Invalidate on: role change, permission change
```
**VI: RBAC (Role-Based Access Control)**
**1. Cấp bậc Role**:
```
SuperAdmin > OrgAdmin > Manager > User > Guest
```
**2. Format Permission**: `resource:action:scope`
- Resource: `users`, `roles`, `permissions`
- Action: `create`, `read`, `update`, `delete`
- Scope: `own`, `org`, `global`
**Ví dụ**:
- `users:read:own` - Đọc profile của chính mình
- `users:update:org` - Update users trong organization
- `roles:create:global` - Tạo roles globally
## Zero-Trust Architecture / Kiến trúc Zero-Trust
```mermaid
graph TD
Request[Request] --> Device[Device Fingerprint]
Device --> IP[IP Address Validation]
IP --> Behavior[Behavioral Analysis]
Behavior --> Session[Session Binding]
Session -->|Valid| Allow[Allow Request]
Session -->|Suspicious| MFA[Require MFA]
Session -->|Anomaly| Block[Block + Alert]
style Block fill:#f8d7da
style MFA fill:#fff3cd
style Allow fill:#d4edda
```
**EN: Zero-Trust Components**:
**1. Device Fingerprinting**:
- Browser: User-Agent, Canvas, WebGL
- Screen resolution, timezone, language
- Plugin detection, fonts available
- Hash fingerprint → Store with session
**2. IP Address Validation**:
- Whitelist known IPs per user
- Alert on new IP + require MFA
- Block suspicious IPs (VPN, Tor)
**3. Behavioral Analysis**:
- Login patterns (time, location)
- API usage patterns
- Failed auth attempts
- Alert on anomalies
**4. Session Binding**:
- Bind session to device fingerprint
- Bind session to IP address
- Invalidate on mismatch
**VI: Thành phần Zero-Trust**:
**1. Device Fingerprinting**:
- Browser: User-Agent, Canvas, WebGL
- Screen resolution, timezone, language
- Phát hiện plugin, fonts có sẵn
- Hash fingerprint → Lưu với session
**2. IP Address Validation**:
- Whitelist IPs đã biết cho user
- Alert với IP mới + require MFA
- Block IPs đáng ngờ (VPN, Tor)
## Data Protection / Bảo vệ Dữ liệu
**EN: Encryption Strategy**:
**1. Data at Rest**:
- PII: AES-256-GCM encryption
- Passwords: bcrypt (cost 12)
- Tokens: SHA-256 hash
- Keys: Environment variables + K8s secrets
**2. Data in Transit**:
- TLS 1.2+ for all communications
- HTTPS enforcement
- Certificate pinning (mobile clients)
**3. Key Management**:
- Unique key per encryption operation
- 32+ character ENCRYPTION_KEY
- Rotate keys quarterly
- Never hardcode secrets
**VI: Chiến lược Mã hóa**:
**1. Data at Rest**:
- PII: AES-256-GCM encryption
- Passwords: bcrypt (cost 12)
- Tokens: SHA-256 hash
- Keys: Environment variables + K8s secrets
**2. Data in Transit**:
- TLS 1.2+ cho mọi giao tiếp
- HTTPS enforcement
- Certificate pinning (mobile clients)
## Compliance & Audit / Tuân thủ & Kiểm toán
**EN: Compliance Requirements**:
**1. GDPR**:
- Right to erasure (soft delete + hard delete after 90 days)
- Data portability (export user data)
- Consent management
- Breach notification (72 hours)
**2. SOC2**:
- Access controls (RBAC)
- Encryption at rest and in transit
- Audit logging (7-year retention)
- Incident response plan
**3. Audit Trail**:
```typescript
// Event sourcing for all auth events
{
eventType: 'auth.login.success',
userId: 'user_123',
timestamp: '2024-01-15T10:30:00Z',
ipAddress: '192.168.1.1',
deviceFingerprint: 'fp_xyz',
metadata: {...}
}
```
**VI: Yêu cầu Tuân thủ**:
**1. GDPR**:
- Right to erasure (soft delete + hard delete sau 90 ngày)
- Data portability (export dữ liệu user)
- Quản lý consent
- Thông báo breach (72 giờ)
**2. SOC2**:
- Access controls (RBAC)
- Encryption at rest và in transit
- Audit logging (7 năm retention)
- Incident response plan
## Related Documentation / Tài liệu Liên quan
- [System Design](./system-design.md) - Overall architecture
- [IAM Architecture](./iam-proposal.md) - IAM service implementation
- [Event-Driven Architecture](./event-driven-architecture.md) - Audit event streaming
---
**Last Updated**: 2024-01-15
**Authors**: GoodGo Security Team

View File

@@ -1,81 +1,929 @@
# System Design
# System Design / Thiết kế Hệ thống
## Overview
> **EN**: Comprehensive system architecture for the GoodGo Microservices Platform
> **VI**: Kiến trúc hệ thống toàn diện cho GoodGo Microservices Platform
GoodGo Microservices Platform is built using a microservices architecture pattern with the following principles:
## System Overview / Tổng quan Hệ thống
- **Service Independence**: Each service has its own database and can be deployed independently
- **API Gateway**: Traefik handles routing, load balancing, and cross-cutting concerns
- **Shared Libraries**: Common functionality is extracted into shared packages
- **Infrastructure as Code**: All infrastructure configurations are versioned
- **Observability**: Full monitoring, logging, and tracing capabilities
## Architecture Diagram
```
┌─────────────┐ ┌─────────────┐
│ Web App │ │ Mobile App │
(Next.js) │ │ (React Native)
└──────┬──────┘ └──────┬──────┘
│ │
└──────────┬────────┘
┌────────▼────────┐
│ Traefik │
│ (API Gateway) │
└────────┬─────────┘
┌─────────────┼─────────────┐
│ │ │
┌───▼────┐ ┌───▼────┐ ┌───▼────┐
│ Auth │ Future │ │ Future │
│Service │ │Service │ │Service │
└───┬────┘ └───┬────┘ └───┬────┘
│ │
└────────────┼────────────┘
┌────────────┼────────────┐
│ │ │
┌───▼────┐ ┌───▼────┐ ┌───▼────┐
│Postgres│ │ Redis │ │Prometheus│
└────────┘ └────────┘ └─────────┘
```mermaid
graph TD
subgraph "Client Layer / Tầng Client"
WebApp[Web Application<br/>Next.js 14+]
MobileApp[Mobile Application<br/>Flutter/React Native]
end
subgraph "API Gateway Layer / Tầng API Gateway"
Traefik[Traefik Gateway<br/>Load Balancer + Routing]
end
subgraph "Services Layer / Tầng Services"
IAM[IAM Service<br/>Authentication & Authorization]
Template[Template Service<br/>Example Microservice]
Future1[Future Service 1<br/>TBD]
Future2[Future Service 2<br/>TBD]
end
subgraph "Data Layer / Tầng Dữ liệu"
PostgreSQL[(PostgreSQL 14+<br/>Primary Database)]
Redis[(Redis 6+<br/>Cache & Sessions)]
end
subgraph "Observability / Khả năng quan sát"
Prometheus[Prometheus<br/>Metrics Collection]
Grafana[Grafana<br/>Metrics Visualization]
Loki[Loki<br/>Log Aggregation]
Jaeger[Jaeger<br/>Distributed Tracing]
end
WebApp --> Traefik
MobileApp --> Traefik
Traefik --> IAM
Traefik --> Template
Traefik --> Future1
Traefik --> Future2
IAM --> PostgreSQL
Template --> PostgreSQL
Future1 --> PostgreSQL
Future2 --> PostgreSQL
IAM --> Redis
Template --> Redis
Future1 --> Redis
Future2 --> Redis
IAM -.->|Metrics| Prometheus
Template -.->|Metrics| Prometheus
Prometheus --> Grafana
IAM -.->|Logs| Loki
Template -.->|Logs| Loki
IAM -.->|Traces| Jaeger
Template -.->|Traces| Jaeger
style Traefik fill:#e1f5ff
style PostgreSQL fill:#f0e1ff
style Redis fill:#fff4e1
style Prometheus fill:#d4edda
```
## Components
### EN: Architecture Principles
### Frontend Layer
- **Web App**: Next.js application with App Router
- **Mobile App**: React Native application
The GoodGo Microservices Platform follows these core principles:
### API Gateway
- **Traefik**: Reverse proxy, load balancer, SSL termination
1. **Service Independence**: Each microservice:
- Has its own database schema (database per service pattern)
- Can be deployed independently without affecting others
- Owns its data and exposes APIs for data access
- Uses standardized communication patterns
### Services Layer
- **Auth Service**: Authentication and authorization
- **Future Services**: Payment, Order, Notification, etc.
2. **API Gateway Pattern**: Traefik provides:
- Single entry point for all client requests
- Path-based routing to appropriate services
- Load balancing across service instances
- SSL/TLS termination
- Rate limiting and security headers
### Infrastructure Layer
- **PostgreSQL**: Primary database
- **Redis**: Caching and session storage
- **Prometheus**: Metrics collection
- **Grafana**: Metrics visualization
- **Loki**: Log aggregation
3. **Shared Infrastructure**: Common concerns handled by:
- Shared packages (@goodgo/logger, @goodgo/types, @goodgo/http-client)
- Centralized observability stack
- Distributed caching layer (Redis)
- Common monitoring and alerting
## Communication Patterns
4. **Infrastructure as Code**: All configurations versioned:
- Docker Compose for local development
- Kubernetes manifests for production
- Traefik dynamic configuration
- Database migrations with Prisma
- **Synchronous**: HTTP/REST for request-response patterns
- **Asynchronous**: Message queues (future implementation)
- **Service Discovery**: Docker networking and Kubernetes DNS
5. **Observability First**: Built-in monitoring:
- Prometheus metrics from all services
- Structured logging with correlation IDs
- Distributed tracing with OpenTelemetry
- Health check endpoints (liveness/readiness)
## Data Management
### VI: Nguyên tắc Kiến trúc
- **Database per Service**: Each service owns its data
- **API Composition**: Services expose APIs for data access
- **Event Sourcing**: Future consideration for audit trails
GoodGo Microservices Platform tuân theo các nguyên tắc cốt lõi sau:
## Security
1. **Độc lập Service**: Mỗi microservice:
- Có schema database riêng (pattern database per service)
- Có thể deploy độc lập mà không ảnh hưởng đến các service khác
- Sở hữu dữ liệu của mình và expose APIs để truy cập dữ liệu
- Sử dụng patterns giao tiếp chuẩn hóa
- **Authentication**: JWT tokens with refresh token rotation
- **Authorization**: Role-based access control (RBAC)
- **Network Security**: TLS/SSL, rate limiting, CORS
- **Secrets Management**: Environment variables, Kubernetes secrets
2. **Pattern API Gateway**: Traefik cung cấp:
- Điểm vào duy nhất cho tất cả client requests
- Routing dựa trên path tới các service phù hợp
- Load balancing giữa các service instances
- SSL/TLS termination
- Rate limiting và security headers
3. **Infrastructure Chia sẻ**: Các concerns chung được xử lý bởi:
- Shared packages (@goodgo/logger, @goodgo/types, @goodgo/http-client)
- Stack observability tập trung
- Tầng caching phân tán (Redis)
- Monitoring và alerting chung
4. **Infrastructure as Code**: Tất cả cấu hình được version:
- Docker Compose cho local development
- Kubernetes manifests cho production
- Traefik dynamic configuration
- Database migrations với Prisma
5. **Observability First**: Monitoring tích hợp sẵn:
- Prometheus metrics từ tất cả services
- Structured logging với correlation IDs
- Distributed tracing với OpenTelemetry
- Health check endpoints (liveness/readiness)
---
## Detailed Component Architecture / Kiến trúc Component Chi tiết
### 1. Client Layer / Tầng Client
```mermaid
graph LR
User((User)) --> WebBrowser[Web Browser]
User --> MobileDevice[Mobile Device]
WebBrowser --> NextJS[Next.js App<br/>Port 3000]
MobileDevice --> Flutter[Flutter App<br/>iOS/Android]
NextJS --> APIClient[@goodgo/http-client]
Flutter --> HTTPPackage[HTTP Package]
APIClient --> Gateway[API Gateway<br/>localhost or api.goodgo.com]
HTTPPackage --> Gateway
style User fill:#e1f5ff
style Gateway fill:#d4edda
```
**EN Components**:
- **Web Application**: Next.js 14+ with App Router
- Server-side rendering (SSR)
- Static site generation (SSG)
- API routes for BFF pattern
- Uses `@goodgo/http-client` for API calls
- **Mobile Application**: Flutter or React Native
- Cross-platform (iOS + Android)
- Offline-first architecture (future)
- Native HTTP client
**VI Thành phần**:
- **Web Application**: Next.js 14+ với App Router
- Server-side rendering (SSR)
- Static site generation (SSG)
- API routes cho BFF pattern
- Sử dụng `@goodgo/http-client` cho API calls
- **Mobile Application**: Flutter hoặc React Native
- Cross-platform (iOS + Android)
- Kiến trúc offline-first (tương lai)
- Native HTTP client
---
### 2. API Gateway Layer / Tầng API Gateway
```mermaid
graph TD
Client[Client Request] --> Traefik
subgraph "Traefik API Gateway"
Traefik[Traefik Router] --> Middlewares
subgraph Middlewares
M1[CORS]
M2[Rate Limiting]
M3[Headers]
M4[Compression]
end
Middlewares --> Router[Dynamic Router]
Router --> LB[Load Balancer]
end
LB --> Service1[Service Instance 1]
LB --> Service2[Service Instance 2]
LB --> Service3[Service Instance 3]
style Traefik fill:#e1f5ff
style Router fill:#fff4e1
style LB fill:#d4edda
```
**EN: Traefik Configuration**
**Static Configuration** (`infra/traefik/traefik.yml`):
- Entry points (HTTP: 80, HTTPS: 443)
- Docker provider for service discovery
- Certificate resolvers (Let's Encrypt)
- Dashboard configuration (port 8080)
**Dynamic Configuration** (`infra/traefik/dynamic/`):
- Middlewares (CORS, rate limiting, security headers)
- Routes (defined via Docker labels or YAML files)
- Services (load balancing strategies)
**Routing Pattern**:
```yaml
http:
routers:
iam-service:
rule: "PathPrefix(`/api/v1/auth`)"
service: iam-service
middlewares:
- cors
- rate-limit
- secure-headers
```
**Service Discovery**: Automatic via Docker labels:
```yaml
labels:
- "traefik.enable=true"
- "traefik.http.routers.iam.rule=PathPrefix(`/api/v1/auth`)"
- "traefik.http.services.iam.loadbalancer.server.port=3001"
- "traefik.http.services.iam.loadbalancer.healthcheck.path=/health/live"
```
**VI: Cấu hình Traefik**
**Cấu hình Tĩnh** (`infra/traefik/traefik.yml`):
- Entry points (HTTP: 80, HTTPS: 443)
- Docker provider cho service discovery
- Certificate resolvers (Let's Encrypt)
- Cấu hình dashboard (port 8080)
**Cấu hình Động** (`infra/traefik/dynamic/`):
- Middlewares (CORS, rate limiting, security headers)
- Routes (định nghĩa qua Docker labels hoặc YAML files)
- Services (chiến lược load balancing)
**Pattern Routing**:
```yaml
http:
routers:
iam-service:
rule: "PathPrefix(`/api/v1/auth`)"
service: iam-service
middlewares:
- cors
- rate-limit
- secure-headers
```
**Service Discovery**: Tự động qua Docker labels:
```yaml
labels:
- "traefik.enable=true"
- "traefik.http.routers.iam.rule=PathPrefix(`/api/v1/auth`)"
- "traefik.http.services.iam.loadbalancer.server.port=3001"
- "traefik.http.services.iam.loadbalancer.healthcheck.path=/health/live"
```
---
### 3. Services Layer / Tầng Services
#### Microservice Template Structure / Cấu trúc Template Microservice
```mermaid
graph TD
subgraph "Microservice (Template Pattern)"
HTTP[HTTP Request] --> MW[Middleware Stack]
MW --> Routes[Routes]
subgraph "Feature Module"
Routes --> Controller
Controller --> Service
Service --> Repository
Repository --> Prisma[Prisma ORM]
end
Service --> Cache[Cache Service]
Cache --> Redis[(Redis)]
Prisma --> DB[(PostgreSQL)]
MW --> Metrics[Metrics Middleware]
Metrics --> Prom[Prometheus]
end
style MW fill:#e1f5ff
style Service fill:#f0e1ff
style Cache fill:#fff4e1
```
**EN: Standard Microservice Structure**
Each microservice follows this pattern (from `services/_template/`):
```
src/
├── config/ # Configuration with Zod validation
│ ├── app.config.ts
│ ├── database.config.ts
│ └── redis.config.ts
├── core/ # Core utilities (IAM service only)
│ ├── cache/ # Multi-layer caching
│ ├── events/ # Event sourcing
│ └── security/ # Zero-trust validator
├── middlewares/ # Express middlewares
│ ├── correlation.middleware.ts
│ ├── logger.middleware.ts
│ ├── metrics.middleware.ts
│ └── error.middleware.ts
├── modules/ # Feature modules
│ ├── common/ # Shared (BaseRepository)
│ ├── feature/ # Example feature
│ ├── health/ # Health checks
│ └── metrics/ # Prometheus metrics
├── routes/ # Route definitions
│ └── index.ts
└── main.ts # Application entry point
```
**Middleware Execution Order**:
1. Correlation ID → 2. Logger → 3. Metrics → 4. CORS → 5. Rate Limit → 6. Body Parser → 7. Routes → 8. Error Handler
**VI: Cấu trúc Microservice Chuẩn**
Mỗi microservice tuân theo pattern này (từ `services/_template/`):
```
src/
├── config/ # Configuration với Zod validation
│ ├── app.config.ts
│ ├── database.config.ts
│ └── redis.config.ts
├── core/ # Core utilities (chỉ IAM service)
│ ├── cache/ # Multi-layer caching
│ ├── events/ # Event sourcing
│ └── security/ # Zero-trust validator
├── middlewares/ # Express middlewares
│ ├── correlation.middleware.ts
│ ├── logger.middleware.ts
│ ├── metrics.middleware.ts
│ └── error.middleware.ts
├── modules/ # Feature modules
│ ├── common/ # Shared (BaseRepository)
│ ├── feature/ # Example feature
│ ├── health/ # Health checks
│ └── metrics/ # Prometheus metrics
├── routes/ # Route definitions
│ └── index.ts
└── main.ts # Application entry point
```
**Thứ tự Thực thi Middleware**:
1. Correlation ID → 2. Logger → 3. Metrics → 4. CORS → 5. Rate Limit → 6. Body Parser → 7. Routes → 8. Error Handler
---
### 4. Data Layer / Tầng Dữ liệu
#### Database Architecture / Kiến trúc Database
```mermaid
graph TD
subgraph "Database Per Service Pattern"
Service1[IAM Service] --> Schema1[(iam_db<br/>30+ tables)]
Service2[Template Service] --> Schema2[(template_db<br/>Example tables)]
Service3[Future Service] --> Schema3[(future_db<br/>TBD)]
end
subgraph "Shared Infrastructure"
Schema1 -.->|Connection Pool| PG[PostgreSQL 14+<br/>Neon Cloud]
Schema2 -.->|Connection Pool| PG
Schema3 -.->|Connection Pool| PG
end
subgraph "Cache Layer"
Service1 --> L1_1[L1: Memory<br/>60s TTL]
Service2 --> L1_2[L1: Memory<br/>60s TTL]
L1_1 --> L2[L2: Redis<br/>5-15min TTL]
L1_2 --> L2
L2 -.->|Cache Miss| Schema1
L2 -.->|Cache Miss| Schema2
end
style PG fill:#f0e1ff
style L2 fill:#fff4e1
style L1_1 fill:#d4edda
style L1_2 fill:#d4edda
```
**EN: Data Management**
**Database per Service**:
- Each service has its own database schema
- Services own their data exclusively
- Cross-service data access via APIs only
- Independent scaling and optimization
**Multi-Layer Caching** (IAM Service):
```
Request → L1 (Memory, 60s) → L2 (Redis, 5-15min) → L3 (Database)
```
**Cache Hit Rates**:
- L1: ~40-50% (hot data)
- L2: ~80-90% (permissions, user data)
- L3: 10-20% (cache miss, fetch from DB)
**Database Technology**:
- **Provider**: Neon (Serverless PostgreSQL)
- **Version**: PostgreSQL 14+
- **ORM**: Prisma
- **Connection Pooling**: Prisma (10 connections default)
- **Migrations**: Prisma Migrate
**VI: Quản lý Dữ liệu**
**Database per Service**:
- Mỗi service có schema database riêng
- Services sở hữu dữ liệu độc quyền
- Truy cập dữ liệu cross-service chỉ qua APIs
- Scaling và optimization độc lập
**Multi-Layer Caching** (IAM Service):
```
Request → L1 (Memory, 60s) → L2 (Redis, 5-15min) → L3 (Database)
```
**Tỷ lệ Cache Hit**:
- L1: ~40-50% (hot data)
- L2: ~80-90% (permissions, user data)
- L3: 10-20% (cache miss, fetch từ DB)
**Công nghệ Database**:
- **Provider**: Neon (Serverless PostgreSQL)
- **Version**: PostgreSQL 14+
- **ORM**: Prisma
- **Connection Pooling**: Prisma (10 connections mặc định)
- **Migrations**: Prisma Migrate
---
## Communication Patterns / Patterns Giao tiếp
### Request Flow / Luồng Request
```mermaid
sequenceDiagram
participant Client
participant Traefik as Traefik Gateway
participant Service
participant Cache as Redis Cache
participant DB as PostgreSQL
Client->>Traefik: HTTP Request
Traefik->>Traefik: Apply Middlewares<br/>(CORS, Rate Limit)
Traefik->>Service: Forward Request
Service->>Cache: Check Cache
alt Cache Hit
Cache-->>Service: Cached Data
Service-->>Traefik: Response (from cache)
else Cache Miss
Cache-->>Service: null
Service->>DB: Query Database
DB-->>Service: Data
Service->>Cache: Store in Cache
Service-->>Traefik: Response (from DB)
end
Traefik-->>Client: HTTP Response
```
**EN: Communication Patterns**
1. **Synchronous (HTTP/REST)**:
- Request-response pattern
- RESTful API design
- JSON payload format
- Standard HTTP status codes
2. **Service-to-Service**:
- Internal HTTP calls via `@goodgo/http-client`
- Service authentication with internal API keys
- Circuit breaker pattern for resilience
- Correlation ID propagation
3. **Service Discovery**:
- **Local**: Docker DNS (`http://service-name:port`)
- **Kubernetes**: Service DNS (`http://service-name.namespace.svc.cluster.local`)
- **Traefik**: Dynamic configuration via labels
4. **Asynchronous (Future)**:
- Message queues (RabbitMQ/Kafka)
- Event-driven architecture
- Pub/Sub patterns
**VI: Patterns Giao tiếp**
1. **Đồng bộ (HTTP/REST)**:
- Pattern request-response
- Thiết kế RESTful API
- Format payload JSON
- HTTP status codes chuẩn
2. **Service-to-Service**:
- Internal HTTP calls qua `@goodgo/http-client`
- Service authentication với internal API keys
- Circuit breaker pattern cho resilience
- Correlation ID propagation
3. **Service Discovery**:
- **Local**: Docker DNS (`http://service-name:port`)
- **Kubernetes**: Service DNS (`http://service-name.namespace.svc.cluster.local`)
- **Traefik**: Dynamic configuration qua labels
4. **Bất đồng bộ (Tương lai)**:
- Message queues (RabbitMQ/Kafka)
- Event-driven architecture
- Pub/Sub patterns
---
## Security Architecture / Kiến trúc Bảo mật
```mermaid
graph TD
Request[Client Request] --> TLS[TLS/HTTPS]
TLS --> RateLimit[Rate Limiting]
RateLimit --> JWT[JWT Validation]
JWT --> RBAC[RBAC Authorization]
RBAC --> ZeroTrust[Zero-Trust Validation]
ZeroTrust --> Service[Service Logic]
Service --> Encrypt[Data Encryption<br/>AES-256-GCM]
Encrypt --> DB[(Encrypted Data<br/>at Rest)]
Service --> Audit[Audit Logging<br/>Event Sourcing]
Audit --> AuditDB[(Audit Trail<br/>7-year retention)]
style TLS fill:#d4edda
style JWT fill:#e1f5ff
style Encrypt fill:#f8d7da
style Audit fill:#fff4e1
```
**EN: Security Layers**
1. **Network Security**:
- TLS 1.2+ for all communications
- HTTPS enforcement
- CORS configuration
- Rate limiting (Redis-backed, distributed)
2. **Authentication**:
- JWT tokens (15min access, 7 days refresh)
- bcrypt password hashing (cost 12)
- Refresh token rotation
- Multi-factor authentication (TOTP)
3. **Authorization**:
- Role-Based Access Control (RBAC)
- Attribute-Based Access Control (ABAC)
- Permission model: `resource:action:scope`
- Permission caching (5min TTL)
4. **Data Protection**:
- AES-256-GCM encryption for PII
- Token hashing (SHA-256)
- Secrets management (environment variables, K8s secrets)
5. **Zero-Trust**:
- Device fingerprinting
- IP address validation
- Behavioral analysis
- Session binding
6. **Audit & Compliance**:
- Event sourcing for all auth events
- 7-year retention (GDPR, SOC2)
- Correlation ID tracking
- Compliance reporting (GDPR, SOC2, ISO27001, HIPAA)
**VI: Các Tầng Bảo mật**
1. **Network Security**:
- TLS 1.2+ cho mọi giao tiếp
- HTTPS enforcement
- Cấu hình CORS
- Rate limiting (Redis-backed, phân tán)
2. **Authentication**:
- JWT tokens (15min access, 7 ngày refresh)
- bcrypt password hashing (cost 12)
- Refresh token rotation
- Multi-factor authentication (TOTP)
3. **Authorization**:
- Role-Based Access Control (RBAC)
- Attribute-Based Access Control (ABAC)
- Permission model: `resource:action:scope`
- Permission caching (5min TTL)
4. **Data Protection**:
- AES-256-GCM encryption cho PII
- Token hashing (SHA-256)
- Secrets management (environment variables, K8s secrets)
5. **Zero-Trust**:
- Device fingerprinting
- IP address validation
- Behavioral analysis
- Session binding
6. **Audit & Compliance**:
- Event sourcing cho tất cả auth events
- 7-year retention (GDPR, SOC2)
- Correlation ID tracking
- Compliance reporting (GDPR, SOC2, ISO27001, HIPAA)
---
## Observability Stack / Stack Khả năng quan sát
```mermaid
graph LR
subgraph "Services"
S1[IAM Service]
S2[Template Service]
end
subgraph "Metrics"
S1 -->|/metrics| Prom[Prometheus]
S2 -->|/metrics| Prom
Prom --> Grafana[Grafana Dashboard]
end
subgraph "Logging"
S1 -->|JSON Logs| Loki[Loki]
S2 -->|JSON Logs| Loki
Loki --> GrafanaLog[Grafana Explore]
end
subgraph "Tracing"
S1 -->|Spans| Jaeger[Jaeger]
S2 -->|Spans| Jaeger
Jaeger --> JaegerUI[Jaeger UI]
end
style Prom fill:#d4edda
style Loki fill:#fff4e1
style Jaeger fill:#e1f5ff
```
**EN: Three Pillars of Observability**
1. **Metrics (Prometheus)**:
- HTTP request duration (histogram)
- HTTP request count (counter)
- Active requests (gauge)
- Cache hit/miss ratio
- Database query duration
- Custom business metrics
2. **Logging (Winston + Loki)**:
- Structured JSON logs
- Correlation IDs in every log
- Request/response logging
- Error stack traces (dev only)
- Log levels: error, warn, info, debug
3. **Tracing (OpenTelemetry + Jaeger)**:
- Distributed tracing across services
- HTTP request spans
- Database query spans
- Cache operation spans
- End-to-end latency tracking
**Health Checks**:
- `/health` - Overall health status
- `/health/live` - Liveness probe (K8s)
- `/health/ready` - Readiness probe (K8s, checks DB + Redis)
**VI: Ba Trụ cột của Khả năng quan sát**
1. **Metrics (Prometheus)**:
- HTTP request duration (histogram)
- HTTP request count (counter)
- Active requests (gauge)
- Cache hit/miss ratio
- Database query duration
- Custom business metrics
2. **Logging (Winston + Loki)**:
- Structured JSON logs
- Correlation IDs trong mọi log
- Request/response logging
- Error stack traces (chỉ dev)
- Log levels: error, warn, info, debug
3. **Tracing (OpenTelemetry + Jaeger)**:
- Distributed tracing giữa các services
- HTTP request spans
- Database query spans
- Cache operation spans
- End-to-end latency tracking
**Health Checks**:
- `/health` - Overall health status
- `/health/live` - Liveness probe (K8s)
- `/health/ready` - Readiness probe (K8s, kiểm tra DB + Redis)
---
## Deployment Architecture / Kiến trúc Triển khai
### Local Development / Phát triển Local
```mermaid
graph TD
subgraph "Docker Compose (deployments/local)"
Traefik[Traefik<br/>Port 80, 8080]
IAM[IAM Service<br/>Port 3001]
Template[Template Service<br/>Port 5000]
PostgreSQL[PostgreSQL<br/>Port 5432]
Redis[Redis<br/>Port 6379]
Traefik --> IAM
Traefik --> Template
IAM --> PostgreSQL
IAM --> Redis
Template --> PostgreSQL
Template --> Redis
end
Dev[Developer] -->|localhost| Traefik
Dev -->|:8080| TraefikDash[Traefik Dashboard]
style Traefik fill:#e1f5ff
style PostgreSQL fill:#f0e1ff
style Redis fill:#fff4e1
```
### Production Deployment / Triển khai Production
```mermaid
graph TD
subgraph "Kubernetes Cluster"
Ingress[Ingress Controller<br/>Traefik]
subgraph "IAM Service"
IAM1[IAM Pod 1]
IAM2[IAM Pod 2]
IAM3[IAM Pod 3]
end
subgraph "Template Service"
T1[Template Pod 1]
T2[Template Pod 2]
end
Ingress --> IAM1
Ingress --> IAM2
Ingress --> IAM3
Ingress --> T1
Ingress --> T2
end
subgraph "Managed Services"
Neon[(Neon PostgreSQL<br/>Serverless)]
RedisCloud[(Redis Cloud)]
end
IAM1 --> Neon
IAM2 --> Neon
IAM3 --> Neon
T1 --> Neon
T2 --> Neon
IAM1 --> RedisCloud
IAM2 --> RedisCloud
T1 --> RedisCloud
T2 --> RedisCloud
style Ingress fill:#e1f5ff
style Neon fill:#f0e1ff
style RedisCloud fill:#fff4e1
```
**EN: Deployment Environments**
1. **Local (Docker Compose)**:
- All services run in Docker containers
- Shared network for service communication
- Local PostgreSQL and Redis
- Traefik for routing
- Hot reload for development
2. **Staging (Kubernetes)**:
- Kubernetes cluster in cloud (GKE/EKS/AKS)
- 2 replicas per service
- Managed PostgreSQL (Neon)
- Managed Redis (Redis Cloud)
- Horizontal Pod Autoscaling (HPA)
3. **Production (Kubernetes)**:
- Production K8s cluster
- 3+ replicas per service
- Managed databases with backups
- Auto-scaling (HPA + VPA)
- Blue-green deployments
- Rolling updates with health checks
**VI: Môi trường Triển khai**
1. **Local (Docker Compose)**:
- Tất cả services chạy trong Docker containers
- Shared network cho service communication
- Local PostgreSQL và Redis
- Traefik cho routing
- Hot reload cho development
2. **Staging (Kubernetes)**:
- Kubernetes cluster trên cloud (GKE/EKS/AKS)
- 2 replicas mỗi service
- Managed PostgreSQL (Neon)
- Managed Redis (Redis Cloud)
- Horizontal Pod Autoscaling (HPA)
3. **Production (Kubernetes)**:
- Production K8s cluster
- 3+ replicas mỗi service
- Managed databases với backups
- Auto-scaling (HPA + VPA)
- Blue-green deployments
- Rolling updates với health checks
---
## Performance Characteristics / Đặc điểm Hiệu suất
**EN: Performance Targets**
| Metric | Target | Notes |
|--------|--------|-------|
| **API Response Time (P95)** | < 100ms | Excluding cold starts |
| **API Response Time (P99)** | < 200ms | |
| **Throughput** | 1000 req/s | Per service instance |
| **Cache Hit Rate** | > 80% | Redis cache |
| **Database Query Time (P95)** | < 50ms | Simple queries |
| **Memory Usage** | < 512MB | Per service instance |
| **CPU Usage** | < 60% | Under normal load |
**Optimization Strategies**:
- Multi-layer caching (L1: Memory, L2: Redis)
- Database connection pooling
- Query optimization with indexes
- Horizontal scaling with HPA
- CDN for static assets
**VI: Mục tiêu Hiệu suất**
| Metric | Mục tiêu | Ghi chú |
|--------|----------|---------|
| **API Response Time (P95)** | < 100ms | Không bao gồm cold starts |
| **API Response Time (P99)** | < 200ms | |
| **Throughput** | 1000 req/s | Mỗi service instance |
| **Cache Hit Rate** | > 80% | Redis cache |
| **Database Query Time (P95)** | < 50ms | Queries đơn giản |
| **Memory Usage** | < 512MB | Mỗi service instance |
| **CPU Usage** | < 60% | Ở normal load |
**Chiến lược Tối ưu**:
- Multi-layer caching (L1: Memory, L2: Redis)
- Database connection pooling
- Query optimization với indexes
- Horizontal scaling với HPA
- CDN cho static assets
---
## Related Documentation / Tài liệu Liên quan
- [Service Communication](./service-communication.md) - EN: Detailed inter-service communication patterns / VI: Patterns giao tiếp giữa services chi tiết
- [IAM Proposal](./iam-proposal.md) - EN: IAM service architecture and features / VI: Kiến trúc và tính năng IAM service
- [Deployment Guide](../guides/deployment.md) - EN: Step-by-step deployment instructions / VI: Hướng dẫn triển khai từng bước
- [Local Development](../guides/local-development.md) - EN: Setting up local environment / VI: Thiết lập môi trường local
- [Project Rules](../skills/project-rules.md) - EN: Project structure and conventions / VI: Cấu trúc dự án và quy ước
---
**Last Updated / Cập nhật lần cuối**: 2026-01-06
**Authors / Tác giả**: DevOps Team
**Reviewers / Người review**: Architecture Team

482
docs/en/templates/README.md Normal file
View File

@@ -0,0 +1,482 @@
# Template Usage Guide / Hướng dẫn Sử dụng Templates
## Overview / Tổng quan
**EN**: This guide explains how to use the documentation templates to maintain consistency across all documentation updates.
**VI**: Hướng dẫn này giải thích cách sử dụng các templates tài liệu để duy trì tính nhất quán trong tất cả các cập nhật tài liệu.
## Available Templates / Templates Có sẵn
| Template | Use For | File |
|----------|---------|------|
| **Architecture** | System design, component architecture | [`architecture-doc-template.md`](./architecture-doc-template.md) |
| **Guide** | Step-by-step howtos, tutorials | [`guide-doc-template.md`](./guide-doc-template.md) |
| **Skill/Pattern** | Design patterns, coding standards | [`skill-pattern-template.md`](./skill-pattern-template.md) |
| **Mermaid** | Diagram reference and examples | [`MERMAID_GUIDE.md`](./MERMAID_GUIDE.md) |
---
## Quick Start / Bắt đầu Nhanh
### 1. Choose the Right Template / Chọn Template Phù hợp
**Decision Tree / Cây Quyết định**:
```mermaid
flowchart TD
Start{What are you<br/>documenting?}
Start -->|System design,<br/>components| Arch[Use Architecture<br/>Template]
Start -->|How-to guide,<br/>setup steps| Guide[Use Guide<br/>Template]
Start -->|Code pattern,<br/>best practice| Skill[Use Skill/Pattern<br/>Template]
Arch --> Mermaid[Add Mermaid<br/>Diagrams]
Guide --> Mermaid
Skill --> Mermaid
Mermaid --> Write[Write Bilingual<br/>Content]
Write --> Review[Review & Test]
style Start fill:#fff3cd
style Mermaid fill:#e1f5ff
style Write fill:#d4edda
style Review fill:#f0e1ff
```
### 2. Copy Template / Sao chép Template
```bash
# EN: Copy appropriate template
# VI: Sao chép template phù hợp
# For Architecture docs
cp docs/templates/architecture-doc-template.md docs/en/architecture/your-doc.md
cp docs/templates/architecture-doc-template.md docs/vi/architecture/your-doc.md
# For Guides
cp docs/templates/guide-doc-template.md docs/en/guides/your-guide.md
cp docs/templates/guide-doc-template.md docs/vi/guides/your-guide.md
# For Skills
cp docs/templates/skill-pattern-template.md docs/en/skills/your-skill.md
cp docs/templates/skill-pattern-template.md docs/vi/skills/your-skill.md
```
### 3. Fill in Content / Điền Nội dung
Replace all placeholders:
- `[Architecture Name]` / `[Tên Kiến trúc]`
- `[Guide Title]` / `[Tiêu đề Hướng dẫn]`
- `[Pattern Name]` / `[Tên Pattern]`
- Code examples
- Mermaid diagrams
---
## Using Architecture Template / Sử dụng Architecture Template
### Sections to Complete / Sections Cần hoàn thành
#### 1. Overview Diagram
**EN**: Create a high-level diagram showing main components
**VI**: Tạo sơ đồ cấp cao cho thấy các thành phần chính
**Diagram Type**: Use `graph TD` or `C4Context`
**Example**:
```mermaid
graph TD
A[Component A] --> B[Component B]
B --> C[Component C]
```
#### 2. Architecture Description
**EN**: Explain purpose, goals, and design decisions
**VI**: Giải thích mục đích, mục tiêu và quyết định thiết kế
**Content to Include**:
- Purpose and goals / Mục đích và mục tiêu
- Key components / Thành phần chính
- Design decisions / Quyết định thiết kế
- Technology choices / Lựa chọn công nghệ
- Trade-offs / Đánh đổi
#### 3. Components Breakdown
**EN**: Detail each major component with:
- Description
- Key features
- Technologies used
- Code references (links to actual source)
- File location
**VI**: Chi tiết từng thành phần chính với:
- Mô tả
- Tính năng chính
- Công nghệ sử dụng
- Tham chiếu code (links tới source thực tế)
- Vị trí file
**Code Reference Format**:
```typescript
// EN: Example code showing implementation
// VI: Ví dụ code cho thấy cách triển khai
import { Component } from './component';
```
**File Link**: [`component.ts`](file:///absolute/path/to/component.ts)
#### 4. Data Flow Diagram
**Diagram Type**: Use `sequenceDiagram`
**Shows**: How data flows through the system
#### 5. Database Architecture (if applicable)
**Diagram Type**: Use `erDiagram`
**Shows**: Database schema and relationships
#### 6. Design Decisions
**Format**:
- **Context**: Why decision was needed
- **Decision**: What was decided
- **Consequences**: Impact (positive and negative)
- **Alternatives**: Other options considered
---
## Using Guide Template / Sử dụng Guide Template
### Sections to Complete / Sections Cần hoàn thành
#### 1. Workflow Diagram
**Diagram Type**: Use `flowchart LR` or `flowchart TD`
**Shows**: Overall workflow from start to finish
**Include**:
- Start/End nodes (rounded)
- Decision points (diamond)
- Action steps (rectangle)
- Error handling paths
#### 2. Prerequisites
**List**:
- Required software with versions
- Required knowledge
- Required access/credentials
**Include Quick Check**:
```bash
# Commands to verify prerequisites
node --version
docker --version
```
#### 3. Step-by-Step Instructions
**For Each Step**:
- Clear title
- Bilingual explanation
- Commands with comments
- Expected output
- Important notes
- File examples
**Format**:
```markdown
### Step 1: [Action]
**EN**: English explanation
**VI**: Giải thích tiếng Việt
\`\`\`bash
# EN: Command description
# VI: Mô tả lệnh
command-here
\`\`\`
```
#### 4. Verification
**Include**:
- Quick test commands
- Verification checklist
- Expected results
#### 5. Troubleshooting
**For Each Issue**:
- Symptoms (what you see)
- Solution (steps to fix)
- Bilingual for both
**Optional**: Add troubleshooting decision tree
---
## Using Skill/Pattern Template / Sử dụng Skill/Pattern Template
### Sections to Complete / Sections Cần hoàn thành
#### 1. Pattern Overview Diagram
**Diagram Type**: Use `graph LR` or `graph TD`
**Shows**: High-level pattern flow
#### 2. When to Use
**Include**:
- ✅ DO use for (scenarios)
- ❌ DON'T use for (anti-patterns)
#### 3. Implementation
**Provide**:
- Basic implementation (simple)
- Advanced implementation (with caching, error handling, etc.)
- Bilingual code comments
**Code Format**:
```typescript
/**
* EN: Class description
* VI: Mô tả class
*/
export class ExamplePattern {
// EN: Implementation details
// VI: Chi tiết triển khai
}
```
**Reference Actual Code**:
- Link to `_template` for basic patterns
- Link to `iam-service` for advanced patterns
**Example**:
```markdown
**Template**: [`feature.service.ts`](file:///Users/velikho/Desktop/WORKING/Base/services/_template/src/modules/feature/feature.service.ts)
**IAM**: [`rbac.service.ts`](file:///Users/velikho/Desktop/WORKING/Base/services/iam-service/src/modules/rbac/rbac.service.ts)
```
#### 4. Class Structure Diagram
**Diagram Type**: Use `classDiagram`
**Shows**: Class relationships, inheritance, dependencies
#### 5. Sequence Flow
**Diagram Type**: Use `sequenceDiagram`
**Shows**: Interaction between components
#### 6. Usage Examples
**Provide**:
- Example 1: Basic usage
- Example 2: Advanced usage
- Include setup, execution, and expected output
#### 7. Common Mistakes
**For Each Mistake**:
```markdown
#### Mistake 1: [Description]
\`\`\`typescript
// ❌ BAD: Incorrect implementation
bad code here
\`\`\`
\`\`\`typescript
// ✅ GOOD: Correct implementation
good code here
\`\`\`
**EN Why**: Explanation
**VI Tại sao**: Giải thích
```
#### 8. Unit Test Example
**Include**:
- Setup (before each)
- Test cases (happy path + error cases)
- Assertions
---
## Bilingual Content Guidelines / Hướng dẫn Nội dung Song ngữ
### Format Options / Tùy chọn Định dạng
#### Option 1: Side-by-side (for short content)
```markdown
> **EN**: Brief English description
> **VI**: Mô tả ngắn gọn tiếng Việt
```
#### Option 2: Separate sections (for detailed content)
```markdown
### EN: English Section
Detailed English content...
### VI: Phần Tiếng Việt
Nội dung chi tiết tiếng Việt...
```
#### Option 3: Inline (for code comments)
```typescript
// EN: English comment
// VI: Comment tiếng Việt
const example = 'value';
```
### Translation Consistency / Tính nhất quán Dịch thuật
**Common Technical Terms**:
| EN | VI |
|----|-----|
| Authentication | Xác thực |
| Authorization | Phân quyền |
| Deployment | Triển khai |
| Middleware | Middleware (giữ nguyên) |
| Repository | Repository (giữ nguyên) |
| Service | Service (giữ nguyên) |
| Controller | Controller (giữ nguyên) |
| Microservice | Microservice (giữ nguyên) |
| Cache | Cache (giữ nguyên) |
| Database | Database (giữ nguyên) |
**Note**: Some technical terms are kept in English for clarity and consistency with code.
---
## Adding Mermaid Diagrams / Thêm Sơ đồ Mermaid
### Step 1: Choose Diagram Type
Refer to [`MERMAID_GUIDE.md`](./MERMAID_GUIDE.md) for:
- Diagram type selection
- Syntax examples
- Styling guidelines
### Step 2: Create Diagram
```markdown
\`\`\`mermaid
graph TD
A[Start] --> B[Process]
B --> C[End]
\`\`\`
```
### Step 3: Test Rendering
```bash
# Install mermaid-cli
npm install -g @mermaid-js/mermaid-cli
# Test render your doc
mmdc -i docs/en/your-doc.md -o test-output.svg
# Check for errors
echo $? # 0 = success
```
### Step 4: Apply Consistent Styling
```mermaid
graph TD
Start([Start]) --> Process[Process]
Process --> End([End])
style Start fill:#e1f5ff
style End fill:#d4edda
style Process fill:#f0e1ff
```
**Color Palette**:
- `#e1f5ff` - Blue (primary, start)
- `#d4edda` - Green (success, end)
- `#fff3cd` - Yellow (warning, decision)
- `#f8d7da` - Red (error)
- `#f0e1ff` - Purple (process)
- `#fff4e1` - Beige (data)
---
## Quality Checklist / Checklist Chất lượng
### Before Committing / Trước khi Commit
- [ ] **Content Complete**: All sections filled
- [ ] **Bilingual**: EN and VI content both complete
- [ ] **Mermaid Diagrams**: At least 2-3 diagrams
- [ ] **Diagrams Render**: Tested with mermaid-cli
- [ ] **Code Examples**: From actual source code
- [ ] **File Links**: All links valid (file:///)
- [ ] **Consistent Styling**: Colors and formatting consistent
- [ ] **No Placeholders**: All [brackets] replaced
- [ ] **Tested Commands**: All bash commands tested
- [ ] **Grammar Check**: Both EN and VI proofread
- [ ] **Cross-references**: Links to related docs work
- [ ] **Metadata**: Last updated date, author filled
### EN/VI Parity Check
```bash
# Compare line counts (should be similar)
wc -l docs/en/your-doc.md
wc -l docs/vi/your-doc.md
# Compare diagram counts
grep -c '```mermaid' docs/en/your-doc.md
grep -c '```mermaid' docs/vi/your-doc.md
```
---
## Examples / Ví dụ
### Good Example: Kubernetes Local Guide
**File**: [`docs/vi/guides/kubernetes-local.md`](../vi/guides/kubernetes-local.md)
**Why it's good**:
- ✅ Clear workflow diagram
- ✅ Step-by-step instructions
- ✅ Bilingual content
- ✅ Verification steps
- ✅ Troubleshooting section
- ✅ Tested commands
### Good Example: IAM Service README
**File**: [`services/iam-service/README.md`](../../services/iam-service/README.md)
**Why it's good**:
- ✅ Comprehensive architecture diagrams
- ✅ Clear API documentation
- ✅ Real code examples
- ✅ Well-organized sections
- ✅ Quick reference tables
---
## Getting Help / Nhận Trợ giúp
### Questions / Câu hỏi
1. **Which template to use?** → See decision tree above
2. **How to create diagrams?** → See `MERMAID_GUIDE.md`
3. **How to structure bilingual content?** → See "Bilingual Content Guidelines"
4. **Where to find code examples?** → Look in `_template` or `iam-service`
### Resources / Tài nguyên
- [Mermaid Guide](./MERMAID_GUIDE.md) - Diagram reference
- [Architecture Template](./architecture-doc-template.md) - Template file
- [Guide Template](./guide-doc-template.md) - Template file
- [Skill Template](./skill-pattern-template.md) - Template file
---
**Last Updated**: 2026-01-05
**Maintained by**: Documentation Team

View File

@@ -0,0 +1,228 @@
# [Architecture Name] / [Tên Kiến trúc]
> **EN**: Brief English description of this architectural component or system
> **VI**: Mô tả ngắn gọn bằng tiếng Việt về thành phần kiến trúc hoặc hệ thống này
## Overview Diagram / Sơ đồ Tổng quan
```mermaid
graph TD
A[Component A] --> B[Component B]
B --> C[Component C]
C --> D[Component D]
style A fill:#e1f5ff
style B fill:#fff4e1
style C fill:#f0e1ff
style D fill:#e1ffe1
```
## Architecture Description / Mô tả Kiến trúc
### EN: English Section
Detailed English explanation of the architecture, including:
- Purpose and goals
- Key components
- Design decisions
- Technology choices
- Trade-offs and considerations
### VI: Phần Tiếng Việt
Giải thích chi tiết bằng tiếng Việt về kiến trúc, bao gồm:
- Mục đích và mục tiêu
- Các thành phần chính
- Quyết định thiết kế
- Lựa chọn công nghệ
- Đánh đổi và cân nhắc
## System Context / Bối cảnh Hệ thống
```mermaid
C4Context
title System Context Diagram for [System Name]
Person(user, "User", "System user")
System(system, "System Name", "System description")
System_Ext(external, "External System", "External dependency")
Rel(user, system, "Uses")
Rel(system, external, "Calls", "HTTPS")
```
## Components / Thành phần
### Component A / Thành phần A
**EN**: Description of Component A, its responsibilities, and how it fits into the overall architecture.
**VI**: Mô tả Thành phần A, trách nhiệm của nó và cách nó khớp vào kiến trúc tổng thể.
**Key Features / Tính năng chính**:
- Feature 1 / Tính năng 1
- Feature 2 / Tính năng 2
- Feature 3 / Tính năng 3
**Technologies Used / Công nghệ sử dụng**:
- Technology 1
- Technology 2
**Code Reference / Tham chiếu Code**:
```typescript
// EN: Example code showing how this component is implemented
// VI: Ví dụ code cho thấy cách thành phần này được triển khai
import { ComponentA } from './component-a';
const componentA = new ComponentA({
config: appConfig,
});
```
**File Location**: [`component-a.ts`](file:///path/to/component-a.ts)
### Component B / Thành phần B
(Repeat structure for each major component)
## Data Flow / Luồng Dữ liệu
```mermaid
sequenceDiagram
participant Client
participant API
participant Service
participant Database
Client->>API: Request
API->>Service: Process
Service->>Database: Query
Database-->>Service: Result
Service-->>API: Response
API-->>Client: JSON
```
**EN**: Detailed explanation of the data flow:
1. Step 1: Description
2. Step 2: Description
3. Step 3: Description
**VI**: Giải thích chi tiết về luồng dữ liệu:
1. Bước 1: Mô tả
2. Bước 2: Mô tả
3. Bước 3: Mô tả
## Database Architecture / Kiến trúc Database
```mermaid
erDiagram
Entity1 ||--o{ Entity2 : has
Entity2 ||--o{ Entity3 : contains
Entity1 {
string id PK
string name
datetime createdAt
}
Entity2 {
string id PK
string entity1Id FK
string description
}
```
**EN**: Database schema description, relationships, and design decisions.
**VI**: Mô tả schema database, mối quan hệ và quyết định thiết kế.
## Design Decisions / Quyết định Thiết kế
### Decision 1 / Quyết định 1: [Decision Title]
**EN Context**: Why this decision was needed
**VI Bối cảnh**: Tại sao quyết định này cần thiết
**EN Decision**: What was decided
**VI Quyết định**: Điều gì đã được quyết định
**EN Consequences**: Impact of the decision (positive and negative)
**VI Hậu quả**: Tác động của quyết định (tích cực và tiêu cực)
**EN Alternatives Considered**: Other options that were evaluated
**VI Các lựa chọn thay thế**: Các tùy chọn khác đã được đánh giá
## Performance Characteristics / Đặc điểm Hiệu suất
**EN**: Description of performance expectations and optimizations
**VI**: Mô tả kỳ vọng hiệu suất và tối ưu hóa
| Metric / Chỉ số | Target / Mục tiêu | Notes / Ghi chú |
|------------------|-------------------|-----------------|
| Response Time / Thời gian phản hồi | < 100ms | P95 |
| Throughput / Thông lượng | 1000 req/s | Peak load |
| Memory Usage / Sử dụng RAM | < 512MB | Per instance |
## Security Considerations / Cân nhắc Bảo mật
**EN**: Security features, authentication, authorization, data protection
**VI**: Tính năng bảo mật, xác thực, phân quyền, bảo vệ dữ liệu
- Security feature 1 / Tính năng bảo mật 1
- Security feature 2 / Tính năng bảo mật 2
## Deployment / Triển khai
**EN**: How this architecture is deployed and scaled
**VI**: Cách kiến trúc này được triển khai và mở rộng
```mermaid
graph LR
LB[Load Balancer] --> A[Instance 1]
LB --> B[Instance 2]
LB --> C[Instance 3]
A --> DB[(Database)]
B --> DB
C --> DB
A --> Cache[(Redis)]
B --> Cache
C --> Cache
```
## Monitoring & Observability / Giám sát & Khả năng quan sát
**EN**: How to monitor this architecture, key metrics, alerts
**VI**: Cách giám sát kiến trúc này, các chỉ số chính, cảnh báo
**Key Metrics / Chỉ số chính**:
- Metric 1 / Chỉ số 1
- Metric 2 / Chỉ số 2
**Health Checks / Kiểm tra Sức khỏe**:
- `/health/live` - Liveness probe
- `/health/ready` - Readiness probe
## Related Documentation / Tài liệu Liên quan
- [Related Arch Doc 1](../architecture/related-doc-1.md) - EN: Description / VI: Mô tả
- [Related Guide](../guides/related-guide.md) - EN: Description / VI: Mô tả
- [Related Skill](../skills/related-skill.md) - EN: Description / VI: Mô tả
## References / Tham khảo
- [External Resource 1](https://example.com) - EN: Description
- [External Resource 2](https://example.com) - EN: Description
---
**Last Updated / Cập nhật lần cuối**: YYYY-MM-DD
**Authors / Tác giả**: Your Name
**Reviewers / Người review**: Reviewer Names

257
docs/en/templates/guide.md Normal file
View File

@@ -0,0 +1,257 @@
# [Guide Title] / [Tiêu đề Hướng dẫn]
> **EN**: Brief English description of what this guide covers
> **VI**: Mô tả ngắn gọn bằng tiếng Việt về nội dung hướng dẫn này
## Workflow Diagram / Sơ đồ Quy trình
```mermaid
flowchart LR
Start([Start]) --> Check{Prerequisites<br/>Met?}
Check -->|No| Install[Install Prerequisites]
Check -->|Yes| Step1[Step 1: Action]
Install --> Step1
Step1 --> Step2[Step 2: Action]
Step2 --> Step3[Step 3: Action]
Step3 --> Verify{Verify<br/>Success?}
Verify -->|No| Troubleshoot[Check Troubleshooting]
Verify -->|Yes| End([Complete])
Troubleshoot --> Step1
style Start fill:#e1f5ff
style End fill:#d4edda
style Check fill:#fff3cd
style Verify fill:#fff3cd
```
## Prerequisites / Yêu cầu
### EN: Requirements
Before starting this guide, ensure you have:
- Requirement 1 with specific version (e.g., Node.js 20+)
- Requirement 2
- Requirement 3
### VI: Yêu cầu
Trước khi bắt đầu hướng dẫn này, hãy đảm bảo bạn có:
- Yêu cầu 1 với phiên bản cụ thể (ví dụ: Node.js 20+)
- Yêu cầu 2
- Yêu cầu 3
**Quick Check / Kiểm tra nhanh**:
```bash
# EN: Verify prerequisites / VI: Xác minh yêu cầu
node --version # Should be 20 or higher / Phải là 20 hoặc cao hơn
docker --version # Should be installed / Phải được cài đặt
```
## Overview / Tổng quan
### EN: What You'll Learn
By the end of this guide, you will be able to:
1. Outcome 1
2. Outcome 2
3. Outcome 3
**Estimated Time / Thời gian ước tính**: X minutes
### VI: Bạn Sẽ Học Được Gì
Khi hoàn thành hướng dẫn này, bạn sẽ có thể:
1. Kết quả 1
2. Kết quả 2
3. Kết quả 3
**Estimated Time / Thời gian ước tính**: X phút
## Step-by-Step Guide / Hướng dẫn Từng bước
### Step 1 / Bước 1: [Action Title]
**EN**: English explanation of what this step accomplishes and why it's necessary.
**VI**: Giải thích tiếng Việt về những gì bước này đạt được và tại sao nó cần thiết.
```bash
# EN: Command description / VI: Mô tả lệnh
command-here --flag value
# EN: Expected output / VI: Kết quả mong đợi
Success message or output
```
**Important Notes / Ghi chú quan trọng**:
- Note 1 / Ghi chú 1
- Note 2 / Ghi chú 2
**File to Create / File cần tạo**:
```bash
# EN: Create configuration file / VI: Tạo file cấu hình
touch .env.local
```
**Example Content / Nội dung ví dụ**:
```env
# EN: Environment variables / VI: Biến môi trường
PORT=5000
NODE_ENV=development
DATABASE_URL=postgresql://localhost:5432/mydb
```
### Step 2 / Bước 2: [Action Title]
**EN**: Continue with next step explanation...
**VI**: Tiếp tục với giải thích bước tiếp theo...
```typescript
// EN: Code example for this step
// VI: Ví dụ code cho bước này
import { Example } from './example';
const instance = new Example();
await instance.initialize();
```
**Expected Result / Kết quả mong đợi**:
- ✅ Result 1 / Kết quả 1
- ✅ Result 2 / Kết quả 2
### Step 3 / Bước 3: [Action Title]
(Continue pattern for each step)
## Verification / Xác minh
**EN**: How to verify that everything is working correctly.
**VI**: Cách xác minh mọi thứ đang hoạt động chính xác.
### Quick Test / Kiểm tra nhanh
```bash
# EN: Run verification command / VI: Chạy lệnh xác minh
curl http://localhost:5000/health
# EN: Expected response / VI: Phản hồi mong đợi
{"status":"ok","timestamp":"2024-01-01T00:00:00.000Z"}
```
### Verification Checklist / Danh sách kiểm tra
- [ ] Check 1 / Kiểm tra 1: Description / Mô tả
- [ ] Check 2 / Kiểm tra 2: Description / Mô tả
- [ ] Check 3 / Kiểm tra 3: Description / Mô tả
## Common Issues / Vấn đề Thường gặp
### Issue 1: [Problem Description]
**EN Symptoms**: What you see when this problem occurs
**VI Triệu chứng**: Những gì bạn thấy khi vấn đề này xảy ra
**EN Solution**:
```bash
# Steps to fix
step-1
step-2
```
**VI Giải pháp**:
```bash
# Các bước để sửa
step-1
step-2
```
### Issue 2: [Problem Description]
(Repeat pattern for common issues)
## Troubleshooting Decision Tree / Cây Quyết định Khắc phục
```mermaid
flowchart TD
Problem[Problem Occurs] --> Check1{Check 1:<br/>Condition?}
Check1 -->|Yes| Solution1[Solution 1]
Check1 -->|No| Check2{Check 2:<br/>Condition?}
Check2 -->|Yes| Solution2[Solution 2]
Check2 -->|No| Check3{Check 3:<br/>Condition?}
Check3 -->|Yes| Solution3[Solution 3]
Check3 -->|No| Support[Contact Support]
Solution1 --> Resolved{Resolved?}
Solution2 --> Resolved
Solution3 --> Resolved
Resolved -->|No| Support
Resolved -->|Yes| Success([Success])
```
## Advanced Options / Tùy chọn Nâng cao
**EN**: Optional advanced configurations or alternative approaches.
**VI**: Cấu hình nâng cao tùy chọn hoặc cách tiếp cận thay thế.
### Option 1 / Tùy chọn 1: [Title]
**EN**: When to use this option and how to implement it.
**VI**: Khi nào sử dụng tùy chọn này và cách triển khai.
```bash
# Example command
advanced-command --option
```
## Next Steps / Bước Tiếp theo
**EN**: What to do after completing this guide.
**VI**: Làm gì sau khi hoàn thành hướng dẫn này.
- [ ] Next step 1 / Bước tiếp theo 1: [Related Guide](../guides/related-guide.md)
- [ ] Next step 2 / Bước tiếp theo 2: [Another Guide](../guides/another-guide.md)
- [ ] Next step 3 / Bước tiếp theo 3: [Deep Dive](../skills/deep-dive.md)
## Additional Resources / Tài nguyên Bổ sung
### Related Documentation / Tài liệu Liên quan
- [Related Guide 1](../guides/guide-1.md) - EN: Description / VI: Mô tả
- [Related Architecture](../architecture/arch-doc.md) - EN: Description / VI: Mô tả
- [Related Skill](../skills/skill-doc.md) - EN: Description / VI: Mô tả
### External Resources / Tài nguyên Bên ngoài
- [Official Documentation](https://example.com) - EN: What it covers
- [Tutorial](https://example.com) - EN: Video or article description
## FAQ / Câu hỏi Thường gặp
### EN: Question 1?
Answer 1 in English.
### VI: Câu hỏi 1?
Câu trả lời 1 bằng tiếng Việt.
### EN: Question 2?
Answer 2 in English.
### VI: Câu hỏi 2?
Câu trả lời 2 bằng tiếng Việt.
---
**Last Updated / Cập nhật lần cuối**: YYYY-MM-DD
**Difficulty / Độ khó**: Beginner/Intermediate/Advanced
**Estimated Time / Thời gian ước tính**: X minutes
**Authors / Tác giả**: Your Name

View File

@@ -0,0 +1,539 @@
# Mermaid Diagram Guide / Hướng dẫn Sơ đồ Mermaid
## Overview / Tổng quan
**EN**: 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 / 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 | ⭐⭐⭐⭐ |
---
## 1. Flowcharts / Sơ đồ Luồng
### When to Use / 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:
- 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
flowchart TD
Start([Start]) --> Input[Get Input]
Input --> Check{Valid?}
Check -->|Yes| Process[Process Data]
Check -->|No| Error[Show Error]
Process --> Output[Return Result]
Output --> End([End])
Error --> End
style Start fill:#e1f5ff
style End fill:#d4edda
style Check fill:#fff3cd
style Error fill:#f8d7da
```
**Code**:
````markdown
```mermaid
flowchart TD
Start([Start]) --> Input[Get Input]
Input --> Check{Valid?}
Check -->|Yes| Process[Process Data]
Check -->|No| Error[Show Error]
Process --> Output[Return Result]
Output --> End([End])
Error --> End
style Start fill:#e1f5ff
style End fill:#d4edda
style Check fill:#fff3cd
style Error fill:#f8d7da
```
````
### Advanced Flowchart with Subgraphs
```mermaid
flowchart LR
A[Client Request] --> B{Auth?}
B -->|No| C[401 Unauthorized]
B -->|Yes| D[Process]
subgraph Processing["Request Processing"]
D --> E[Validate Input]
E --> F[Execute Logic]
F --> G[Format Response]
end
G --> H[Return 200 OK]
C --> I[End]
H --> I
style Processing fill:#f0e1ff
```
---
## 2. Sequence Diagrams / Sơ đồ Tuần tự
### When to Use / 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:
- 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
sequenceDiagram
participant Client
participant API
participant Service
participant DB
Client->>API: POST /login
API->>Service: authenticate(credentials)
Service->>DB: findUser(email)
DB-->>Service: user
Service->>Service: verifyPassword()
Service-->>API: JWT token
API-->>Client: 200 OK {token}
```
**Code**:
````markdown
```mermaid
sequenceDiagram
participant Client
participant API
participant Service
participant DB
Client->>API: POST /login
API->>Service: authenticate(credentials)
Service->>DB: findUser(email)
DB-->>Service: user
Service->>Service: verifyPassword()
Service-->>API: JWT token
API-->>Client: 200 OK {token}
```
````
### Advanced with Alt/Opt/Loop
```mermaid
sequenceDiagram
participant Client
participant API
participant Cache
participant DB
Client->>API: GET /users/:id
API->>Cache: get(key)
alt Cache Hit
Cache-->>API: cached data
API-->>Client: 200 OK (from cache)
else Cache Miss
Cache-->>API: null
API->>DB: SELECT * FROM users
DB-->>API: user data
API->>Cache: set(key, data, ttl)
API-->>Client: 200 OK (from DB)
end
```
---
## 3. Class Diagrams / Sơ đồ Class
### When to Use / 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:
- 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
classDiagram
class BaseRepository {
#prisma: PrismaClient
#modelName: string
+findById(id: string) T
+findAll(options: QueryOptions) T[]
+create(data: CreateDto) T
+update(id: string, data: UpdateDto) T
+delete(id: string) void
}
class UserRepository {
+findByEmail(email: string) User
+findByUsername(username: string) User
}
class FeatureRepository {
+findByName(name: string) Feature
+toggleStatus(id: string) Feature
}
BaseRepository <|-- UserRepository
BaseRepository <|-- FeatureRepository
```
---
## 4. Graph Diagrams / Sơ đồ Graph
### When to Use / 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:
- 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
graph TD
Client[Web Client] --> Gateway[Traefik Gateway]
Gateway --> Auth[Auth Service]
Gateway --> IAM[IAM Service]
Gateway --> User[User Service]
Auth --> DB[(PostgreSQL)]
IAM --> DB
User --> DB
Auth --> Cache[(Redis)]
IAM --> Cache
User --> Cache
style Gateway fill:#e1f5ff
style DB fill:#f0e1ff
style Cache fill:#fff4e1
```
### Data Flow
```mermaid
graph LR
Input[User Input] --> Validation[Zod Validation]
Validation --> Controller[Controller]
Controller --> Service[Service Layer]
Service --> Repository[Repository]
Repository --> Prisma[Prisma ORM]
Prisma --> DB[(Database)]
Service --> Cache[Cache Service]
Cache --> Redis[(Redis)]
style Validation fill:#d4edda
style Service fill:#e1f5ff
style Cache fill:#fff4e1
```
---
## 5. ER Diagrams / Sơ đồ ER
### When to Use / 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:
- 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
erDiagram
User ||--o{ Session : has
User ||--o{ RefreshToken : has
User ||--o{ UserRole : has
Role ||--o{ UserRole : has
Role ||--o{ RolePermission : has
Permission ||--o{ RolePermission : has
User {
string id PK
string email UK
string passwordHash
boolean mfaEnabled
datetime createdAt
datetime updatedAt
}
Session {
string id PK
string userId FK
string token UK
string deviceId
string ipAddress
datetime expiresAt
}
Role {
string id PK
string name UK
string description
datetime createdAt
}
Permission {
string id PK
string code UK
string resource
string action
string scope
}
```
---
## 6. Gantt Charts / Biểu đồ Gantt
### When to Use / 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:
- Timeline dự án
- Các giai đoạn triển khai
- Lịch trình migration
- Kế hoạch deployment
### Project Timeline
```mermaid
gantt
title Documentation Update Project Timeline
dateFormat YYYY-MM-DD
section Phase 1
Analysis & Research :done, p1, 2024-01-01, 1d
section Phase 2
Templates & Strategy :active, p2, 2024-01-02, 0.5d
section Phase 3
High Priority Docs :p3, 2024-01-03, 2d
section Phase 4
Remaining Docs :p4, 2024-01-05, 3d
section Phase 5
QA & Verification :p5, 2024-01-08, 1d
```
---
## 7. C4 Diagrams / Sơ đồ C4
### When to Use / 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:
- 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
C4Context
title System Context Diagram for IAM System
Person(user, "User", "System user needing authentication")
Person(admin, "Admin", "System administrator")
System(iam, "IAM System", "Identity and Access Management")
System_Ext(email, "Email Service", "SendGrid/AWS SES")
System_Ext(oauth, "OAuth Providers", "Google, Facebook, GitHub")
Rel(user, iam, "Authenticates with", "HTTPS")
Rel(admin, iam, "Manages users and permissions", "HTTPS")
Rel(iam, email, "Sends emails", "SMTP/API")
Rel(iam, oauth, "OAuth login", "OAuth 2.0")
```
---
## Styling Tips / Mẹo Styling
### Color Palette / Bảng màu
```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"]
style A fill:#e1f5ff
style B fill:#fff4e1
style C fill:#d4edda
style D fill:#fff3cd
style E fill:#f8d7da
style F fill:#f0e1ff
```
### Style Syntax
```markdown
style NodeId fill:#colorcode,stroke:#bordercolor,stroke-width:2px
```
**Examples**:
```markdown
style Start fill:#e1f5ff
style Error fill:#f8d7da
style Process fill:#d4edda,stroke:#28a745,stroke-width:2px
```
---
## Best Practices / Best Practices
### 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
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
---
## Common Pitfalls / Lỗi Thường gặp
### ❌ Too Complex
```mermaid
graph TD
A --> B
A --> C
B --> D
B --> E
C --> F
C --> G
D --> H
E --> H
F --> I
G --> I
H --> J
I --> J
```
### ✅ Simplified with Subgraphs
```mermaid
graph TD
A[Start] --> B[Process A]
B --> C[Process B]
subgraph "Detailed Processing"
C --> D[Step 1]
D --> E[Step 2]
end
E --> F[End]
```
---
## Testing Diagrams / Test Sơ đồ
**EN**: Always test your diagrams before committing:
**VI**: Luôn test sơ đồ trước khi commit:
```bash
# Install mermaid-cli
npm install -g @mermaid-js/mermaid-cli
# Test render
mmdc -i your-doc.md -o test-output.svg
# Check for errors
echo $? # Should be 0 if successful
```
---
## Resources / Tài nguyên
- [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
---
**Last Updated**: 2026-01-05

View File

@@ -0,0 +1,475 @@
# [Pattern Name] Pattern / Pattern [Tên Pattern]
> **EN**: Brief English description of when and why to use this pattern
> **VI**: Mô tả ngắn gọn bằng tiếng Việt về khi nào và tại sao sử dụng pattern này
## Pattern Overview / Tổng quan Pattern
```mermaid
graph LR
Input[Input/Request] --> Process[Pattern Process]
Process --> Output[Output/Result]
subgraph Pattern["Pattern Implementation"]
Process --> Step1[Step 1]
Step1 --> Step2[Step 2]
Step2 --> Step3[Step 3]
end
style Input fill:#e1f5ff
style Output fill:#d4edda
style Pattern fill:#f0e1ff
```
## When to Use / Khi nào sử dụng
### EN: Use this pattern when
- Scenario 1: Description of when this pattern is beneficial
- Scenario 2: Another use case
- Scenario 3: Additional context
**DO use this pattern for**:
- ✅ Use case 1
- ✅ Use case 2
**DON'T use this pattern for**:
- ❌ Anti-pattern 1
- ❌ Anti-pattern 2
### VI: Sử dụng pattern này khi
- Tình huống 1: Mô tả khi pattern này có lợi
- Tình huống 2: Trường hợp sử dụng khác
- Tình huống 3: Bối cảnh bổ sung
**NÊN sử dụng pattern này cho**:
- ✅ Trường hợp 1
- ✅ Trường hợp 2
**KHÔNG NÊN sử dụng pattern này cho**:
- ❌ Anti-pattern 1
- ❌ Anti-pattern 2
## Core Concepts / Khái niệm Cốt lõi
### EN: Key Principles
1. **Principle 1**: Description of the first core principle
2. **Principle 2**: Description of the second core principle
3. **Principle 3**: Description of the third core principle
### VI: Nguyên tắc Chính
1. **Nguyên tắc 1**: Mô tả nguyên tắc cốt lõi đầu tiên
2. **Nguyên tắc 2**: Mô tả nguyên tắc cốt lõi thứ hai
3. **Nguyên tắc 3**: Mô tả nguyên tắc cốt lõi thứ ba
## Implementation / Triển khai
### Basic Implementation / Triển khai Cơ bản
**EN**: Step-by-step explanation of how to implement this pattern.
**VI**: Giải thích từng bước về cách triển khai pattern này.
```typescript
// EN: Basic implementation example
// VI: Ví dụ triển khai cơ bản
/**
* EN: Pattern implementation class
* VI: Class triển khai pattern
*/
export class ExamplePattern {
/**
* EN: Constructor with dependencies
* VI: Constructor với các dependencies
*/
constructor(
private dependency1: Dependency1,
private dependency2: Dependency2
) {}
/**
* EN: Core method implementing the pattern
* VI: Phương thức cốt lõi triển khai pattern
*
* @param input - EN: Input data / VI: Dữ liệu đầu vào
* @returns EN: Processed result / VI: Kết quả đã xử lý
*/
async execute(input: InputType): Promise<OutputType> {
// EN: Step 1: Validate input
// VI: Bước 1: Validate đầu vào
this.validateInput(input);
// EN: Step 2: Process
// VI: Bước 2: Xử lý
const processed = await this.process(input);
// EN: Step 3: Return result
// VI: Bước 3: Trả về kết quả
return this.formatOutput(processed);
}
private validateInput(input: InputType): void {
// EN: Validation logic
// VI: Logic validation
if (!input) {
throw new Error('Input is required / Đầu vào là bắt buộc');
}
}
private async process(input: InputType): Promise<ProcessedType> {
// EN: Core business logic
// VI: Logic nghiệp vụ cốt lõi
return await this.dependency1.transform(input);
}
private formatOutput(processed: ProcessedType): OutputType {
// EN: Format for output
// VI: Định dạng cho đầu ra
return {
success: true,
data: processed,
};
}
}
```
**File Location / Vị trí File**:
- **Template**: [`_template/src/modules/example/example.pattern.ts`](file:///Users/velikho/Desktop/WORKING/Base/services/_template/src/modules/example/example.pattern.ts)
- **Production**: [`iam-service/src/modules/example/example.pattern.ts`](file:///Users/velikho/Desktop/WORKING/Base/services/iam-service/src/modules/example/example.pattern.ts)
### Advanced Implementation / Triển khai Nâng cao
**EN**: More complex implementation with additional features.
**VI**: Triển khai phức tạp hơn với các tính năng bổ sung.
```typescript
// EN: Advanced implementation with caching and error handling
// VI: Triển khai nâng cao với caching và xử lý lỗi
export class AdvancedExamplePattern extends ExamplePattern {
constructor(
dependency1: Dependency1,
dependency2: Dependency2,
private cache: CacheService,
private logger: Logger
) {
super(dependency1, dependency2);
}
async execute(input: InputType): Promise<OutputType> {
// EN: Try cache first
// VI: Thử cache trước
const cacheKey = this.getCacheKey(input);
const cached = await this.cache.get<OutputType>(cacheKey);
if (cached) {
this.logger.info('Cache hit', { key: cacheKey });
return cached;
}
try {
// EN: Execute pattern logic
// VI: Thực thi logic pattern
const result = await super.execute(input);
// EN: Cache result
// VI: Cache kết quả
await this.cache.set(cacheKey, result, 300); // 5 minutes
return result;
} catch (error) {
// EN: Error handling
// VI: Xử lý lỗi
this.logger.error('Pattern execution failed', { error, input });
throw new PatternExecutionError('Execution failed', { cause: error });
}
}
private getCacheKey(input: InputType): string {
return `pattern:example:${JSON.stringify(input)}`;
}
}
```
## Pattern Diagram / Sơ đồ Pattern
### Class Structure / Cấu trúc Class
```mermaid
classDiagram
class ExamplePattern {
-dependency1: Dependency1
-dependency2: Dependency2
+execute(input: InputType): OutputType
-validateInput(input: InputType): void
-process(input: InputType): ProcessedType
-formatOutput(processed: ProcessedType): OutputType
}
class AdvancedExamplePattern {
-cache: CacheService
-logger: Logger
+execute(input: InputType): OutputType
-getCacheKey(input: InputType): string
}
class Dependency1 {
+transform(input: InputType): ProcessedType
}
class CacheService {
+get(key: string): Promise~any~
+set(key: string, value: any, ttl: number): Promise~void~
}
ExamplePattern <|-- AdvancedExamplePattern
ExamplePattern --> Dependency1
AdvancedExamplePattern --> CacheService
```
### Sequence Flow / Luồng Tuần tự
```mermaid
sequenceDiagram
participant Client
participant Pattern as ExamplePattern
participant Dep1 as Dependency1
participant Cache as CacheService
Client->>Pattern: execute(input)
Pattern->>Cache: get(cacheKey)
Cache-->>Pattern: null (cache miss)
Pattern->>Pattern: validateInput(input)
Pattern->>Dep1: transform(input)
Dep1-->>Pattern: processed
Pattern->>Pattern: formatOutput(processed)
Pattern->>Cache: set(cacheKey, result, ttl)
Cache-->>Pattern: void
Pattern-->>Client: result
```
## Usage Examples / Ví dụ Sử dụng
### Example 1 / Ví dụ 1: Basic Usage
**EN**: Basic usage scenario with explanation.
**VI**: Tình huống sử dụng cơ bản với giải thích.
```typescript
// EN: Setup
// VI: Thiết lập
const dependency1 = new Dependency1();
const dependency2 = new Dependency2();
const pattern = new ExamplePattern(dependency1, dependency2);
// EN: Execute pattern
// VI: Thực thi pattern
const input: InputType = {
id: '123',
data: 'example',
};
const result = await pattern.execute(input);
console.log(result);
// EN: Output / VI: Kết quả:
// { success: true, data: { ... } }
```
### Example 2 / Ví dụ 2: Advanced Usage with Caching
**EN**: Advanced usage with caching enabled.
**VI**: Sử dụng nâng cao với caching được bật.
```typescript
// EN: Setup with additional dependencies
// VI: Thiết lập với các dependencies bổ sung
const cache = new CacheService();
const logger = new Logger();
const pattern = new AdvancedExamplePattern(
dependency1,
dependency2,
cache,
logger
);
// EN: First call (cache miss)
// VI: Lần gọi đầu tiên (cache miss)
const result1 = await pattern.execute(input);
// EN: Second call (cache hit)
// VI: Lần gọi thứ hai (cache hit)
const result2 = await pattern.execute(input); // Returns cached result
```
## Best Practices / Best Practices
### EN: Recommended Practices
1. **Practice 1**: Description of best practice with reasoning
2. **Practice 2**: Another important guideline
3. **Practice 3**: Additional recommendation
**Configuration / Cấu hình**:
```typescript
const config = {
timeout: 5000,
retries: 3,
cacheTime: 300, // 5 minutes
};
```
### VI: Thực hành Được đề xuất
1. **Nguyên tắc 1**: Mô tả best practice với lý do
2. **Nguyên tắc 2**: Hướng dẫn quan trọng khác
3. **Nguyên tắc 3**: Khuyến nghị bổ sung
## Common Mistakes / Lỗi Thường gặp
### EN: Mistakes to Avoid
#### Mistake 1 / Lỗi 1: [Description]
```typescript
// ❌ BAD: Incorrect implementation
const result = await pattern.execute(null); // Will throw error
```
```typescript
// ✅ GOOD: Correct implementation
if (input) {
const result = await pattern.execute(input);
}
```
**EN Why**: Explanation of why the first approach is bad and the second is good.
**VI Tại sao**: Giải thích tại sao cách tiếp cận đầu tiên là không tốt và cách thứ hai là tốt.
#### Mistake 2 / Lỗi 2: [Description]
(Repeat pattern for each common mistake)
## Performance Considerations / Cân nhắc Hiệu suất
**EN**: Performance characteristics and optimization tips.
**VI**: Đặc điểm hiệu suất và mẹo tối ưu hóa.
| Aspect / Khía cạnh | Impact / Tác động | Mitigation / Giảm thiểu |
|---------------------|-------------------|-------------------------|
| Memory usage / Sử dụng RAM | Medium / Trung bình | Use caching strategically / Sử dụng caching có chiến lược |
| CPU usage / Sử dụng CPU | Low / Thấp | N/A |
| I/O operations / Thao tác I/O | High / Cao | Implement connection pooling / Triển khai connection pooling |
## Testing / Kiểm thử
### Unit Test Example / Ví dụ Unit Test
```typescript
// EN: Unit test for the pattern
// VI: Unit test cho pattern
describe('ExamplePattern', () => {
let pattern: ExamplePattern;
let mockDep1: jest.Mocked<Dependency1>;
let mockDep2: jest.Mocked<Dependency2>;
beforeEach(() => {
mockDep1 = {
transform: jest.fn(),
} as any;
mockDep2 = {} as any;
pattern = new ExamplePattern(mockDep1, mockDep2);
});
it('should execute successfully', async () => {
// EN: Arrange
// VI: Chuẩn bị
const input = { id: '123', data: 'test' };
const expectedProcessed = { transformed: true };
mockDep1.transform.mockResolvedValue(expectedProcessed);
// EN: Act
// VI: Thực thi
const result = await pattern.execute(input);
// EN: Assert
// VI: Kiểm tra
expect(result.success).toBe(true);
expect(result.data).toEqual(expectedProcessed);
expect(mockDep1.transform).toHaveBeenCalledWith(input);
});
it('should throw error for invalid input', async () => {
// EN: Expect error for null input
// VI: Mong đợi lỗi cho đầu vào null
await expect(pattern.execute(null as any))
.rejects
.toThrow('Input is required');
});
});
```
## Related Patterns / Patterns Liên quan
**EN**: Other patterns that complement or relate to this one.
**VI**: Các patterns khác bổ sung hoặc liên quan đến pattern này.
- [Related Pattern 1](./related-pattern-1.md) - EN: How it relates / VI: Cách nó liên quan
- [Related Pattern 2](./related-pattern-2.md) - EN: Comparison / VI: So sánh
- [Alternative Pattern](./alternative-pattern.md) - EN: When to use instead / VI: Khi nào sử dụng thay thế
## Real-World Examples / Ví dụ Thực tế
**EN**: Examples of this pattern used in the codebase.
**VI**: Ví dụ về pattern này được sử dụng trong codebase.
### Example from IAM Service
**File**: [`iam-service/src/modules/rbac/rbac.service.ts`](file:///Users/velikho/Desktop/WORKING/Base/services/iam-service/src/modules/rbac/rbac.service.ts)
```typescript
// EN: Real implementation from IAM service
// VI: Triển khai thực tế từ IAM service
export class RBACService implements ExamplePattern {
// ... implementation
}
```
## Additional Resources / Tài nguyên Bổ sung
### EN: Related Documentation
- [API Design Guide](../api-design.md) - How this pattern fits into API design
- [Error Handling](../error-handling-patterns.md) - Error handling for this pattern
- [Testing Guide](../testing-patterns.md) - Testing strategies
### VI: Tài liệu Liên quan
- [Hướng dẫn Thiết kế API](../api-design.md) - Pattern này khớp với thiết kế API như thế nào
- [Xử lý Lỗi](../error-handling-patterns.md) - Xử lý lỗi cho pattern này
- [Hướng dẫn Kiểm thử](../testing-patterns.md) - Chiến lược kiểm thử
### External Resources / Tài nguyên Bên ngoài
- [Design Patterns Book](https://example.com) - Classic reference
- [Blog Post](https://example.com) - Modern interpretation
---
**Last Updated / Cập nhật lần cuối**: YYYY-MM-DD
**Complexity / Độ phức tạp**: Beginner/Intermediate/Advanced
**Category / Danh mục**: [Category Name]
**Authors / Tác giả**: Your Name

204
docs/vi/templates/README.md Normal file
View File

@@ -0,0 +1,204 @@
# Hướng dẫn Sử dụng Templates Tài liệu
> **Mục đích**: Hướng dẫn sử dụng các templates tài liệu để tạo documentation nhất quán cho project GoodGo
## Templates Có sẵn
### 1. Architecture Template - [`architecture.md`](./architecture.md)
**Sử dụng khi**: Tài liệu hóa kiến trúc hệ thống, thành phần, hoặc design decision
**Bao gồm**:
- Sơ đồ tổng quan (Mermaid diagrams)
- Mô tả thành phần chi tiết
- Quyết định thiết kế
- Database architecture
- Performance characteristics
- Security considerations
- Deployment strategy
**Ví dụ**: [`system-design.md`](../architecture/system-design.md)
### 2. Guide Template - [`guide.md`](./guide.md)
**Sử dụng khi**: Tạo hướng dẫn từng bước (getting started, deployment, troubleshooting)
**Bao gồm**:
- Workflow diagram
- Prerequisites
- Hướng dẫn từng bước chi tiết
- Verification steps
- Common issues & troubleshooting
- FAQ section
**Ví dụ**: Hướng dẫn deployment, local development
### 3. Skill/Pattern Template - [`skill-pattern.md`](./skill-pattern.md)
**Sử dụng khi**: Tài liệu hóa coding patterns, best practices, hoặc kỹ thuật
**Bao gồm**:
- Pattern overview
- When to use / when not to use
- Implementation examples
- Class diagrams
- Best practices
- Common mistakes
- Testing examples
**Ví dụ**: Repository pattern, RBAC pattern
## Quick Start
### Bước 1: Chọn Template phù hợp
Xác định loại tài liệu bạn cần tạo:
- **Kiến trúc** → `architecture.md`
- **Hướng dẫn** → `guide.md`
- **Pattern/Skill** → `skill-pattern.md`
### Bước 2: Copy Template
```bash
# Ví dụ: Tạo architecture document mới
cp docs/vi/templates/architecture.md docs/vi/architecture/ten-kien-truc-moi.md
```
### Bước 3: Thay thế Placeholders
Thay thế các placeholder trong template:
- `[Tên Kiến trúc]` → Tên thực của document
- `[Tiêu đề]` → Tiêu đề sections
- `[Mô tả]` → Nội dung thực tế
### Bước 4: Tùy chỉnh Nội dung
- Điền vào tất cả sections
- Tạo Mermaid diagrams (xem [mermaid-guide.md](./mermaid-guide.md))
- Thêm code examples với comments song ngữ
- Cập nhật metadata (Last Updated, Authors)
### Bước 5: Review Checklist
- [ ] Tất cả placeholders đã được thay thế
- [ ] Mermaid diagrams hiển thị đúng
- [ ] Code examples có syntax highlighting
- [ ] Có đầy đủ nội dung tiếng Việt
- [ ] Links hoạt động chính xác
- [ ] Metadata được cập nhật
## Quy ước Viết Tài liệu
### Ngôn ngữ
**Tiếng Việt**:
- Sử dụng 100% tiếng Việt cho tất cả nội dung
- Giữ thuật ngữ kỹ thuật bằng tiếng Anh khi cần (Docker, Kubernetes, etc.)
- Code examples vẫn giữ nguyên tiếng Anh
**Code Comments**:
```typescript
// Ví dụ code với comments tiếng Việt
export class Example {
/**
* Khởi tạo service với dependencies
*/
constructor(private dependency: Dependency) {}
}
```
### Mermaid Diagrams
Tham khảo [Hướng dẫn Mermaid](./mermaid-guide.md) để biết:
- Các loại diagrams có sẵn
- Color scheme chuẩn
- Best practices
- Ví dụ cho mỗi loại diagram
**Color Palette**:
```
#e1f5ff - Xanh nhạt (Primary actions)
#fff4e1 - Vàng nhạt (Data/Cache)
#f0e1ff - Tím nhạt (Processing)
#d4edda - Xanh lá nhạt (Success)
#f8d7da - Đỏ nhạt (Errors)
#fff3cd - Vàng (Warnings)
```
### File Organization
```
docs/vi/
├── templates/ # Templates (file này)
├── architecture/ # Architecture docs
├── guides/ # How-to guides
└── skills/ # Patterns & skills
```
## Best Practices
### 1. Viết Concise và Clear
- Ngắn gọn, súc tích
- Một ý chính mỗi paragraph
- Sử dụng bullet points cho lists
### 2. Visual First
- Thêm diagrams cho mọi concepts phức tạp
- Sử dụng code examples với output
- Screenshots khi cần (UI, browser)
### 3. Maintainability
- Link tới related documentation
- Cập nhật "Last Updated" date
- Ghi rõ version nếu có
### 4. Accessibility
- Alt text cho images
- Descriptive link text (không dùng "click here")
- Headings có cấu trúc logic
## Mẹo Hữu ích
### Tạo Diagrams nhanh
```bash
# Sử dụng Mermaid Live Editor
# https://mermaid.live/
```
### Validate Markdown
```bash
# Cài đặt markdownlint
pnpm add -g markdownlint-cli
# Check markdown files
markdownlint docs/vi/**/*.md
```
### Link Format
```markdown
# Relative links (ưu tiên)
[Architecture](../architecture/system-design.md)
# Với line numbers (file links)
[Code Example](file:///path/to/file.ts#L10-L20)
```
## Troubleshooting
### Mermaid không hiển thị?
1. Kiểm tra syntax với [Mermaid Live Editor](https://mermaid.live/)
2. Đảm bảo code block có `mermaid` language tag
3. Không có ký tự đặc biệt chưa escape
---
**Cập nhật lần cuối**: 2024-01-15
**Tác giả**: GoodGo Documentation Team

View File

@@ -0,0 +1,190 @@
# [Tên Kiến trúc]
> **Mô tả**: Mô tả ngắn gọn bằng tiếng Việt về thành phần kiến trúc hoặc hệ thống này
## Sơ đồ Tổng quan
```mermaid
graph TD
A[Thành phần A] --> B[Thành phần B]
B --> C[Thành phần C]
C --> D[Thành phần D]
style A fill:#e1f5ff
style B fill:#fff4e1
style C fill:#f0e1ff
style D fill:#e1ffe1
```
## Mô tả Kiến trúc
Giải thích chi tiết về kiến trúc, bao gồm:
- Mục đích và mục tiêu
- Các thành phần chính
- Quyết định thiết kế
- Lựa chọn công nghệ
- Đánh đổi và cân nhắc
## Bối cảnh Hệ thống
```mermaid
C4Context
title Sơ đồ Bối cảnh Hệ thống cho [Tên Hệ thống]
Person(user, "Người dùng", "Người dùng hệ thống")
System(system, "Tên Hệ thống", "Mô tả hệ thống")
System_Ext(external, "Hệ thống Bên ngoài", "Phụ thuộc bên ngoài")
Rel(user, system, "Sử dụng")
Rel(system, external, "Gọi", "HTTPS")
```
## Thành phần
### Thành phần A
**Mô tả**: Mô tả Thành phần A, trách nhiệm của nó và cách nó khớp vào kiến trúc tổng thể.
**Tính năng chính**:
- Tính năng 1
- Tính năng 2
- Tính năng 3
**Công nghệ sử dụng**:
- Công nghệ 1
- Công nghệ 2
**Tham chiếu Code**:
```typescript
// Ví dụ code cho thấy cách thành phần này được triển khai
import { ComponentA } from './component-a';
const componentA = new ComponentA({
config: appConfig,
});
```
**Vị trí File**: [`component-a.ts`](file:///path/to/component-a.ts)
### Thành phần B
(Lặp lại cấu trúc cho mỗi thành phần chính)
## Luồng Dữ liệu
```mermaid
sequenceDiagram
participant Client as Khách hàng
participant API
participant Service as Dịch vụ
participant Database as Cơ sở dữ liệu
Client->>API: Yêu cầu
API->>Service: Xử lý
Service->>Database: Truy vấn
Database-->>Service: Kết quả
Service-->>API: Phản hồi
API-->>Client: JSON
```
**Giải thích chi tiết về luồng dữ liệu**:
1. Bước 1: Mô tả
2. Bước 2: Mô tả
3. Bước 3: Mô tả
## Kiến trúc Database
```mermaid
erDiagram
Entity1 ||--o{ Entity2 : has
Entity2 ||--o{ Entity3 : contains
Entity1 {
string id PK
string name
datetime createdAt
}
Entity2 {
string id PK
string entity1Id FK
string description
}
```
**Mô tả**: Mô tả schema database, mối quan hệ và quyết định thiết kế.
## Quyết định Thiết kế
### Quyết định 1: [Tiêu đề Quyết định]
**Bối cảnh**: Tại sao quyết định này cần thiết
**Quyết định**: Điều gì đã được quyết định
**Hậu quả**: Tác động của quyết định (tích cực và tiêu cực)
**Các lựa chọn thay thế**: Các tùy chọn khác đã được đánh giá
## Đặc điểm Hiệu suất
**Mô tả**: Mô tả kỳ vọng hiệu suất và tối ưu hóa
| Chỉ số | Mục tiêu | Ghi chú |
|---------|----------|---------|
| Thời gian phản hồi | < 100ms | P95 |
| Thông lượng | 1000 req/s | Peak load |
| Sử dụng RAM | < 512MB | Mỗi instance |
## Cân nhắc Bảo mật
**Mô tả**: Tính năng bảo mật, xác thực, phân quyền, bảo vệ dữ liệu
- Tính năng bảo mật 1
- Tính năng bảo mật 2
## Triển khai
**Mô tả**: Cách kiến trúc này được triển khai và mở rộng
```mermaid
graph LR
LB[Load Balancer] --> A[Instance 1]
LB --> B[Instance 2]
LB --> C[Instance 3]
A --> DB[(Database)]
B --> DB
C --> DB
A --> Cache[(Redis)]
B --> Cache
C --> Cache
```
## Giám sát & Khả năng quan sát
**Mô tả**: Cách giám sát kiến trúc này, các chỉ số chính, cảnh báo
**Chỉ số chính**:
- Chỉ số 1
- Chỉ số 2
**Kiểm tra Sức khỏe**:
- `/health/live` - Liveness probe
- `/health/ready` - Readiness probe
## Tài liệu Liên quan
- [Tài liệu Kiến trúc Liên quan 1](../architecture/related-doc-1.md) - Mô tả
- [Hướng dẫn Liên quan](../guides/related-guide.md) - Mô tả
- [Skill Liên quan](../skills/related-skill.md) - Mô tả
## Tham khảo
- [Tài nguyên Bên ngoài 1](https://example.com) - Mô tả
- [Tài nguyên Bên ngoài 2](https://example.com) - Mô tả
---
**Cập nhật lần cuối**: YYYY-MM-DD
**Tác giả**: Tên của bạn
**Người review**: Tên người review

208
docs/vi/templates/guide.md Normal file
View File

@@ -0,0 +1,208 @@
# [Tiêu đề Hướng dẫn]
> **Mô tả**: Mô tả ngắn gọn về nội dung hướng dẫn này
## Sơ đồ Quy trình
```mermaid
flowchart LR
Start([Bắt đầu]) --> Check{Yêu cầu<br/>Đáp ứng?}
Check -->|Không| Install[Cài đặt Yêu cầu]
Check -->|Có| Step1[Bước 1: Hành động]
Install --> Step1
Step1 --> Step2[Bước 2: Hành động]
Step2 --> Step3[Bước 3: Hành động]
Step3 --> Verify{Xác minh<br/>Thành công?}
Verify -->|Không| Troubleshoot[Xem Khắc phục sự cố]
Verify -->|Có| End([Hoàn thành])
Troubleshoot --> Step1
style Start fill:#e1f5ff
style End fill:#d4edda
style Check fill:#fff3cd
style Verify fill:#fff3cd
```
## Yêu cầu
Trước khi bắt đầu hướng dẫn này, hãy đảm bảo bạn có:
- Yêu cầu 1 với phiên bản cụ thể (ví dụ: Node.js 20+)
- Yêu cầu 2
- Yêu cầu 3
**Kiểm tra nhanh**:
```bash
# Xác minh yêu cầu
node --version # Phải là 20 hoặc cao hơn
docker --version # Phải được cài đặt
```
## Tổng quan
### Bạn Sẽ Học Được Gì
Khi hoàn thành hướng dẫn này, bạn sẽ có thể:
1. Kết quả 1
2. Kết quả 2
3. Kết quả 3
**Thời gian ước tính**: X phút
## Hướng dẫn Từng bước
### Bước 1: [Tiêu đề Hành động]
**Mô tả**: Giải thích về những gì bước này đạt được và tại sao nó cần thiết.
```bash
# Mô tả lệnh
command-here --flag value
# Kết quả mong đợi
Thông báo thành công hoặc kết quả
```
**Ghi chú quan trọng**:
- Ghi chú 1
- Ghi chú 2
**File cần tạo**:
```bash
# Tạo file cấu hình
touch .env.local
```
**Nội dung ví dụ**:
```env
# Biến môi trường
PORT=5000
NODE_ENV=development
DATABASE_URL=postgresql://localhost:5432/mydb
```
### Bước 2: [Tiêu đề Hành động]
**Mô tả**: Tiếp tục với giải thích bước tiếp theo...
```typescript
// Ví dụ code cho bước này
import { Example } from './example';
const instance = new Example();
await instance.initialize();
```
**Kết quả mong đợi**:
- ✅ Kết quả 1
- ✅ Kết quả 2
### Bước 3: [Tiêu đề Hành động]
(Tiếp tục mẫu cho mỗi bước)
## Xác minh
**Mô tả**: Cách xác minh mọi thứ đang hoạt động chính xác.
### Kiểm tra nhanh
```bash
# Chạy lệnh xác minh
curl http://localhost:5000/health
# Phản hồi mong đợi
{"status":"ok","timestamp":"2024-01-01T00:00:00.000Z"}
```
### Danh sách kiểm tra
- [ ] Kiểm tra 1: Mô tả
- [ ] Kiểm tra 2: Mô tả
- [ ] Kiểm tra 3: Mô tả
## Vấn đề Thường gặp
### Vấn đề 1: [Mô tả Vấn đề]
**Triệu chứng**: Những gì bạn thấy khi vấn đề này xảy ra
**Giải pháp**:
```bash
# Các bước để sửa
step-1
step-2
```
### Vấn đề 2: [Mô tả Vấn đề]
(Lặp lại mẫu cho các vấn đề thường gặp)
## Cây Quyết định Khắc phục
```mermaid
flowchart TD
Problem[Xảy ra Vấn đề] --> Check1{Kiểm tra 1:<br/>Điều kiện?}
Check1 -->|Có| Solution1[Giải pháp 1]
Check1 -->|Không| Check2{Kiểm tra 2:<br/>Điều kiện?}
Check2 -->|Có| Solution2[Giải pháp 2]
Check2 -->|Không| Check3{Kiểm tra 3:<br/>Điều kiện?}
Check3 -->|Có| Solution3[Giải pháp 3]
Check3 -->|Không| Support[Liên hệ Hỗ trợ]
Solution1 --> Resolved{Đã giải quyết?}
Solution2 --> Resolved
Solution3 --> Resolved
Resolved -->|Không| Support
Resolved -->|Có| Success([Thành công])
```
## Tùy chọn Nâng cao
**Mô tả**: Cấu hình nâng cao tùy chọn hoặc cách tiếp cận thay thế.
### Tùy chọn 1: [Tiêu đề]
**Mô tả**: Khi nào sử dụng tùy chọn này và cách triển khai.
```bash
# Lệnh ví dụ
advanced-command --option
```
## Bước Tiếp theo
**Mô tả**: Làm gì sau khi hoàn thành hướng dẫn này.
- [ ] Bước tiếp theo 1: [Hướng dẫn Liên quan](../guides/related-guide.md)
- [ ] Bước tiếp theo 2: [Hướng dẫn Khác](../guides/another-guide.md)
- [ ] Bước tiếp theo 3: [Tìm hiểu Sâu](../skills/deep-dive.md)
## Tài nguyên Bổ sung
### Tài liệu Liên quan
- [Hướng dẫn Liên quan 1](../guides/guide-1.md) - Mô tả
- [Kiến trúc Liên quan](../architecture/arch-doc.md) - Mô tả
- [Skill Liên quan](../skills/skill-doc.md) - Mô tả
### Tài nguyên Bên ngoài
- [Tài liệu Chính thức](https://example.com) - Nội dung bao gồm
- [Bài hướng dẫn](https://example.com) - Mô tả video hoặc bài viết
## Câu hỏi Thường gặp
### Câu hỏi 1?
Câu trả lời 1.
### Câu hỏi 2?
Câu trả lời 2.
---
**Cập nhật lần cuối**: YYYY-MM-DD
**Độ khó**: Beginner/Intermediate/Advanced
**Thời gian ước tính**: X phút
**Tác giả**: Tên của bạn

View File

@@ -0,0 +1,539 @@
# Mermaid Diagram Guide / Hướng dẫn Sơ đồ Mermaid
## Overview / Tổng quan
**EN**: 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 / 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 | ⭐⭐⭐⭐ |
---
## 1. Flowcharts / Sơ đồ Luồng
### When to Use / 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:
- 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
flowchart TD
Start([Start]) --> Input[Get Input]
Input --> Check{Valid?}
Check -->|Yes| Process[Process Data]
Check -->|No| Error[Show Error]
Process --> Output[Return Result]
Output --> End([End])
Error --> End
style Start fill:#e1f5ff
style End fill:#d4edda
style Check fill:#fff3cd
style Error fill:#f8d7da
```
**Code**:
````markdown
```mermaid
flowchart TD
Start([Start]) --> Input[Get Input]
Input --> Check{Valid?}
Check -->|Yes| Process[Process Data]
Check -->|No| Error[Show Error]
Process --> Output[Return Result]
Output --> End([End])
Error --> End
style Start fill:#e1f5ff
style End fill:#d4edda
style Check fill:#fff3cd
style Error fill:#f8d7da
```
````
### Advanced Flowchart with Subgraphs
```mermaid
flowchart LR
A[Client Request] --> B{Auth?}
B -->|No| C[401 Unauthorized]
B -->|Yes| D[Process]
subgraph Processing["Request Processing"]
D --> E[Validate Input]
E --> F[Execute Logic]
F --> G[Format Response]
end
G --> H[Return 200 OK]
C --> I[End]
H --> I
style Processing fill:#f0e1ff
```
---
## 2. Sequence Diagrams / Sơ đồ Tuần tự
### When to Use / 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:
- 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
sequenceDiagram
participant Client
participant API
participant Service
participant DB
Client->>API: POST /login
API->>Service: authenticate(credentials)
Service->>DB: findUser(email)
DB-->>Service: user
Service->>Service: verifyPassword()
Service-->>API: JWT token
API-->>Client: 200 OK {token}
```
**Code**:
````markdown
```mermaid
sequenceDiagram
participant Client
participant API
participant Service
participant DB
Client->>API: POST /login
API->>Service: authenticate(credentials)
Service->>DB: findUser(email)
DB-->>Service: user
Service->>Service: verifyPassword()
Service-->>API: JWT token
API-->>Client: 200 OK {token}
```
````
### Advanced with Alt/Opt/Loop
```mermaid
sequenceDiagram
participant Client
participant API
participant Cache
participant DB
Client->>API: GET /users/:id
API->>Cache: get(key)
alt Cache Hit
Cache-->>API: cached data
API-->>Client: 200 OK (from cache)
else Cache Miss
Cache-->>API: null
API->>DB: SELECT * FROM users
DB-->>API: user data
API->>Cache: set(key, data, ttl)
API-->>Client: 200 OK (from DB)
end
```
---
## 3. Class Diagrams / Sơ đồ Class
### When to Use / 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:
- 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
classDiagram
class BaseRepository {
#prisma: PrismaClient
#modelName: string
+findById(id: string) T
+findAll(options: QueryOptions) T[]
+create(data: CreateDto) T
+update(id: string, data: UpdateDto) T
+delete(id: string) void
}
class UserRepository {
+findByEmail(email: string) User
+findByUsername(username: string) User
}
class FeatureRepository {
+findByName(name: string) Feature
+toggleStatus(id: string) Feature
}
BaseRepository <|-- UserRepository
BaseRepository <|-- FeatureRepository
```
---
## 4. Graph Diagrams / Sơ đồ Graph
### When to Use / 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:
- 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
graph TD
Client[Web Client] --> Gateway[Traefik Gateway]
Gateway --> Auth[Auth Service]
Gateway --> IAM[IAM Service]
Gateway --> User[User Service]
Auth --> DB[(PostgreSQL)]
IAM --> DB
User --> DB
Auth --> Cache[(Redis)]
IAM --> Cache
User --> Cache
style Gateway fill:#e1f5ff
style DB fill:#f0e1ff
style Cache fill:#fff4e1
```
### Data Flow
```mermaid
graph LR
Input[User Input] --> Validation[Zod Validation]
Validation --> Controller[Controller]
Controller --> Service[Service Layer]
Service --> Repository[Repository]
Repository --> Prisma[Prisma ORM]
Prisma --> DB[(Database)]
Service --> Cache[Cache Service]
Cache --> Redis[(Redis)]
style Validation fill:#d4edda
style Service fill:#e1f5ff
style Cache fill:#fff4e1
```
---
## 5. ER Diagrams / Sơ đồ ER
### When to Use / 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:
- 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
erDiagram
User ||--o{ Session : has
User ||--o{ RefreshToken : has
User ||--o{ UserRole : has
Role ||--o{ UserRole : has
Role ||--o{ RolePermission : has
Permission ||--o{ RolePermission : has
User {
string id PK
string email UK
string passwordHash
boolean mfaEnabled
datetime createdAt
datetime updatedAt
}
Session {
string id PK
string userId FK
string token UK
string deviceId
string ipAddress
datetime expiresAt
}
Role {
string id PK
string name UK
string description
datetime createdAt
}
Permission {
string id PK
string code UK
string resource
string action
string scope
}
```
---
## 6. Gantt Charts / Biểu đồ Gantt
### When to Use / 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:
- Timeline dự án
- Các giai đoạn triển khai
- Lịch trình migration
- Kế hoạch deployment
### Project Timeline
```mermaid
gantt
title Documentation Update Project Timeline
dateFormat YYYY-MM-DD
section Phase 1
Analysis & Research :done, p1, 2024-01-01, 1d
section Phase 2
Templates & Strategy :active, p2, 2024-01-02, 0.5d
section Phase 3
High Priority Docs :p3, 2024-01-03, 2d
section Phase 4
Remaining Docs :p4, 2024-01-05, 3d
section Phase 5
QA & Verification :p5, 2024-01-08, 1d
```
---
## 7. C4 Diagrams / Sơ đồ C4
### When to Use / 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:
- 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
C4Context
title System Context Diagram for IAM System
Person(user, "User", "System user needing authentication")
Person(admin, "Admin", "System administrator")
System(iam, "IAM System", "Identity and Access Management")
System_Ext(email, "Email Service", "SendGrid/AWS SES")
System_Ext(oauth, "OAuth Providers", "Google, Facebook, GitHub")
Rel(user, iam, "Authenticates with", "HTTPS")
Rel(admin, iam, "Manages users and permissions", "HTTPS")
Rel(iam, email, "Sends emails", "SMTP/API")
Rel(iam, oauth, "OAuth login", "OAuth 2.0")
```
---
## Styling Tips / Mẹo Styling
### Color Palette / Bảng màu
```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"]
style A fill:#e1f5ff
style B fill:#fff4e1
style C fill:#d4edda
style D fill:#fff3cd
style E fill:#f8d7da
style F fill:#f0e1ff
```
### Style Syntax
```markdown
style NodeId fill:#colorcode,stroke:#bordercolor,stroke-width:2px
```
**Examples**:
```markdown
style Start fill:#e1f5ff
style Error fill:#f8d7da
style Process fill:#d4edda,stroke:#28a745,stroke-width:2px
```
---
## Best Practices / Best Practices
### 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
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
---
## Common Pitfalls / Lỗi Thường gặp
### ❌ Too Complex
```mermaid
graph TD
A --> B
A --> C
B --> D
B --> E
C --> F
C --> G
D --> H
E --> H
F --> I
G --> I
H --> J
I --> J
```
### ✅ Simplified with Subgraphs
```mermaid
graph TD
A[Start] --> B[Process A]
B --> C[Process B]
subgraph "Detailed Processing"
C --> D[Step 1]
D --> E[Step 2]
end
E --> F[End]
```
---
## Testing Diagrams / Test Sơ đồ
**EN**: Always test your diagrams before committing:
**VI**: Luôn test sơ đồ trước khi commit:
```bash
# Install mermaid-cli
npm install -g @mermaid-js/mermaid-cli
# Test render
mmdc -i your-doc.md -o test-output.svg
# Check for errors
echo $? # Should be 0 if successful
```
---
## Resources / Tài nguyên
- [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
---
**Last Updated**: 2026-01-05

View File

@@ -0,0 +1,353 @@
# Pattern [Tên Pattern]
> **Mô tả**: Mô tả ngắn gọn về khi nào và tại sao sử dụng pattern này
## Tổng quan Pattern
```mermaid
graph LR
Input[Đầu vào/Yêu cầu] --> Process[Xử lý Pattern]
Process --> Output[Đầu ra/Kết quả]
subgraph Pattern["Triển khai Pattern"]
Process --> Step1[Bước 1]
Step1 --> Step2[Bước 2]
Step2 --> Step3[Bước 3]
end
style Input fill:#e1f5ff
style Output fill:#d4edda
style Pattern fill:#f0e1ff
```
## Khi nào sử dụng
Sử dụng pattern này khi:
- Tình huống 1: Mô tả khi pattern này có lợi
- Tình huống 2: Trường hợp sử dụng khác
- Tình huống 3: Bối cảnh bổ sung
**NÊN sử dụng pattern này cho**:
- ✅ Trường hợp 1
- ✅ Trường hợp 2
**KHÔNG NÊN sử dụng pattern này cho**:
- ❌ Anti-pattern 1
- ❌ Anti-pattern 2
## Khái niệm Cốt lõi
### Nguyên tắc Chính
1. **Nguyên tắc 1**: Mô tả nguyên tắc cốt lõi đầu tiên
2. **Nguyên tắc 2**: Mô tả nguyên tắc cốt lõi thứ hai
3. **Nguyên tắc 3**: Mô tả nguyên tắc cốt lõi thứ ba
## Triển khai
### Triển khai Cơ bản
Giải thích từng bước về cách triển khai pattern này.
```typescript
// Ví dụ triển khai cơ bản
/**
* Class triển khai pattern
*/
export class ExamplePattern {
/**
* Constructor với các dependencies
*/
constructor(
private dependency1: Dependency1,
private dependency2: Dependency2
) {}
/**
* Phương thức cốt lõi triển khai pattern
*
* @param input - Dữ liệu đầu vào
* @returns Kết quả đã xử lý
*/
async execute(input: InputType): Promise<OutputType> {
// Bước 1: Validate đầu vào
this.validateInput(input);
// Bước 2: Xử lý
const processed = await this.process(input);
// Bước 3: Trả về kết quả
return this.formatOutput(processed);
}
private validateInput(input: InputType): void {
// Logic validation
if (!input) {
throw new Error('Đầu vào là bắt buộc');
}
}
private async process(input: InputType): Promise<ProcessedType> {
// Logic nghiệp vụ cốt lõi
return await this.dependency1.transform(input);
}
private formatOutput(processed: ProcessedType): OutputType {
// Định dạng cho đầu ra
return {
success: true,
data: processed,
};
}
}
```
### Triển khai Nâng cao
Triển khai phức tạp hơn với các tính năng bổ sung.
```typescript
// Triển khai nâng cao với caching và xử lý lỗi
export class AdvancedExamplePattern extends ExamplePattern {
constructor(
dependency1: Dependency1,
dependency2: Dependency2,
private cache: CacheService,
private logger: Logger
) {
super(dependency1, dependency2);
}
async execute(input: InputType): Promise<OutputType> {
// Thử cache trước
const cacheKey = this.getCacheKey(input);
const cached = await this.cache.get<OutputType>(cacheKey);
if (cached) {
this.logger.info('Cache hit', { key: cacheKey });
return cached;
}
try {
// Thực thi logic pattern
const result = await super.execute(input);
// Cache kết quả
await this.cache.set(cacheKey, result, 300); // 5 phút
return result;
} catch (error) {
// Xử lý lỗi
this.logger.error('Thực thi pattern thất bại', { error, input });
throw new PatternExecutionError('Thực thi thất bại', { cause: error });
}
}
private getCacheKey(input: InputType): string {
return `pattern:example:${JSON.stringify(input)}`;
}
}
```
## Sơ đồ Pattern
### Cấu trúc Class
```mermaid
classDiagram
class ExamplePattern {
-dependency1: Dependency1
-dependency2: Dependency2
+execute(input: InputType): OutputType
-validateInput(input: InputType): void
-process(input: InputType): ProcessedType
-formatOutput(processed: ProcessedType): OutputType
}
class AdvancedExamplePattern {
-cache: CacheService
-logger: Logger
+execute(input: InputType): OutputType
-getCacheKey(input: InputType): string
}
ExamplePattern <|-- AdvancedExamplePattern
```
### Luồng Tuần tự
```mermaid
sequenceDiagram
participant Client as Khách hàng
participant Pattern as ExamplePattern
participant Dep1 as Dependency1
participant Cache as CacheService
Client->>Pattern: execute(input)
Pattern->>Cache: get(cacheKey)
Cache-->>Pattern: null (cache miss)
Pattern->>Pattern: validateInput(input)
Pattern->>Dep1: transform(input)
Dep1-->>Pattern: processed
Pattern->>Pattern: formatOutput(processed)
Pattern->>Cache: set(cacheKey, result, ttl)
Cache-->>Pattern: void
Pattern-->>Client: result
```
## Ví dụ Sử dụng
### Ví dụ 1: Sử dụng Cơ bản
Tình huống sử dụng cơ bản với giải thích.
```typescript
// Thiết lập
const dependency1 = new Dependency1();
const dependency2 = new Dependency2();
const pattern = new ExamplePattern(dependency1, dependency2);
// Thực thi pattern
const input: InputType = {
id: '123',
data: 'example',
};
const result = await pattern.execute(input);
console.log(result);
// Kết quả: { success: true, data: { ... } }
```
### Ví dụ 2: Sử dụng Nâng cao
Sử dụng nâng cao với caching được bật.
```typescript
// Thiết lập với các dependencies bổ sung
const cache = new CacheService();
const logger = new Logger();
const pattern = new AdvancedExamplePattern(
dependency1,
dependency2,
cache,
logger
);
// Lần gọi đầu tiên (cache miss)
const result1 = await pattern.execute(input);
// Lần gọi thứ hai (cache hit)
const result2 = await pattern.execute(input); // Trả về kết quả cached
```
## Best Practices
### Thực hành Được đề xuất
1. **Nguyên tắc 1**: Mô tả best practice với lý do
2. **Nguyên tắc 2**: Hướng dẫn quan trọng khác
3. **Nguyên tắc 3**: Khuyến nghị bổ sung
**Cấu hình**:
```typescript
const config = {
timeout: 5000,
retries: 3,
cacheTime: 300, // 5 phút
};
```
## Lỗi Thường gặp
### Lỗi 1: [Mô tả]
```typescript
// ❌ KHÔNG TỐT: Triển khai không chính xác
const result = await pattern.execute(null); // Sẽ throw error
```
```typescript
// ✅ TỐT: Triển khai chính xác
if (input) {
const result = await pattern.execute(input);
}
```
**Tại sao**: Giải thích tại sao cách tiếp cận đầu tiên là không tốt và cách thứ hai là tốt.
## Cân nhắc Hiệu suất
**Mô tả**: Đặc điểm hiệu suất và mẹo tối ưu hóa.
| Khía cạnh | Tác động | Giảm thiểu |
|-----------|----------|------------|
| Sử dụng RAM | Trung bình | Sử dụng caching có chiến lược |
| Sử dụng CPU | Thấp | N/A |
| Thao tác I/O | Cao | Triển khai connection pooling |
## Kiểm thử
```typescript
// Unit test cho pattern
describe('ExamplePattern', () => {
let pattern: ExamplePattern;
let mockDep1: jest.Mocked<Dependency1>;
beforeEach(() => {
mockDep1 = {
transform: jest.fn(),
} as any;
pattern = new ExamplePattern(mockDep1, {} as any);
});
it('nên thực thi thành công', async () => {
// Chuẩn bị
const input = { id: '123', data: 'test' };
const expectedProcessed = { transformed: true };
mockDep1.transform.mockResolvedValue(expectedProcessed);
// Thực thi
const result = await pattern.execute(input);
// Kiểm tra
expect(result.success).toBe(true);
expect(result.data).toEqual(expectedProcessed);
expect(mockDep1.transform).toHaveBeenCalledWith(input);
});
it('nên throw error cho đầu vào không hợp lệ', async () => {
// Mong đợi lỗi cho đầu vào null
await expect(pattern.execute(null as any))
.rejects
.toThrow('Đầu vào là bắt buộc');
});
});
```
## Patterns Liên quan
Các patterns khác bổ sung hoặc liên quan đến pattern này.
- [Pattern Liên quan 1](./related-pattern-1.md) - Cách nó liên quan
- [Pattern Liên quan 2](./related-pattern-2.md) - So sánh
- [Pattern Thay thế](./alternative-pattern.md) - Khi nào sử dụng thay thế
## Tài nguyên Bổ sung
### Tài liệu Liên quan
- [Hướng dẫn Thiết kế API](../api-design.md) - Pattern này khớp với thiết kế API như thế nào
- [Xử lý Lỗi](../error-handling-patterns.md) - Xử lý lỗi cho pattern này
- [Hướng dẫn Kiểm thử](../testing-patterns.md) - Chiến lược kiểm thử
---
**Cập nhật lần cuối**: YYYY-MM-DD
**Độ phức tạp**: Beginner/Intermediate/Advanced
**Danh mục**: [Tên Danh mục]
**Tác giả**: Tên của bạn