Implements a comprehensive web crawler microservice
Introduces a complete NestJS-based web crawler microservice. This release establishes a robust system for web data extraction through a flexible Pipeline/Stage architecture. Key features include: - Supports both static (axios, cheerio) and dynamic (Playwright) page crawling. - Implements diverse triggering options: cron-based scheduling, NATS event-driven, and manual API calls. - Enhances system resilience with domain-specific rate limiting and configurable exponential backoff retry mechanisms. - Provides dedicated API endpoints and database schemas for managing pipelines, stages, and execution history. - Ensures data persistence by saving crawl results to MinIO. The `README.md` is entirely rewritten to provide comprehensive documentation on features, architecture, setup, API usage, and troubleshooting. Core dependencies for crawling, scheduling, and API validation are added, and database models are refactored to align with the new crawler system's data structures.
This commit is contained in:
1 parent
60f8e249fa
commit
a0d218a169
26 files changed
+4367
-281
No files matched your search
@@ -1,98 +1,774 @@
|
||||
<p align="center">
|
||||
<a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo-small.svg" width="120" alt="Nest Logo" /></a>
|
||||
</p>
|
||||
# MSA 기반 웹 크롤러 서비스
|
||||
|
||||
[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456
|
||||
[circleci-url]: https://circleci.com/gh/nestjs/nest
|
||||
NestJS 기반의 마이크로서비스 아키텍처 웹 크롤러 시스템입니다. 정적/동적 웹페이지 크롤링, Pipeline/Stage 기반 병렬 실행, 다중 트리거 지원, Rate Limiting 등의 기능을 제공합니다.
|
||||
|
||||
<p align="center">A progressive <a href="http://nodejs.org" target="_blank">Node.js</a> framework for building efficient and scalable server-side applications.</p>
|
||||
<p align="center">
|
||||
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
|
||||
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
|
||||
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/dm/@nestjs/common.svg" alt="NPM Downloads" /></a>
|
||||
<a href="https://circleci.com/gh/nestjs/nest" target="_blank"><img src="https://img.shields.io/circleci/build/github/nestjs/nest/master" alt="CircleCI" /></a>
|
||||
<a href="https://discord.gg/G7Qnnhy" target="_blank"><img src="https://img.shields.io/badge/discord-online-brightgreen.svg" alt="Discord"/></a>
|
||||
<a href="https://opencollective.com/nest#backer" target="_blank"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
|
||||
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
|
||||
<a href="https://paypal.me/kamilmysliwiec" target="_blank"><img src="https://img.shields.io/badge/Donate-PayPal-ff3f59.svg" alt="Donate us"/></a>
|
||||
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://img.shields.io/badge/Support%20us-Open%20Collective-41B883.svg" alt="Support us"></a>
|
||||
<a href="https://twitter.com/nestframework" target="_blank"><img src="https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow" alt="Follow us on Twitter"></a>
|
||||
</p>
|
||||
<!--[](https://opencollective.com/nest#backer)
|
||||
[](https://opencollective.com/nest#sponsor)-->
|
||||
## 주요 기능
|
||||
|
||||
## Description
|
||||
### 크롤링 엔진
|
||||
- **정적 페이지 크롤링**: axios + cheerio 기반 HTML 파싱
|
||||
- **동적 SPA 크롤링**: Playwright 기반 JavaScript 렌더링 지원
|
||||
- **셀렉터 기반 데이터 추출**: CSS 셀렉터로 원하는 데이터만 추출
|
||||
- **속성 추출**: 이미지 URL 등 HTML 속성 추출 지원
|
||||
|
||||
[Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.
|
||||
### Pipeline/Stage 아키텍처
|
||||
- **병렬 실행**: 여러 Stage를 동시에 실행하여 성능 최적화
|
||||
- **실행 기록**: 각 Stage의 실행 이력 및 결과 저장
|
||||
- **메타데이터 기반**: 유연한 설정 및 확장 가능한 구조
|
||||
|
||||
## Project setup
|
||||
### 트리거 시스템
|
||||
- **스케줄 트리거**: Cron 표현식 기반 정기 실행
|
||||
- **이벤트 트리거**: NATS 메시지 기반 이벤트 드리븐 실행
|
||||
- **API 트리거**: REST API 호출로 수동 실행
|
||||
|
||||
```bash
|
||||
$ npm install
|
||||
### 안정성 및 성능
|
||||
- **Rate Limiting**: 도메인별 토큰 버킷 알고리즘으로 요청 제한
|
||||
- **재시도 로직**: Exponential backoff 기반 자동 재시도
|
||||
- **에러 알림**: 실패 시 NATS를 통한 알림 발송
|
||||
- **결과 저장**: MinIO에 크롤링 결과 자동 저장
|
||||
|
||||
## 기술 스택
|
||||
|
||||
### 프레임워크 및 런타임
|
||||
- **NestJS 11**: TypeScript 기반 서버 프레임워크
|
||||
- **Node.js**: JavaScript 런타임
|
||||
|
||||
### 크롤링 및 파싱
|
||||
- **axios**: HTTP 클라이언트
|
||||
- **cheerio**: 서버사이드 jQuery (HTML 파싱)
|
||||
- **playwright**: 브라우저 자동화 (동적 페이지 크롤링)
|
||||
|
||||
### 데이터베이스 및 스토리지
|
||||
- **MongoDB + Mongoose**: NoSQL 데이터베이스
|
||||
- **MinIO**: S3 호환 객체 스토리지
|
||||
|
||||
### 메시징 및 이벤트
|
||||
- **NATS**: 메시지 브로커 (이벤트 트리거 및 알림)
|
||||
|
||||
### 스케줄링 및 인증
|
||||
- **@nestjs/schedule + cron**: 작업 스케줄링
|
||||
- **JWT (jose)**: 토큰 기반 인증 (Microsoft Entra ID 지원)
|
||||
- **Infisical**: 중앙화된 비밀값 관리
|
||||
|
||||
## 아키텍처
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ REST API │
|
||||
│ (JWT Authentication Required) │
|
||||
└────────────────────────┬────────────────────────────────────┘
|
||||
│
|
||||
┌────────────────┼────────────────┐
|
||||
│ │ │
|
||||
┌────▼─────┐ ┌──────▼──────┐ ┌────▼─────┐
|
||||
│ Cron │ │ NATS Event │ │ API │
|
||||
│ Trigger │ │ Trigger │ │ Trigger │
|
||||
└────┬─────┘ └──────┬──────┘ └────┬─────┘
|
||||
│ │ │
|
||||
└────────────────┼────────────────┘
|
||||
│
|
||||
┌──────────▼──────────┐
|
||||
│ Pipeline Engine │
|
||||
│ (병렬 실행 관리) │
|
||||
└──────────┬──────────┘
|
||||
│
|
||||
┌────────────────┼────────────────┐
|
||||
│ │ │
|
||||
┌────▼─────┐ ┌──────▼──────┐ ┌────▼─────┐
|
||||
│ Stage 1 │ │ Stage 2 │ │ Stage 3 │
|
||||
│(EventSrc)│ │ (EventSrc) │ │(EventSrc)│
|
||||
└────┬─────┘ └──────┬──────┘ └────┬─────┘
|
||||
│ │ │
|
||||
┌────▼─────┐ ┌──────▼──────┐ ┌────▼─────┐
|
||||
│ Crawler │ │ Crawler │ │ Crawler │
|
||||
│ Service │ │ Service │ │ Service │
|
||||
└────┬─────┘ └──────┬──────┘ └────┬─────┘
|
||||
│ │ │
|
||||
└────────────────┼────────────────┘
|
||||
│
|
||||
┌──────────▼──────────┐
|
||||
│ MinIO Storage │
|
||||
│ (크롤링 결과 저장) │
|
||||
└─────────────────────┘
|
||||
```
|
||||
|
||||
## Compile and run the project
|
||||
## 설치
|
||||
|
||||
### 필수 요구사항
|
||||
|
||||
- **Node.js**: 18.x 이상
|
||||
- **MongoDB**: 4.x 이상
|
||||
- **NATS**: 2.x 이상
|
||||
- **MinIO**: S3 호환 객체 스토리지
|
||||
- **Infisical**: 비밀값 관리 (선택)
|
||||
|
||||
### 1. 저장소 클론 및 패키지 설치
|
||||
|
||||
```bash
|
||||
# development
|
||||
$ npm run start
|
||||
|
||||
# watch mode
|
||||
$ npm run start:dev
|
||||
|
||||
# production mode
|
||||
$ npm run start:prod
|
||||
git clone https://git.dahyeon.us/dahyeon/crawler.git
|
||||
cd crawler
|
||||
npm install
|
||||
```
|
||||
|
||||
## Run tests
|
||||
### 2. Playwright 브라우저 설치
|
||||
|
||||
```bash
|
||||
# unit tests
|
||||
$ npm run test
|
||||
|
||||
# e2e tests
|
||||
$ npm run test:e2e
|
||||
|
||||
# test coverage
|
||||
$ npm run test:cov
|
||||
npx playwright install chromium
|
||||
```
|
||||
|
||||
## Deployment
|
||||
### 3. 환경 변수 설정
|
||||
|
||||
When you're ready to deploy your NestJS application to production, there are some key steps you can take to ensure it runs as efficiently as possible. Check out the [deployment documentation](https://docs.nestjs.com/deployment) for more information.
|
||||
|
||||
If you are looking for a cloud-based platform to deploy your NestJS application, check out [Mau](https://mau.nestjs.com), our official platform for deploying NestJS applications on AWS. Mau makes deployment straightforward and fast, requiring just a few simple steps:
|
||||
환경별 `.env` 파일을 생성합니다:
|
||||
|
||||
```bash
|
||||
$ npm install -g @nestjs/mau
|
||||
$ mau deploy
|
||||
# 개발 환경
|
||||
cp env-vars/example.env .env.dev
|
||||
|
||||
# 테스트 환경
|
||||
cp env-vars/example.env .env.test
|
||||
|
||||
# 프로덕션 환경
|
||||
cp env-vars/example.env .env.prod
|
||||
```
|
||||
|
||||
With Mau, you can deploy your application in just a few clicks, allowing you to focus on building features rather than managing infrastructure.
|
||||
#### 필수 환경 변수 (Infisical 사용 시)
|
||||
|
||||
## Resources
|
||||
```env
|
||||
# Infisical 설정
|
||||
INFISICAL_SITE_URL=https://app.infisical.com
|
||||
INFISICAL_CLIENT_ID=your-client-id
|
||||
INFISICAL_CLIENT_SECRET=your-client-secret
|
||||
INFISICAL_PROJECT_ID=a33f45fb-7564-4e4e-9931-96201395d110
|
||||
```
|
||||
|
||||
Check out a few resources that may come in handy when working with NestJS:
|
||||
Infisical을 통해 다음 값들을 관리:
|
||||
- `MONGODB_CONNECTION_STRING`: MongoDB 연결 문자열
|
||||
- `NATS_ENDPOINT`: NATS 서버 주소
|
||||
- `NATS_USER`: NATS 사용자명
|
||||
- `NATS_PASS`: NATS 비밀번호
|
||||
- `JWT_CLAIM_AUDIENCE`: JWT 검증 audience
|
||||
- `MICROSOFT_ENTRAID_TENANT_ID`: Azure AD 테넌트 ID
|
||||
- `MINIO_ENDPOINT`: MinIO 서버 주소
|
||||
- `MINIO_ACCESS_KEY`: MinIO 액세스 키
|
||||
- `MINIO_SECRET_KEY`: MinIO 시크릿 키
|
||||
|
||||
- Visit the [NestJS Documentation](https://docs.nestjs.com) to learn more about the framework.
|
||||
- For questions and support, please visit our [Discord channel](https://discord.gg/G7Qnnhy).
|
||||
- To dive deeper and get more hands-on experience, check out our official video [courses](https://courses.nestjs.com/).
|
||||
- Deploy your application to AWS with the help of [NestJS Mau](https://mau.nestjs.com) in just a few clicks.
|
||||
- Visualize your application graph and interact with the NestJS application in real-time using [NestJS Devtools](https://devtools.nestjs.com).
|
||||
- Need help with your project (part-time to full-time)? Check out our official [enterprise support](https://enterprise.nestjs.com).
|
||||
- To stay in the loop and get updates, follow us on [X](https://x.com/nestframework) and [LinkedIn](https://linkedin.com/company/nestjs).
|
||||
- Looking for a job, or have a job to offer? Check out our official [Jobs board](https://jobs.nestjs.com).
|
||||
### 4. TLS 인증서 (선택)
|
||||
|
||||
## Support
|
||||
NATS TLS 연결을 위해 `internal-service-ca.pem` 파일을 프로젝트 루트에 배치합니다.
|
||||
|
||||
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support).
|
||||
## 실행
|
||||
|
||||
## Stay in touch
|
||||
### 개발 모드
|
||||
|
||||
- Author - [Kamil Myśliwiec](https://twitter.com/kammysliwiec)
|
||||
- Website - [https://nestjs.com](https://nestjs.com/)
|
||||
- Twitter - [@nestframework](https://twitter.com/nestframework)
|
||||
```bash
|
||||
npm run start:dev
|
||||
```
|
||||
|
||||
## License
|
||||
### 프로덕션 빌드
|
||||
|
||||
Nest is [MIT licensed](https://github.com/nestjs/nest/blob/master/LICENSE).
|
||||
```bash
|
||||
npm run build
|
||||
npm run start:prod
|
||||
```
|
||||
|
||||
### 환경 전환
|
||||
|
||||
```bash
|
||||
# 테스트 환경
|
||||
NODE_ENV=test npm run start:dev
|
||||
|
||||
# 프로덕션 환경
|
||||
NODE_ENV=prod npm run start:prod
|
||||
```
|
||||
|
||||
## REST API
|
||||
|
||||
서버 실행 후 Swagger 문서: `http://localhost:3000/api`
|
||||
|
||||
### 인증
|
||||
|
||||
모든 API는 JWT 인증이 필요합니다 (일부 Public 엔드포인트 제외).
|
||||
|
||||
```http
|
||||
Authorization: Bearer {JWT_TOKEN}
|
||||
```
|
||||
|
||||
### Pipelinedef 관리
|
||||
|
||||
#### 1. Pipelinedef 생성
|
||||
|
||||
```http
|
||||
POST /api/v1/crawler/pipelinedefs
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"apiVersion": "v1",
|
||||
"trigger": {
|
||||
"type": "always"
|
||||
},
|
||||
"stageIds": ["stage-id-1", "stage-id-2"],
|
||||
"schedule": {
|
||||
"cron": "0 0 * * *",
|
||||
"timezone": "Asia/Seoul"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### 2. Pipelinedef 목록 조회
|
||||
|
||||
```http
|
||||
GET /api/v1/crawler/pipelinedefs?page=1&limit=20
|
||||
```
|
||||
|
||||
#### 3. Pipelinedef 상세 조회
|
||||
|
||||
```http
|
||||
GET /api/v1/crawler/pipelinedefs/{id}
|
||||
```
|
||||
|
||||
#### 4. Pipelinedef 수정
|
||||
|
||||
```http
|
||||
PUT /api/v1/crawler/pipelinedefs/{id}
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"schedule": {
|
||||
"cron": "0 12 * * *"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### 5. Pipelinedef 삭제
|
||||
|
||||
```http
|
||||
DELETE /api/v1/crawler/pipelinedefs/{id}
|
||||
```
|
||||
|
||||
### Stagedef 관리
|
||||
|
||||
#### 1. Stagedef 생성
|
||||
|
||||
```http
|
||||
POST /api/v1/crawler/stagedefs
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"apiVersion": "v1",
|
||||
"name": "Example Crawler",
|
||||
"topic": "crawler.results.example",
|
||||
"eventSource": [
|
||||
{
|
||||
"type": "web",
|
||||
"name": "example-source",
|
||||
"metadatas": [
|
||||
{
|
||||
"key": "url",
|
||||
"value": "https://example.com",
|
||||
"dataType": "string"
|
||||
},
|
||||
{
|
||||
"key": "selectors",
|
||||
"value": "{\"title\":\"h1\",\"content\":\".main\"}",
|
||||
"dataType": "json"
|
||||
},
|
||||
{
|
||||
"key": "dynamic",
|
||||
"value": "false",
|
||||
"dataType": "string"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
#### 2. Stagedef 목록 조회
|
||||
|
||||
```http
|
||||
GET /api/v1/crawler/stagedefs?page=1&limit=20
|
||||
```
|
||||
|
||||
### Pipeline 실행
|
||||
|
||||
#### 1. Pipeline 수동 실행
|
||||
|
||||
```http
|
||||
POST /api/v1/crawler/pipelines/trigger
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"pipelineDefId": "pipeline-def-id",
|
||||
"variables": {
|
||||
"customVar": "value"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### 2. 실행된 Pipeline 목록
|
||||
|
||||
```http
|
||||
GET /api/v1/crawler/pipelines?page=1&limit=20&status=completed
|
||||
```
|
||||
|
||||
**status 옵션**: `completed`, `failed`, `partial`
|
||||
|
||||
#### 3. Pipeline 실행 상세
|
||||
|
||||
```http
|
||||
GET /api/v1/crawler/pipelines/{pipelineId}
|
||||
```
|
||||
|
||||
#### 4. Pipeline의 Stage 목록
|
||||
|
||||
```http
|
||||
GET /api/v1/crawler/pipelines/{pipelineId}/stages
|
||||
```
|
||||
|
||||
### 모니터링
|
||||
|
||||
#### 1. 등록된 스케줄 목록
|
||||
|
||||
```http
|
||||
GET /api/v1/crawler/schedules
|
||||
```
|
||||
|
||||
#### 2. Rate Limit 상태
|
||||
|
||||
```http
|
||||
GET /api/v1/crawler/rate-limits
|
||||
```
|
||||
|
||||
#### 3. 트리거 재로드
|
||||
|
||||
```http
|
||||
POST /api/v1/crawler/triggers/reload
|
||||
```
|
||||
|
||||
#### 4. Health Check (Public)
|
||||
|
||||
```http
|
||||
GET /api/v1/crawler/health
|
||||
```
|
||||
|
||||
## 사용 예시
|
||||
|
||||
### 1. 정적 웹페이지 크롤링
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "web",
|
||||
"name": "news-crawler",
|
||||
"metadatas": [
|
||||
{
|
||||
"key": "url",
|
||||
"value": "https://news.example.com/latest",
|
||||
"dataType": "string"
|
||||
},
|
||||
{
|
||||
"key": "selectors",
|
||||
"value": "{\"title\":\"h2.article-title\",\"summary\":\".article-summary\",\"author\":\".author-name\"}",
|
||||
"dataType": "json"
|
||||
},
|
||||
{
|
||||
"key": "dynamic",
|
||||
"value": "false",
|
||||
"dataType": "string"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### 2. 동적 SPA 페이지 크롤링
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "web",
|
||||
"name": "spa-crawler",
|
||||
"metadatas": [
|
||||
{
|
||||
"key": "url",
|
||||
"value": "https://spa-app.example.com/products",
|
||||
"dataType": "string"
|
||||
},
|
||||
{
|
||||
"key": "selectors",
|
||||
"value": "{\"products\":\".product-item\",\"price\":\".price\"}",
|
||||
"dataType": "json"
|
||||
},
|
||||
{
|
||||
"key": "dynamic",
|
||||
"value": "true",
|
||||
"dataType": "string"
|
||||
},
|
||||
{
|
||||
"key": "waitSelector",
|
||||
"value": ".products-loaded",
|
||||
"dataType": "string"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### 3. 이미지 URL 추출
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "web",
|
||||
"name": "image-crawler",
|
||||
"metadatas": [
|
||||
{
|
||||
"key": "url",
|
||||
"value": "https://gallery.example.com",
|
||||
"dataType": "string"
|
||||
},
|
||||
{
|
||||
"key": "selectors",
|
||||
"value": "{\"title\":\"h1.gallery-title\"}",
|
||||
"dataType": "json"
|
||||
},
|
||||
{
|
||||
"key": "extractAttributes",
|
||||
"value": "{\"imageUrl\":\"img.gallery-image@src\",\"thumbnail\":\"img.thumb@data-src\"}",
|
||||
"dataType": "json"
|
||||
},
|
||||
{
|
||||
"key": "dynamic",
|
||||
"value": "false",
|
||||
"dataType": "string"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### 4. 매일 자정 실행하는 스케줄 설정
|
||||
|
||||
```json
|
||||
{
|
||||
"apiVersion": "v1",
|
||||
"trigger": {
|
||||
"type": "always"
|
||||
},
|
||||
"stageIds": ["stage-id-1"],
|
||||
"schedule": {
|
||||
"cron": "0 0 * * *",
|
||||
"timezone": "Asia/Seoul"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 5. NATS 이벤트로 트리거
|
||||
|
||||
```json
|
||||
{
|
||||
"apiVersion": "v1",
|
||||
"trigger": {
|
||||
"type": "kafka-event",
|
||||
"kafkaEvent": {
|
||||
"topic": "crawler.trigger.news"
|
||||
}
|
||||
},
|
||||
"stageIds": ["stage-id-1"]
|
||||
}
|
||||
```
|
||||
|
||||
## 프로젝트 구조
|
||||
|
||||
```
|
||||
src/
|
||||
├── main.ts # 애플리케이션 진입점
|
||||
├── app.module.ts # 루트 모듈
|
||||
│
|
||||
├── global/ # 글로벌 공유 모듈
|
||||
│ ├── auth/ # JWT 인증
|
||||
│ │ ├── jwt.service.ts
|
||||
│ │ ├── jwt.guard.ts
|
||||
│ │ └── decorators...
|
||||
│ ├── secret/ # Infisical 비밀값 관리
|
||||
│ │ └── secret.service.ts
|
||||
│ ├── database/ # MongoDB 연결
|
||||
│ │ ├── connection.service.ts
|
||||
│ │ ├── schema.ts # Mongoose 스키마
|
||||
│ │ └── types.d.ts
|
||||
│ ├── nats/ # NATS 메시징
|
||||
│ │ └── nats.service.ts
|
||||
│ └── minio/ # MinIO 파일 저장소
|
||||
│ └── minio.service.ts
|
||||
│
|
||||
└── crawler/ # 크롤러 비즈니스 로직
|
||||
├── crawler.module.ts
|
||||
├── crawler.controller.ts # REST API 컨트롤러
|
||||
│
|
||||
├── services/
|
||||
│ ├── crawler.service.ts # HTTP + Playwright 크롤링
|
||||
│ ├── rate-limiter.service.ts # Rate Limiting
|
||||
│ ├── retry.service.ts # 재시도 로직
|
||||
│ ├── stage-executor.service.ts # Stage 실행
|
||||
│ ├── pipeline-engine.service.ts # Pipeline 관리
|
||||
│ └── trigger.service.ts # 트리거 시스템
|
||||
│
|
||||
├── dto/
|
||||
│ ├── common.dto.ts
|
||||
│ ├── create-pipelinedef.dto.ts
|
||||
│ ├── create-stagedef.dto.ts
|
||||
│ └── trigger-pipeline.dto.ts
|
||||
│
|
||||
└── interfaces/
|
||||
└── crawler-result.interface.ts
|
||||
```
|
||||
|
||||
## 데이터베이스 스키마
|
||||
|
||||
### Pipelinedef
|
||||
파이프라인 정의 (재사용 가능한 템플릿)
|
||||
|
||||
```typescript
|
||||
{
|
||||
apiVersion: string; // "v1"
|
||||
trigger: PipelineTrigger; // always | kafka-event
|
||||
stage: ObjectId[]; // Stagedef ID 배열
|
||||
metadatas: Metadata[]; // 커스텀 메타데이터
|
||||
}
|
||||
```
|
||||
|
||||
### Pipeline
|
||||
실행된 파이프라인 인스턴스
|
||||
|
||||
```typescript
|
||||
{
|
||||
apiVersion: string;
|
||||
name: string; // "pipeline-1234567890"
|
||||
stage: Stage[]; // 실행 중인 Stage 배열
|
||||
metadatas: Metadata[]; // 실행 정보 (triggeredBy, status 등)
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
```
|
||||
|
||||
### Stagedef
|
||||
스테이지 정의
|
||||
|
||||
```typescript
|
||||
{
|
||||
apiVersion: string;
|
||||
name: string;
|
||||
taxonomy?: string;
|
||||
eventSource: EventSource[]; // 크롤링 대상 설정
|
||||
topic: string; // NATS 발행 토픽
|
||||
metadatas: Metadata[];
|
||||
}
|
||||
```
|
||||
|
||||
### Stage
|
||||
실행된 스테이지
|
||||
|
||||
```typescript
|
||||
{
|
||||
apiVersion: string;
|
||||
name: string;
|
||||
executions: Execution[]; // 실행 기록
|
||||
status: "pending" | "in-progress" | "completed" | "failed" | "cancelled" | "skipped";
|
||||
metadatas: Metadata[];
|
||||
}
|
||||
```
|
||||
|
||||
### Execution
|
||||
개별 실행 기록
|
||||
|
||||
```typescript
|
||||
{
|
||||
status: "pending" | "in-progress" | "completed" | "failed" | "cancelled" | "skipped";
|
||||
metadatas: Metadata[]; // crawlResult, storageKey 등
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
```
|
||||
|
||||
## Rate Limiting
|
||||
|
||||
### 도메인별 제한 설정
|
||||
|
||||
```typescript
|
||||
// 기본값: 10 req, 초당 2개 보충
|
||||
rateLimiter.setLimit('example.com', {
|
||||
maxTokens: 20, // 최대 20개 토큰
|
||||
refillRate: 5 // 초당 5개 보충
|
||||
});
|
||||
```
|
||||
|
||||
### 현재 상태 조회
|
||||
|
||||
```http
|
||||
GET /api/v1/crawler/rate-limits
|
||||
```
|
||||
|
||||
응답:
|
||||
```json
|
||||
{
|
||||
"example.com": {
|
||||
"config": {
|
||||
"maxTokens": 20,
|
||||
"refillRate": 5
|
||||
},
|
||||
"available": 15
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 재시도 전략
|
||||
|
||||
### RetryStrategy 설정
|
||||
|
||||
```typescript
|
||||
{
|
||||
limit: 3, // 최대 3회 재시도
|
||||
delay: 1000, // 초기 대기 시간 1초
|
||||
backoff: 2, // 2배씩 증가 (1초 → 2초 → 4초)
|
||||
when: [
|
||||
"failed", // 모든 실패
|
||||
"5xx", // 5xx 에러
|
||||
"network" // 네트워크 에러
|
||||
],
|
||||
notify: [
|
||||
"admin-channel" // 실패 시 알림 채널
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## NATS 이벤트
|
||||
|
||||
### 발행되는 이벤트
|
||||
|
||||
#### Pipeline 시작
|
||||
```
|
||||
Topic: crawler.pipeline.started
|
||||
Payload: {
|
||||
pipelineId: string;
|
||||
pipelineDefId: string;
|
||||
triggeredBy: "api" | "schedule" | "nats";
|
||||
timestamp: string;
|
||||
}
|
||||
```
|
||||
|
||||
#### Pipeline 완료
|
||||
```
|
||||
Topic: crawler.pipeline.completed
|
||||
Payload: {
|
||||
pipelineId: string;
|
||||
status: "completed" | "failed" | "partial";
|
||||
triggeredBy: "api" | "schedule" | "nats";
|
||||
stageResults: Array<{
|
||||
stageName: string;
|
||||
status: string;
|
||||
error?: string;
|
||||
}>;
|
||||
completedAt: string;
|
||||
}
|
||||
```
|
||||
|
||||
#### Stage 시작
|
||||
```
|
||||
Topic: crawler.stage.started
|
||||
Payload: {
|
||||
pipelineId: string;
|
||||
stageIndex: number;
|
||||
stageName: string;
|
||||
timestamp: string;
|
||||
}
|
||||
```
|
||||
|
||||
#### Stage 완료 (커스텀 토픽)
|
||||
```
|
||||
Topic: {stagedef.topic}
|
||||
Payload: {
|
||||
pipelineId: string;
|
||||
stageIndex: number;
|
||||
stageName: string;
|
||||
status: "completed" | "failed";
|
||||
results: Array<{
|
||||
url: string;
|
||||
success: boolean;
|
||||
parsedData: object;
|
||||
}>;
|
||||
timestamp: string;
|
||||
}
|
||||
```
|
||||
|
||||
## 개발
|
||||
|
||||
### 테스트
|
||||
|
||||
```bash
|
||||
# 단위 테스트
|
||||
npm run test
|
||||
|
||||
# E2E 테스트
|
||||
npm run test:e2e
|
||||
|
||||
# 커버리지
|
||||
npm run test:cov
|
||||
```
|
||||
|
||||
### 린트
|
||||
|
||||
```bash
|
||||
npm run lint
|
||||
npm run format
|
||||
```
|
||||
|
||||
### 빌드
|
||||
|
||||
```bash
|
||||
npm run build
|
||||
```
|
||||
|
||||
## 트러블슈팅
|
||||
|
||||
### Playwright 브라우저 설치 실패
|
||||
|
||||
```bash
|
||||
# 수동 설치
|
||||
npx playwright install-deps
|
||||
npx playwright install chromium
|
||||
```
|
||||
|
||||
### MongoDB 연결 실패
|
||||
|
||||
- `MONGODB_CONNECTION_STRING` 환경 변수 확인
|
||||
- MongoDB 서버 상태 확인
|
||||
- 네트워크 연결 및 방화벽 설정 확인
|
||||
|
||||
### NATS 연결 실패
|
||||
|
||||
- `NATS_ENDPOINT`, `NATS_USER`, `NATS_PASS` 확인
|
||||
- TLS 인증서 경로 확인 (`internal-service-ca.pem`)
|
||||
- NATS 서버 상태 확인
|
||||
|
||||
### Rate Limit 초과
|
||||
|
||||
```typescript
|
||||
// 도메인별 제한 조정
|
||||
await fetch('http://localhost:3000/api/v1/crawler/rate-limits');
|
||||
// 또는 코드에서 직접 설정
|
||||
rateLimiter.setLimit('slow-domain.com', { maxTokens: 5, refillRate: 1 });
|
||||
```
|
||||
|
||||
## 보안 고려사항
|
||||
|
||||
1. **JWT 인증**: 모든 API 엔드포인트는 JWT 인증 필요
|
||||
2. **비밀값 관리**: Infisical을 통한 중앙화된 비밀값 관리
|
||||
3. **TLS 통신**: NATS 연결 시 TLS 인증서 사용
|
||||
4. **Rate Limiting**: 크롤링 대상 서버 보호
|
||||
5. **Input Validation**: DTO 기반 요청 검증
|
||||
|
||||
## 라이선스
|
||||
|
||||
MIT
|
||||
|
||||
## 작성자
|
||||
|
||||
- Dahyeon
|
||||
- Repository: https://git.dahyeon.us/dahyeon/crawler
|
||||
|
||||
## 기술 지원
|
||||
|
||||
이슈 및 문의: Repository Issues 페이지
|
||||
Reference in new issue
Block a user