Skip to content

Conversation

@kshmaker
Copy link
Collaborator

@kshmaker kshmaker commented Mar 13, 2025

health check

Summary by CodeRabbit

  • 새로운 기능
    • 헬스 체크 기능이 도입되어 애플리케이션의 상태를 실시간으로 모니터링할 수 있습니다.
    • 외부 서비스, 데이터베이스 연결, 메모리 사용량 등의 지표를 확인할 수 있는 새로운 엔드포인트가 추가되었습니다.

@kshmaker kshmaker linked an issue Mar 13, 2025 that may be closed by this pull request
@coderabbitai
Copy link

coderabbitai bot commented Mar 13, 2025

📝 Walkthrough

Walkthrough

이번 변경사항은 NestJS 애플리케이션에 헬스 체크 기능을 추가합니다. package.json@nestjs/terminus 의존성이 추가되었으며, src/app.module.ts 파일에 헬스 관련 모듈과 컨트롤러가 포함되었습니다. 또한, 새로운 HealthModuleHealthController가 도입되어 외부 서비스, 데이터베이스 및 메모리 상태를 점검하는 헬스 체크 엔드포인트를 제공합니다.

Changes

파일/디렉토리 변경 요약
package.json @nestjs/terminus 의존성이 ^11.0.0 버전으로 추가됨
src/app.module.ts importsHealthModule, controllersHealthController 추가
src/health/health.controller.ts
src/health/health.module.ts
헬스 체크 기능을 위한 HealthControllerHealthModule 신규 도입 (헬스 검사, 구성, DB 체크)

Sequence Diagram(s)

sequenceDiagram
    participant C as Client
    participant HC as HealthController
    participant TM as TerminusModule
    participant DB as PrismaService

    C->>HC: GET /health 요청
    HC->>TM: 헬스 체크 실행 (HTTP, 메모리, DB)
    TM-->>HC: 헬스 상태 응답 (Aggregate 결과)
    HC->>C: 헬스 상태 결과 반환
Loading

Poem

나는 귀여운 토끼, 코드 속을 뛰어다니며,
새로운 헬스 체크 기능에 마음이 날아가네.
모듈과 컨트롤러, 함께 춤추며,
시스템 건강을 살피는 멋진 이야기!
🐰 코드 정원에서 오늘도 반짝반짝 빛나네!

Tip

⚡🧪 Multi-step agentic review comment chat (experimental)
  • We're introducing multi-step agentic chat in review comments. This experimental feature enhances review discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments.
    - To enable this feature, set early_access to true under in the settings.
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@kshmaker kshmaker requested a review from controlZ March 13, 2025 07:59
@kshmaker kshmaker self-assigned this Mar 13, 2025
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (3)
src/health/health.module.ts (1)

16-17: HealthController를 exports에 추가하고 빈 providers 배열 제거 권장

현재 HealthModule에는 빈 providers 배열이 있습니다. 필요하지 않은 경우 이를 제거하는 것이 좋습니다. 또한, AppModule에서 HealthController를 직접 사용할 수 있도록 controllers를 exports에 추가하는 것이 필요합니다.

@Module({
  imports: [
    TerminusModule.forRoot({
      errorLogStyle: 'pretty',
      logger: true,
    }),
    CustomConfigModule,
    PrismaModule,
  ],
-  providers: [],
  controllers: [HealthController],
+  exports: [HealthController],
})
export class HealthModule {}

또는 AppModule에서 HealthController를 직접 선언하지 않고 HealthModule만 가져오는 방식이 더 바람직합니다.

src/health/health.controller.ts (2)

27-37: 헬스체크 로직 개선 제안

헬스체크 엔드포인트가 잘 구현되었습니다. 다음 개선사항을 고려해보세요:

  1. 메모리 제한(150MB)을 하드코딩하는 대신 CustomConfigService를 통해 구성 가능하게 만들면 환경에 따라 유연하게 조정할 수 있습니다.
  2. 외부 서비스 URL이 비어있거나 잘못된 형식인 경우에 대한 예외 처리가 필요할 수 있습니다.
  3. 디스크 공간 사용량 같은 추가적인 헬스 지표를 고려해보세요.
@Get()
@HealthCheck()
async check() {
  this.logger.log('Health check');
  return this.health.check([
    () =>
-     this.http.pingCheck('infoteam-idp', this.configService.IDP_BASE_URL),
+     this.configService.IDP_BASE_URL 
+       ? this.http.pingCheck('infoteam-idp', this.configService.IDP_BASE_URL)
+       : Promise.resolve({ infoteam_idp: { status: 'down', message: 'IDP_BASE_URL not configured' }}),
    () => this.prisma.pingCheck('database', this.prismaService),
-   () => this.memory.checkRSS('memory_rss', 1024 * 1024 * 150),
+   () => this.memory.checkRSS('memory_rss', this.configService.MEMORY_LIMIT_MB * 1024 * 1024 || 1024 * 1024 * 150),
  ]);
}

1-13: Swagger API 문서에 더 자세한 정보 추가 제안

현재 헬스체크 엔드포인트에는 @ApiTags('health') 데코레이터만 적용되어 있습니다. API 소비자에게 더 많은 정보를 제공하기 위해 다음과 같은 추가 데코레이터를 고려해보세요:

import { Controller, Get, Logger } from '@nestjs/common';
import { CustomConfigService } from '@lib/custom-config';
import { PrismaService } from '@lib/prisma';
import {
  HealthCheck,
  HealthCheckService,
  HttpHealthIndicator,
  MemoryHealthIndicator,
  PrismaHealthIndicator,
} from '@nestjs/terminus';

-import { ApiTags } from '@nestjs/swagger';
+import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';

@ApiTags('health')
@Controller('health')
export class HealthController {

그리고 check 메서드에 다음과 같은 데코레이터를 추가하는 것이 좋습니다:

@Get()
@HealthCheck()
+@ApiOperation({ summary: '애플리케이션 상태 확인', description: '외부 서비스, 데이터베이스, 메모리 사용량을 확인합니다.' })
+@ApiResponse({ status: 200, description: '모든 서비스가 정상 작동 중' })
+@ApiResponse({ status: 503, description: '하나 이상의 서비스에 문제가 있음' })
async check() {
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8f7f270 and b3876b6.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (4)
  • package.json (1 hunks)
  • src/app.module.ts (1 hunks)
  • src/health/health.controller.ts (1 hunks)
  • src/health/health.module.ts (1 hunks)
🔇 Additional comments (1)
package.json (1)

32-32: 헬스체크 기능을 위한 @nestjs/terminus 패키지 추가

NestJS 애플리케이션의 상태 모니터링을 위한 terminus 패키지가 적절히 추가되었습니다.

Comment on lines +7 to +8
import { HealthController } from './health/health.controller';
import { HealthModule } from './health/health.module';
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

HealthController를 AppModule에 직접 등록하지 말고 HealthModule을 통해서만 접근하는 것이 좋습니다

현재 구조에서는 HealthController가 두 곳에서 선언되고 있습니다:

  1. AppModule의 controllers 배열에 직접 포함
  2. HealthModule의 controllers 배열에도 포함

NestJS의 모듈 패턴에 따르면, 컨트롤러는 일반적으로 특정 모듈 내에서만 선언되고, 해당 모듈을 가져오면 컨트롤러도 자동으로 사용 가능해집니다. 따라서 다음과 같이 수정하는 것이 좋습니다:

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { UserModule } from './user/user.module';
import { ImageModule } from './image/image.module';
import { EmailModule } from './email/email.module';
-import { HealthController } from './health/health.controller';
import { HealthModule } from './health/health.module';

@Module({
  imports: [UserModule, ImageModule, EmailModule, HealthModule],
-  controllers: [AppController, HealthController],
+  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

Also applies to: 11-12

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

health check 만들기

2 participants