Initial commit - cleaned repository

This commit is contained in:
jungwoo choi
2025-09-28 20:41:57 +09:00
commit e3c28f796a
188 changed files with 28102 additions and 0 deletions

182
docs/ARCHITECTURE.md Normal file
View File

@ -0,0 +1,182 @@
# Site11 Microservices Architecture
## 시스템 아키텍처 개요
### 메시징 및 데이터 처리 시스템
#### 1. **Apache Kafka** - 통합 메시징 플랫폼
- **역할**: 이벤트 스트리밍 + 작업 큐 + 메시지 버스
- **사용 사례**:
- 서비스 간 이벤트 발행/구독
- 비동기 작업 큐 (Celery 대체)
- 사용자 활동 로그 스트리밍
- 실시간 데이터 파이프라인
- 이벤트 소싱 패턴 구현
- CQRS (Command Query Responsibility Segregation)
- 백그라운드 작업 처리
#### 2. **Redis** - 인메모리 데이터 스토어
- **역할**: 캐싱 및 세션 관리 전용
- **사용 사례**:
- API 응답 캐싱
- 사용자 세션 저장
- Rate limiting
- 실시간 리더보드/카운터
- 임시 데이터 저장
#### 3. **MongoDB** - Document Database
- **역할**: 주요 데이터 영속성
- **사용 사례**:
- 서비스별 도메인 데이터
- 유연한 스키마 관리
- 이벤트 저장소
## 서비스 통신 패턴
### 동기 통신 (REST API)
```
Client → Nginx → Console (API Gateway) → Microservice
```
- 즉각적인 응답이 필요한 경우
- CRUD 작업
- 실시간 데이터 조회
### 비동기 통신 (Kafka Events)
```
Service A → Kafka Topic → Service B, C, D
```
- 서비스 간 느슨한 결합
- 이벤트 기반 아키텍처
- 확장 가능한 처리
### 캐싱 전략 (Redis)
```
Request → Check Redis Cache → Hit? Return : Fetch from DB → Store in Redis → Return
```
- 응답 시간 개선
- 데이터베이스 부하 감소
- 세션 관리
## 이벤트 플로우 예시
### 사용자 등록 플로우
1. **API Request**: Client → Console → Users Service
2. **User Created Event**: Users Service → Kafka
3. **Event Consumers**:
- Statistics Service: 사용자 통계 업데이트
- Email Service: 환영 이메일 발송
- Analytics Service: 가입 분석
4. **Cache Update**: Redis에 사용자 정보 캐싱
### 이미지 업로드 플로우
1. **Upload Request**: Client → Console → Images Service
2. **Image Uploaded Event**: Images Service → Kafka
3. **Event Processing**:
- Thumbnail Service: 썸네일 생성
- ML Service: 이미지 분석
- Statistics Service: 업로드 통계
4. **Job Queue**: Redis/Celery로 백그라운드 처리
## Kafka Topics 구조 (예정)
### Event Topics (이벤트 스트리밍)
```
# User Domain
user.created
user.updated
user.deleted
user.login
# Image Domain
image.uploaded
image.processed
image.deleted
# Application Domain
app.registered
app.updated
app.deployed
# System Events
service.health
service.error
audit.log
```
### Task Queue Topics (작업 큐)
```
# Background Jobs
tasks.email.send
tasks.image.resize
tasks.report.generate
tasks.data.export
tasks.notification.push
# Scheduled Jobs
tasks.cleanup.expired
tasks.backup.database
tasks.analytics.aggregate
```
## Redis 사용 패턴
### 1. 캐싱 계층
- Key: `cache:users:{user_id}`
- TTL: 3600초
- 패턴: Cache-Aside
### 2. 세션 관리
- Key: `session:{token}`
- TTL: 1800초
- 데이터: 사용자 정보, 권한
### 3. Rate Limiting
- Key: `rate_limit:{user_id}:{endpoint}`
- Window: Sliding window
- Limit: 100 requests/minute
### 4. 작업 큐 (Celery)
- Queue: `celery:tasks`
- Priority Queue 지원
- Dead Letter Queue
## 구현 로드맵
### Phase 1 (현재)
- ✅ 기본 서비스 구조
- ✅ MongoDB 연동
- ✅ Redis 설치
- 🔄 JWT 인증
### Phase 2 (Step 6-7)
- Kafka 클러스터 설정
- 기본 Producer/Consumer 구현
- Event Schema 정의
- Redis 캐싱 전략 구현
### Phase 3 (Step 8+)
- Event Sourcing 패턴
- CQRS 구현
- Saga 패턴 (분산 트랜잭션)
- 모니터링 대시보드
## 기술 스택
### 메시징 & 스트리밍
- **Kafka**: Event streaming
- **Redis**: Caching, Queue, Pub/Sub
- **Confluent Schema Registry**: Schema 관리 (향후)
### 백엔드
- **FastAPI**: REST API
- **Celery**: 비동기 작업 처리
- **kafka-python**: Kafka 클라이언트
### 데이터베이스
- **MongoDB**: Document store
- **Redis**: In-memory cache
### 모니터링 (향후)
- **Kafka Manager**: Kafka 클러스터 관리
- **RedisInsight**: Redis 모니터링
- **Prometheus + Grafana**: 메트릭 수집/시각화

140
docs/DATA_PERSISTENCE.md Normal file
View File

@ -0,0 +1,140 @@
# Data Persistence Configuration
## Overview
All data services are configured to use bind mounts to local directories for data persistence. This ensures data survives container restarts and rebuilds.
## Directory Structure
```
data/
├── mongodb/ # MongoDB database files
├── redis/ # Redis persistence files
├── kafka/ # Kafka log data
├── zookeeper/ # Zookeeper data and logs
│ ├── data/
│ └── logs/
├── minio/ # MinIO object storage
├── solr/ # Solr search index
├── files-temp/ # Temporary file storage
└── images-cache/ # Image processing cache
```
## Volume Mappings
### MongoDB
- `./data/mongodb:/data/db` - Database files
- `./data/mongodb/configdb:/data/configdb` - Configuration database
### Redis
- `./data/redis:/data` - RDB snapshots and AOF logs
### Kafka
- `./data/kafka:/var/lib/kafka/data` - Message logs
### Zookeeper
- `./data/zookeeper/data:/var/lib/zookeeper/data` - Coordination data
- `./data/zookeeper/logs:/var/lib/zookeeper/log` - Transaction logs
### MinIO
- `./data/minio:/data` - Object storage buckets
### Solr
- `./data/solr:/var/solr` - Search index and configuration
### Application Caches
- `./data/files-temp:/tmp` - Temporary file processing
- `./data/images-cache:/app/cache` - Processed image cache
## Backup and Restore
### Backup All Data
```bash
# Stop services
docker-compose down
# Create backup
tar -czf backup-$(date +%Y%m%d).tar.gz data/
# Restart services
docker-compose up -d
```
### Restore Data
```bash
# Stop services
docker-compose down
# Extract backup
tar -xzf backup-YYYYMMDD.tar.gz
# Restart services
docker-compose up -d
```
### Individual Service Backups
#### MongoDB Backup
```bash
docker exec site11_mongodb mongodump --out /data/db/backup
tar -czf mongodb-backup.tar.gz data/mongodb/backup/
```
#### Redis Backup
```bash
docker exec site11_redis redis-cli BGSAVE
# Wait for completion
cp data/redis/dump.rdb redis-backup-$(date +%Y%m%d).rdb
```
## Permissions
Ensure proper permissions for data directories:
```bash
# Set appropriate permissions
chmod -R 755 data/
```
## Disk Space Monitoring
Monitor disk usage regularly:
```bash
# Check data directory size
du -sh data/*
# Check individual services
du -sh data/mongodb
du -sh data/minio
du -sh data/kafka
```
## Clean Up Old Data
### Clear Kafka Logs (older than 7 days)
```bash
docker exec site11_kafka kafka-log-dirs.sh --describe --bootstrap-server localhost:9092
```
### Clear Image Cache
```bash
rm -rf data/images-cache/*
```
### Clear Temporary Files
```bash
rm -rf data/files-temp/*
```
## Migration from Docker Volumes
If migrating from named Docker volumes to bind mounts:
1. Export data from Docker volumes:
```bash
docker run --rm -v site11_mongodb_data:/source -v $(pwd)/data/mongodb:/dest alpine cp -av /source/. /dest/
```
2. Update docker-compose.yml (already done)
3. Restart services with new configuration
## Notes
- The `data/` directory is excluded from git via .gitignore
- Ensure sufficient disk space for data growth
- Consider setting up automated backups for production
- Monitor disk I/O performance for database services

View File

@ -0,0 +1,238 @@
# Pipeline Scheduler Guide
## 개요
Pipeline Scheduler는 등록된 키워드를 주기적으로 실행하여 자동으로 뉴스를 수집하고 AI 기사를 생성하는 시스템입니다.
## 아키텍처
### 1. 구성 요소
#### 1.1 Multi-Thread Scheduler (pipeline-scheduler)
- **역할**: 키워드별 스레드 관리 및 주기적 실행
- **특징**:
- 단일 Docker 컨테이너에서 여러 스레드 동시 실행
- 각 키워드당 하나의 독립 스레드
- 30초마다 새 키워드 체크 및 스레드 관리
- **위치**: `services/pipeline/scheduler/multi_thread_scheduler.py`
#### 1.2 Keyword Manager API (keyword-manager)
- **역할**: 키워드 CRUD 및 스레드 모니터링
- **포트**: 8100
- **주요 엔드포인트**:
- `GET /threads/status` - 모든 스레드 상태 조회
- `GET /keywords` - 모든 키워드 목록
- `POST /keywords` - 새 키워드 추가
- `PUT /keywords/{keyword}` - 키워드 수정
- `DELETE /keywords/{keyword}` - 키워드 삭제
- `POST /keywords/{keyword}/activate` - 키워드 활성화
- `POST /keywords/{keyword}/deactivate` - 키워드 비활성화
- `POST /keywords/{keyword}/trigger` - 즉시 실행
- **위치**: `services/pipeline/scheduler/keyword_manager.py`
### 2. 데이터 모델
```python
class Keyword:
keyword_id: str # UUID
keyword: str # 검색 키워드
interval_minutes: int # 실행 주기 (분)
is_active: bool # 활성 상태
priority: int # 우선순위 (높을수록 우선)
rss_feeds: List[str] # RSS 피드 URL 목록
max_articles_per_run: int # 실행당 최대 기사 수
last_run: datetime # 마지막 실행 시간
next_run: datetime # 다음 실행 예정 시간
```
## 사용 방법
### 1. 서비스 시작
```bash
# 스케줄러와 매니저 시작
docker-compose up -d pipeline-scheduler keyword-manager
# 로그 확인
docker-compose logs -f pipeline-scheduler
```
### 2. 키워드 관리
#### 2.1 키워드 추가
```bash
curl -X POST http://localhost:8100/keywords \
-H "Content-Type: application/json" \
-d '{
"keyword": "딥러닝",
"interval_minutes": 60,
"priority": 1,
"rss_feeds": [],
"max_articles_per_run": 100,
"is_active": true
}'
```
#### 2.2 키워드 수정
```bash
curl -X PUT http://localhost:8100/keywords/딥러닝 \
-H "Content-Type: application/json" \
-d '{
"interval_minutes": 30,
"priority": 2
}'
```
#### 2.3 키워드 활성화/비활성화
```bash
# 활성화
curl -X POST http://localhost:8100/keywords/딥러닝/activate
# 비활성화
curl -X POST http://localhost:8100/keywords/딥러닝/deactivate
```
#### 2.4 즉시 실행
```bash
curl -X POST http://localhost:8100/keywords/딥러닝/trigger
```
#### 2.5 키워드 삭제
```bash
curl -X DELETE http://localhost:8100/keywords/딥러닝
```
### 3. 모니터링
#### 3.1 스레드 상태 확인
```bash
curl http://localhost:8100/threads/status | python3 -m json.tool
```
응답 예시:
```json
{
"total_threads": 4,
"active_threads": 4,
"threads": [
{
"keyword": "블록체인",
"keyword_id": "5c7ac9a9-c56f-4878-94ec-adb13f105c8a",
"is_active": true,
"interval_minutes": 30,
"priority": 2,
"last_run": "2025-09-15T08:05:58.807000",
"next_run": "2025-09-15T08:35:58.807000",
"thread_status": "active",
"minutes_until_next_run": 25.3
}
]
}
```
#### 3.2 키워드 목록 조회
```bash
curl http://localhost:8100/keywords | python3 -m json.tool
```
## 작동 방식
### 1. 실행 흐름
1. **키워드 스레드 시작**
- 스케줄러 시작 시 활성 키워드 로드
- 각 키워드별 독립 스레드 생성
2. **주기적 실행**
- 각 스레드는 설정된 주기마다 실행
- 실행 시 PipelineJob 생성 후 Redis 큐에 추가
- RSS 수집 → Google 검색 → AI 기사 생성 → 번역 파이프라인 자동 진행
3. **동적 스레드 관리**
- 30초마다 새 키워드 확인
- 새 키워드 추가 시 자동으로 스레드 생성
- 비활성화/삭제 시 스레드 자동 중지
### 2. 우선순위 처리
- 높은 우선순위(priority) 키워드가 먼저 처리
- Redis 큐에서 우선순위별 정렬
### 3. 오류 처리
- 각 스레드는 독립적으로 오류 처리
- 오류 발생 시 1분 대기 후 재시도
- 스레드별 error_count, last_error 추적
## 현재 설정된 키워드
| 키워드 | 실행 주기 | 우선순위 | 상태 |
|--------|-----------|----------|------|
| 블록체인 | 30분 | 2 | 활성 |
| AI | 60분 | 1 | 활성 |
| 테크놀로지 | 60분 | 1 | 활성 |
| 경제 | 60분 | 0 | 활성 |
## 주의사항
1. **스레드 관리**
- 키워드 추가/삭제는 30초 이내 자동 반영
- 스레드 상태는 keyword-manager API로 실시간 확인 가능
2. **실행 주기**
- 최소 실행 주기: 제한 없음 (권장: 30분 이상)
- interval_minutes 변경 시 다음 실행 시간 자동 재계산
3. **중복 방지**
- 동일 키워드 중복 등록 불가
- RSS 수집 시 중복 URL 자동 필터링
## 트러블슈팅
### 스레드가 시작되지 않을 때
```bash
# 스케줄러 재시작
docker-compose restart pipeline-scheduler
# 로그 확인
docker-compose logs --tail=50 pipeline-scheduler
```
### 키워드가 실행되지 않을 때
```bash
# 키워드 상태 확인
curl http://localhost:8100/keywords/키워드명 | python3 -m json.tool
# 즉시 실행 트리거
curl -X POST http://localhost:8100/keywords/키워드명/trigger
```
### MongoDB 연결 오류
```bash
# MongoDB 상태 확인
docker-compose ps mongodb
# MongoDB 재시작
docker-compose restart mongodb
```
## 파일 구조
```
services/pipeline/scheduler/
├── multi_thread_scheduler.py # 멀티스레드 스케줄러
├── keyword_manager.py # 키워드 관리 API
├── single_keyword_scheduler.py # (deprecated) 단일 키워드 스케줄러
├── requirements.txt # Python 의존성
└── Dockerfile # Docker 이미지 정의
services/pipeline/shared/
└── models.py # Keyword, PipelineJob 모델 정의
```
## 향후 개선사항
1. **웹 대시보드**: 실시간 모니터링 UI
2. **알림 시스템**: 오류 발생 시 이메일/Slack 알림
3. **통계 기능**: 키워드별 수집 통계 및 분석
4. **스케줄 템플릿**: 자주 사용하는 설정 저장/불러오기
5. **백업/복구**: 키워드 설정 백업 및 복구 기능

401
docs/PLAN.md Normal file
View File

@ -0,0 +1,401 @@
# Microservices Architecture Implementation Plan
## Project Overview
Build a microservices-based platform with a central Console service acting as an orchestrator and API Gateway, managing multiple domain-specific services.
## Architecture Decision
**Selected Pattern**: API Gateway Pattern with Console as the central orchestrator
- Console handles authentication, routing, and monitoring
- Each microservice focuses on domain-specific logic
- Services communicate via REST APIs and Redis pub/sub
## Progressive Implementation Strategy
### Step-by-Step Approach
큰 그림을 먼저 구성하고, 핵심 기능부터 점진적으로 확장하는 전략
## Implementation Phases
### Step 1: Minimal Foundation (Day 1-2)
**목표**: 가장 기본적인 구조 확립
```
site11/
├── docker-compose.yml # 최소 구성 (Console만)
├── console/
│ └── backend/
│ └── main.py # Hello World API
└── README.md
```
**Tasks**:
- [ ] 간단한 docker-compose.yml 생성
- [ ] Console FastAPI "Hello World"
- [ ] 기본 health check endpoint
- [ ] Docker로 실행 확인
### Step 2: Add First Service (Day 3-4)
**목표**: Console과 하나의 서비스 연결
```
site11/
├── docker-compose.yml
├── console/
│ └── backend/
│ └── main.py # Gateway 역할 추가
└── services/
└── users/
└── backend/
└── main.py # Users 서비스
```
**Tasks**:
- [ ] Users 서비스 생성
- [ ] Console에서 Users로 라우팅
- [ ] 서비스 간 통신 테스트
- [ ] 간단한 CRUD API
### Step 3: Database Integration (Day 5-6)
**목표**: MongoDB 연결 및 기본 데이터 저장
**Tasks**:
- [ ] MongoDB 컨테이너 추가
- [ ] Console과 Users 서비스 DB 연결
- [ ] 기본 데이터 모델 생성
- [ ] 실제 데이터 CRUD 테스트
### Step 4: Frontend Skeleton (Week 2)
**목표**: 최소한의 UI 구성
**Tasks**:
- [ ] Console Frontend 생성 (React + Vite)
- [ ] 기본 레이아웃
- [ ] 서비스 상태 표시
- [ ] Nginx 설정
### Step 5: Authentication Basic (Week 2)
**목표**: 간단한 인증 시스템
**Tasks**:
- [ ] JWT 토큰 생성
- [ ] Login endpoint
- [ ] Token 검증 미들웨어
- [ ] Protected routes
### Step 6: Second Service (Week 3)
**목표**: 두 번째 서비스 추가로 패턴 확립
**Tasks**:
- [ ] OAuth 또는 Images 서비스 추가
- [ ] Console 라우팅 확장
- [ ] 서비스 간 통신 패턴 확립
- [ ] Service registry 기초
### Step 7: Service Communication (Week 3)
**목표**: 서비스 간 통신 패턴 구현
**Tasks**:
- [ ] Redis pub/sub 설정
- [ ] Event 기반 통신 예제
- [ ] Service discovery 구현
- [ ] Health check 자동화
### Step 8: Gradual Service Addition (Week 4-5)
**목표**: 나머지 서비스 점진적 추가
**각 서비스별로**:
- [ ] 기본 구조 생성
- [ ] Console 연결
- [ ] 핵심 API 구현
- [ ] Frontend 컴포넌트 추가
## 현재 시작점 (NOW)
### 즉시 시작할 수 있는 첫 걸음
#### 1. 최소 Docker 환경 구성
```bash
# 실행 명령
docker-compose up -d console
curl http://localhost:8000/health
```
#### 2. Console 서비스만으로 시작
- Health endpoint
- 간단한 API Gateway 구조
- 서비스 등록 준비
#### 3. 하나씩 추가하며 테스트
- Users 서비스 하나만 추가
- 통신 확인
- 패턴 확립 후 확장
### 핵심 원칙
1. **작동하는 코드 우선** - 완벽한 설계보다 동작하는 MVP
2. **점진적 복잡도** - 간단한 것부터 시작해서 기능 추가
3. **빠른 피드백** - 각 단계마다 실행하고 확인
4. **패턴 확립** - 첫 서비스로 패턴을 만들고 복제
---
## 상세 구현 계획 (참고용)
### Phase 1: Foundation Setup (Week 1)
#### Goals
- Set up project structure
- Configure Docker environment
- Establish basic infrastructure
#### Tasks
- [ ] Initialize Git repository
- [ ] Create Docker Compose configuration
- [ ] Set up Nginx reverse proxy
- [ ] Configure MongoDB and Redis containers
- [ ] Create base directory structure for all services
#### Deliverables
- Working Docker environment
- Basic networking between containers
- Database and cache ready
### Phase 2: Console Service - Core (Week 2)
#### Goals
- Implement Console as API Gateway
- Set up authentication system
- Create service registry
#### Tasks
- [ ] Console Backend
- [ ] FastAPI application setup
- [ ] JWT authentication implementation
- [ ] Service registry and discovery
- [ ] API routing mechanism
- [ ] Health check endpoints
- [ ] Console Frontend
- [ ] React + Vite setup
- [ ] Login/Register pages
- [ ] Admin dashboard layout
- [ ] Service status dashboard
#### Deliverables
- Working authentication system
- Basic API Gateway functionality
- Service health monitoring dashboard
### Phase 3: OAuth Service (Week 3)
#### Goals
- Centralized authentication service
- OAuth2 implementation
- User session management
#### Tasks
- [ ] OAuth Backend
- [ ] OAuth2 server implementation
- [ ] Token generation and validation
- [ ] User authentication endpoints
- [ ] Integration with Console
- [ ] OAuth Frontend
- [ ] OAuth consent screens
- [ ] Token management UI
- [ ] Application registration
#### Deliverables
- OAuth2 server
- Token-based authentication
- Integration with Console
### Phase 4: Users Service (Week 4)
#### Goals
- User management microservice
- Profile management
- User data CRUD operations
#### Tasks
- [ ] Users Backend
- [ ] User model and database schema
- [ ] CRUD APIs for user management
- [ ] Profile management endpoints
- [ ] Integration with OAuth service
- [ ] Users Frontend
- [ ] User list and search
- [ ] Profile editing interface
- [ ] User details view
#### Deliverables
- Complete user management system
- Profile management features
- Admin user interface
### Phase 5: Core Microservices (Weeks 5-6)
#### Goals
- Implement remaining core services
- Establish inter-service communication
#### Services to Implement
1. **Images Service**
- Image upload/download
- Image processing
- Storage management
2. **Applications Service**
- Application registration
- Configuration management
- Version control
3. **Data Service**
- Data import/export
- Data transformation
- API for data access
4. **Statistics Service**
- Metrics collection
- Analytics dashboard
- Report generation
#### Tasks per Service
- [ ] Backend implementation
- [ ] Domain models
- [ ] Business logic
- [ ] REST APIs
- [ ] Event publishing
- [ ] Frontend implementation
- [ ] Service-specific UI
- [ ] Integration with Console
- [ ] Dashboard widgets
### Phase 6: Integration & Testing (Week 7)
#### Goals
- End-to-end integration
- Performance optimization
- Security hardening
#### Tasks
- [ ] Integration Testing
- [ ] Service communication tests
- [ ] Load testing
- [ ] Security testing
- [ ] Optimization
- [ ] Redis caching implementation
- [ ] Database indexing
- [ ] API response optimization
- [ ] Documentation
- [ ] API documentation (OpenAPI)
- [ ] Deployment guide
- [ ] Developer documentation
#### Deliverables
- Fully integrated system
- Performance benchmarks
- Complete documentation
### Phase 7: Monitoring & DevOps (Week 8)
#### Goals
- Production readiness
- Monitoring and alerting
- CI/CD pipeline
#### Tasks
- [ ] Monitoring Setup
- [ ] Prometheus metrics
- [ ] Grafana dashboards
- [ ] Log aggregation (ELK stack)
- [ ] DevOps
- [ ] GitHub Actions CI/CD
- [ ] Automated testing
- [ ] Docker image optimization
- [ ] Production Configuration
- [ ] Environment variables
- [ ] Secrets management
- [ ] Backup strategies
#### Deliverables
- Production-ready deployment
- Monitoring dashboards
- Automated deployment pipeline
## Technical Implementation Details
### Service Communication Flow
```
Client Request → Nginx → Console (API Gateway) → Microservice
Authentication Check
Request Routing
Response Aggregation
```
### Database Strategy
```
MongoDB Instance
├── console_db # Console service data
├── users_db # Users service data
├── oauth_db # OAuth tokens and sessions
├── images_db # Image metadata
├── applications_db # Application data
├── data_db # Generic data storage
└── statistics_db # Analytics data
```
### API Versioning Strategy
- All APIs follow `/api/v1/` pattern
- Version in URL path for major versions
- Header-based versioning for minor updates
### Security Implementation
1. **Authentication Flow**
- User login → OAuth service
- OAuth service issues JWT
- Console validates JWT on each request
- Console forwards validated requests to services
2. **Service-to-Service Auth**
- Internal service tokens
- mTLS for production
- Network isolation via Docker networks
### Development Workflow
1. **Local Development**
```bash
docker-compose up -d [service-name]
docker-compose logs -f [service-name]
```
2. **Testing**
```bash
docker-compose exec [service-name] pytest
```
3. **Deployment**
```bash
docker-compose build
docker-compose up -d
```
## Success Criteria
- [ ] All services independently deployable
- [ ] Console successfully routes to all services
- [ ] Authentication works across all services
- [ ] Health monitoring shows all services green
- [ ] Load testing shows <100ms p95 latency
- [ ] Zero downtime deployments possible
## Risk Mitigation
1. **Service Failure**: Circuit breakers in Console
2. **Data Consistency**: Event sourcing for critical operations
3. **Performance**: Redis caching layer
4. **Security**: Regular security audits, dependency updates
## Timeline Summary
- **Week 1**: Foundation and infrastructure
- **Week 2**: Console core implementation
- **Week 3**: OAuth service
- **Week 4**: Users service
- **Weeks 5-6**: Remaining microservices
- **Week 7**: Integration and testing
- **Week 8**: Monitoring and production setup
## Next Steps
1. Review and approve plan
2. Set up Git repository
3. Begin Phase 1 implementation
4. Schedule weekly progress reviews

127
docs/PROGRESS.md Normal file
View File

@ -0,0 +1,127 @@
# Progress Tracking & Context Management
## Purpose
이 파일은 Claude의 컨텍스트가 리셋되어도 빠르게 현재 진행 상황을 파악하고 이어서 작업할 수 있도록 돕는 체크포인트 문서입니다.
## Current Status
- **Date Started**: 2025-09-09
- **Current Phase**: Step 3 Complete ✅
- **Next Action**: Step 4 - Frontend Skeleton
## Completed Checkpoints
✅ Project structure planning (CLAUDE.md)
✅ Implementation plan created (docs/PLAN.md)
✅ Progressive approach defined
✅ Step 1: Minimal Foundation - Docker + Console Hello World
- docker-compose.yml created
- console/backend with FastAPI
- Running on port 8011
✅ Step 2: Add First Service (Users)
- Users service with CRUD operations
- Console API Gateway routing to Users
- Service communication verified
- Test: curl http://localhost:8011/api/users/users
✅ Step 3: Database Integration
- MongoDB and Redis containers added
- Users service using MongoDB with Beanie ODM
- Data persistence verified
- MongoDB IDs: 68c126c0bbbe52be68495933
## Active Working Files
```
현재 작업 중인 주요 파일:
- /docs/PLAN.md (구현 계획)
- /CLAUDE.md (아키텍처 가이드)
- /docs/PROGRESS.md (이 파일)
```
## Next Immediate Steps
```bash
# 다음 작업 시작 명령
# Step 1: Create docker-compose.yml
# Step 2: Create console/backend/main.py
# Step 3: Test with docker-compose up
```
## Code Snippets Ready to Use
### 1. Minimal docker-compose.yml
```yaml
version: '3.8'
services:
console:
build: ./console/backend
ports:
- "8000:8000"
environment:
- ENV=development
```
### 2. Console main.py starter
```python
from fastapi import FastAPI
app = FastAPI(title="Console API Gateway")
@app.get("/health")
async def health():
return {"status": "healthy", "service": "console"}
```
## Important Decisions Made
1. **Architecture**: API Gateway Pattern with Console as orchestrator
2. **Tech Stack**: FastAPI + React + MongoDB + Redis + Docker
3. **Approach**: Progressive implementation (simple to complex)
4. **First Service**: Users service after Console
## Questions to Ask When Resuming
새로운 세션에서 이어서 작업할 때 확인할 사항:
1. "PROGRESS.md 파일을 확인했나요?"
2. "마지막으로 완료한 Step은 무엇인가요?"
3. "현재 에러나 블로킹 이슈가 있나요?"
## Git Commits Pattern
각 Step 완료 시 커밋 메시지:
```
Step X: [간단한 설명]
- 구현 내용 1
- 구현 내용 2
```
## Directory Structure Snapshot
```
site11/
├── CLAUDE.md ✅ Created
├── docs/
│ ├── PLAN.md ✅ Created
│ └── PROGRESS.md ✅ Created (this file)
├── console/ 🔄 Next
│ └── backend/
│ └── main.py
└── docker-compose.yml 🔄 Next
```
## Context Recovery Commands
새 세션에서 빠르게 상황 파악하기:
```bash
# 1. 현재 구조 확인
ls -la
# 2. 진행 상황 확인
cat docs/PROGRESS.md
# 3. 다음 단계 확인
grep "Step" docs/PLAN.md | head -5
# 4. 실행 중인 컨테이너 확인
docker ps
```
## Error Log
문제 발생 시 여기에 기록:
- (아직 없음)
## Notes for Next Session
- Step 1부터 시작
- docker-compose.yml 생성 필요
- console/backend/main.py 생성 필요
- 모든 문서 파일은 대문자.md 형식으로 생성 (예: README.md, SETUP.md)

170
docs/TEST_AUTH.md Normal file
View File

@ -0,0 +1,170 @@
# 인증 시스템 테스트 가이드
## 테스트 계정
- **관리자**: admin / admin123
- **일반 사용자**: user / user123
## 1. Terminal에서 테스트
### 로그인 테스트
```bash
# 관리자로 로그인
curl -X POST http://localhost:8011/api/auth/login \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "username=admin&password=admin123"
# 응답 예시:
# {"access_token":"eyJhbGci...","token_type":"bearer"}
```
### 토큰 저장 및 사용
```bash
# 토큰을 변수에 저장
export TOKEN="eyJhbGci..." # 위에서 받은 토큰
# 인증된 요청 - 사용자 정보 조회
curl -X GET http://localhost:8011/api/auth/me \
-H "Authorization: Bearer $TOKEN"
# 인증된 요청 - 보호된 엔드포인트
curl -X GET http://localhost:8011/api/protected \
-H "Authorization: Bearer $TOKEN"
# 인증된 요청 - Users 서비스 접근
curl -X GET http://localhost:8011/api/users/ \
-H "Authorization: Bearer $TOKEN"
```
### 로그아웃
```bash
curl -X POST http://localhost:8011/api/auth/logout \
-H "Authorization: Bearer $TOKEN"
```
## 2. Postman/Insomnia에서 테스트
### Postman 설정
1. **로그인 요청**
- Method: POST
- URL: `http://localhost:8011/api/auth/login`
- Body: x-www-form-urlencoded
- username: admin
- password: admin123
2. **토큰 사용**
- Authorization 탭에서 Type: Bearer Token 선택
- Token 필드에 받은 토큰 붙여넣기
## 3. Python 스크립트로 테스트
```python
import requests
# 로그인
login_response = requests.post(
"http://localhost:8011/api/auth/login",
data={"username": "admin", "password": "admin123"}
)
token = login_response.json()["access_token"]
# 인증된 요청
headers = {"Authorization": f"Bearer {token}"}
me_response = requests.get(
"http://localhost:8011/api/auth/me",
headers=headers
)
print(me_response.json())
# Users 서비스 접근
users_response = requests.get(
"http://localhost:8011/api/users/",
headers=headers
)
print(users_response.json())
```
## 4. JavaScript (브라우저 콘솔)에서 테스트
```javascript
// 로그인
const loginResponse = await fetch('http://localhost:8011/api/auth/login', {
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: 'username=admin&password=admin123'
});
const { access_token } = await loginResponse.json();
console.log('Token:', access_token);
// 인증된 요청
const meResponse = await fetch('http://localhost:8011/api/auth/me', {
headers: {'Authorization': `Bearer ${access_token}`}
});
const userData = await meResponse.json();
console.log('User:', userData);
```
## 5. Frontend에서 테스트 (React)
브라우저에서 http://localhost:3000 접속 후 개발자 도구 콘솔에서:
```javascript
// 로그인 함수
async function testLogin() {
const response = await fetch('/api/auth/login', {
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: 'username=admin&password=admin123'
});
const data = await response.json();
localStorage.setItem('token', data.access_token);
console.log('Logged in!', data);
return data.access_token;
}
// 인증 테스트
async function testAuth() {
const token = localStorage.getItem('token');
const response = await fetch('/api/auth/me', {
headers: {'Authorization': `Bearer ${token}`}
});
const data = await response.json();
console.log('User info:', data);
}
// 실행
await testLogin();
await testAuth();
```
## 오류 테스트
### 잘못된 비밀번호
```bash
curl -X POST http://localhost:8011/api/auth/login \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "username=admin&password=wrong"
# 응답: 401 Unauthorized
```
### 토큰 없이 보호된 엔드포인트 접근
```bash
curl -X GET http://localhost:8011/api/auth/me
# 응답: 401 Unauthorized
```
### 잘못된 토큰
```bash
curl -X GET http://localhost:8011/api/auth/me \
-H "Authorization: Bearer invalid_token"
# 응답: 401 Unauthorized
```
## 토큰 정보
- **유효 기간**: 30분 (환경 변수 ACCESS_TOKEN_EXPIRE_MINUTES로 설정 가능)
- **알고리즘**: HS256
- **페이로드**: username 정보 포함
## 다음 단계
Frontend에 로그인 페이지를 추가하면 UI에서 직접 테스트 가능합니다.