Skip to content

Conversation

@efdao
Copy link
Collaborator

@efdao efdao commented Feb 6, 2025

#️⃣ 연관된 이슈>

📝 작업 내용> 이번 PR에서 작업한 내용을 간략히 설명해주세요(이미지 첨부 가능)

  • RedisTempate 작성
  • DiscussionBitmapService에서 {discussionId}:{minuteKey} : byte[2] 형태로 데이터 저장 로직 구현
  • dev환경 테스트용 redis testContainer 설정
  • 데이터 저장, 조회, 변경 테스트 코드 작성

🙏 여기는 꼭 봐주세요! > 리뷰어가 특별히 봐주었으면 하는 부분이 있다면 작성해주세요

Summary by CodeRabbit

  • New Features

    • Integrated support for Redis to enhance backend operations and provide efficient management of discussion-related data.
  • Tests

    • Added automated tests for the DiscussionBitmapService and RedisTemplate to verify the correctness and reliability of the new data handling capabilities.
  • Chores

    • Updated project dependencies, including Redis and Testcontainers, to ensure robust integration and smoother development workflows.

efdao added 5 commits February 6, 2025 11:13
key: {discussionId}:{minuteKey} 로 2byte의 비트맵을 저장

RedisTemplate 사용하여 value를 비트단위로 수정 가능
작성한 RedisTemplate 테스트

DiscussionBitmapService 작동 테스트
@efdao efdao added the 🛠️ BE Backend label Feb 6, 2025
@efdao efdao added this to the 1차 스프린트 milestone Feb 6, 2025
@efdao efdao self-assigned this Feb 6, 2025
@efdao efdao requested a review from kwon204 as a code owner February 6, 2025 02:18
@coderabbitai
Copy link

coderabbitai bot commented Feb 6, 2025

Walkthrough

This pull request integrates Redis support into the backend. It adds a Redis dependency and Testcontainers dependency in the build file. A new Redis configuration class is introduced to enable Redis connectivity with a custom RedisTemplate. Additionally, a service for managing bitmap data in Redis is implemented, along with tests to verify bitmap operations and byte array storage. A test container class is also provided to facilitate running Redis during tests using a Docker container.

Changes

Files Change Summary
backend/build.gradle Added dependency for Redis support and a test dependency for Testcontainers.
backend/.../RedisConfig.java Added a new configuration class providing a Redis connection factory and a customized RedisTemplate for handling binary data.
backend/.../DiscussionBitmapService.java Introduced a service for generating Redis keys, converting timestamps, and performing bitmap initialization and bit-wise operations in Redis.
backend/.../DiscussionBitmapServiceTest.java
backend/.../RedisTemplateTest.java
Added tests for the bitmap service and RedisTemplate operations, verifying initialization, bit manipulation, and byte array storage in Redis.
backend/.../RedisTestContainer.java Added a test container class to launch a Redis Docker container in a development profile, enabling integration tests with Redis.

Sequence Diagram(s)

sequenceDiagram
    actor Client
    participant Service as DiscussionBitmapService
    participant Template as RedisTemplate
    participant Redis as Redis Server

    Client->>Service: initializeBitmap(discussionId, dateTime)
    Service->>Template: Store initial bitmap
    Template->>Redis: SET key with initial bitmap
    Note over Template,Redis: Bitmap initialized

    Client->>Service: setBitValue(discussionId, dateTime, bitOffset, true)
    Service->>Template: SETBIT key at bitOffset
    Template->>Redis: Update bit value
    Note over Template,Redis: Bit operation completed

    Client->>Service: getBitValue(discussionId, dateTime, bitOffset)
    Service->>Template: GETBIT key at bitOffset
    Template->>Redis: Retrieve bit value
    Redis-->>Template: bit value
    Template-->>Service: Return bit value
    Service-->>Client: Deliver result
Loading

Poem

Hoppin' through the code I see,
Redis magic in the spree,
Bitmaps bloom with every byte,
Testing makes our code so light,
A container spins, so fresh and bright!

Happy hops from your coding rabbit!

Tip

🌐 Web search-backed reviews and chat
  • We have enabled web search-based reviews and chat for all users. This feature allows CodeRabbit to access the latest documentation and information on the web.
  • You can disable this feature by setting web_search: false in the knowledge_base settings.
  • Please share any feedback in the Discord discussion.
✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

🪧 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. (Beta)
  • @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.

@efdao efdao linked an issue Feb 6, 2025 that may be closed by this pull request
3 tasks
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: 5

🧹 Nitpick comments (7)
backend/src/main/java/endolphin/backend/global/config/RedisConfig.java (1)

22-25: Consider adding connection pool settings for production use.

The Redis connection factory could benefit from connection pool configuration to handle high concurrent loads efficiently.

 @Bean
 public RedisConnectionFactory redisConnectionFactory() {
-    return new LettuceConnectionFactory(host, port);
+    LettuceConnectionFactory factory = new LettuceConnectionFactory(host, port);
+    factory.setShareNativeConnection(false);  // Each connection is thread-safe
+    return factory;
 }
backend/src/test/java/endolphin/backend/global/redis/DiscussionBitmapServiceTest.java (1)

38-43: Consider extracting bit manipulation logic.

The bit manipulation logic for verification could be moved to a utility class for reuse.

+    private boolean extractBit(byte[] data, int offset) {
+        int byteIndex = offset / 8;
+        int bitPosition = offset % 8;
+        return ((data[byteIndex] >> (7 - bitPosition)) & 1) == 1;
+    }
backend/src/main/java/endolphin/backend/global/redis/DiscussionBitmapService.java (4)

18-20: Add input validation for discussionId.

The method should validate that discussionId is not null to prevent NullPointerException.

 private String buildRedisKey(Long discussionId, long minuteKey) {
+    if (discussionId == null) {
+        throw new IllegalArgumentException("discussionId must not be null");
+    }
     return discussionId + ":" + minuteKey;
 }

25-27: Add input validation for dateTime.

The method should validate that dateTime is not null to prevent NullPointerException.

 private long convertToMinuteKey(LocalDateTime dateTime) {
+    if (dateTime == null) {
+        throw new IllegalArgumentException("dateTime must not be null");
+    }
     return dateTime.toEpochSecond(ZoneOffset.UTC) / 60;
 }

35-41: Consider adding key existence check and make byteSize a constant.

  1. Add a check to prevent overwriting existing data.
  2. Define byteSize as a constant since it's a fixed value.
+    private static final int BITMAP_SIZE_BYTES = 2;
+
     public void initializeBitmap(Long discussionId, LocalDateTime dateTime) {
-        int byteSize = 2;
         long minuteKey = convertToMinuteKey(dateTime);
         String redisKey = buildRedisKey(discussionId, minuteKey);
-        byte[] initialData = new byte[byteSize];
+        if (redisTemplate.hasKey(redisKey)) {
+            throw new IllegalStateException("Bitmap already exists for key: " + redisKey);
+        }
+        byte[] initialData = new byte[BITMAP_SIZE_BYTES];
         redisTemplate.opsForValue().set(redisKey, initialData);
     }

80-84: Add validation for returned data size.

Verify that the returned data is either null or exactly 2 bytes.

     public byte[] getBitmapData(Long discussionId, LocalDateTime dateTime) {
         long minuteKey = convertToMinuteKey(dateTime);
         String redisKey = buildRedisKey(discussionId, minuteKey);
-        return redisTemplate.opsForValue().get(redisKey);
+        byte[] data = redisTemplate.opsForValue().get(redisKey);
+        if (data != null && data.length != BITMAP_SIZE_BYTES) {
+            throw new IllegalStateException("Invalid bitmap data size: " + data.length);
+        }
+        return data;
     }
backend/build.gradle (1)

57-58: Consider adding testcontainers-redis module.

While the core testcontainers dependency is added, consider also adding the Redis-specific module for better Redis container support.

 // test-containers
 testImplementation "org.testcontainers:testcontainers:1.20.4"
+testImplementation "org.testcontainers:testcontainers-redis:1.20.4"
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between dbca849 and b4bb03c.

📒 Files selected for processing (6)
  • backend/build.gradle (1 hunks)
  • backend/src/main/java/endolphin/backend/global/config/RedisConfig.java (1 hunks)
  • backend/src/main/java/endolphin/backend/global/redis/DiscussionBitmapService.java (1 hunks)
  • backend/src/test/java/endolphin/backend/global/redis/DiscussionBitmapServiceTest.java (1 hunks)
  • backend/src/test/java/endolphin/backend/global/redis/RedisTemplateTest.java (1 hunks)
  • backend/src/test/java/endolphin/backend/global/redis/RedisTestContainer.java (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Send PR Notification to Reviewers
🔇 Additional comments (4)
backend/src/main/java/endolphin/backend/global/config/RedisConfig.java (1)

32-42: Consider adding SSL/TLS configuration for secure Redis connections.

For production environments, secure communication with Redis should be configured.

backend/src/test/java/endolphin/backend/global/redis/RedisTestContainer.java (1)

14-14: Consider upgrading Redis version for test container.

The current Redis version (6) is outdated. Consider using a more recent version for testing.

✅ Verification successful

🌐 Web query:

What is the latest stable version of Redis?

Length of output: 1145


Redis Test Container Version Update Needed

  • The test container currently uses redis:6-alpine, which is outdated.
  • As of February 2025, the latest stable Redis version is 7.4. Upgrading to an image like redis:7.4-alpine is recommended.
backend/build.gradle (2)

50-52: LGTM! Redis dependency added correctly.

The Redis starter dependency is correctly added and will provide all necessary Redis components.


3-3: Verify Spring Boot version compatibility.

Spring Boot version 3.4.2 seems incorrect as it's beyond the latest known version.

✅ Verification successful

🌐 Web query:

What is the latest version of Spring Boot?

Length of output: 1427


Subject: Spring Boot version 3.4.2 is Compatible

The Spring Boot version specified (3.4.2) matches the latest stable version as of February 2025. No changes are needed.

Comment on lines +16 to +27
static {
GenericContainer<?> REDIS_CONTAINER =
new GenericContainer<>(DockerImageName.parse(REDIS_DOCKER_IMAGE))
.withExposedPorts(6379)
.withReuse(true);

REDIS_CONTAINER.start();

System.setProperty("spring.data.redis.host", REDIS_CONTAINER.getHost());
System.setProperty("spring.data.redis.port",
REDIS_CONTAINER.getMappedPort(6379).toString());
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider using @DynamicPropertySource instead of static block.

Using a static block for container initialization can cause issues with Spring context lifecycle. Consider using @DynamicPropertySource for better integration with Spring Boot test context.

-    static {
-        GenericContainer<?> REDIS_CONTAINER =
-            new GenericContainer<>(DockerImageName.parse(REDIS_DOCKER_IMAGE))
-                .withExposedPorts(6379)
-                .withReuse(true);
-
-        REDIS_CONTAINER.start();
-
-        System.setProperty("spring.data.redis.host", REDIS_CONTAINER.getHost());
-        System.setProperty("spring.data.redis.port",
-            REDIS_CONTAINER.getMappedPort(6379).toString());
-    }
+    static final GenericContainer<?> REDIS_CONTAINER;
+    
+    static {
+        REDIS_CONTAINER = new GenericContainer<>(DockerImageName.parse(REDIS_DOCKER_IMAGE))
+            .withExposedPorts(6379)
+            .withReuse(true);
+        REDIS_CONTAINER.start();
+    }
+    
+    @DynamicPropertySource
+    static void redisProperties(DynamicPropertyRegistry registry) {
+        registry.add("spring.data.redis.host", REDIS_CONTAINER::getHost);
+        registry.add("spring.data.redis.port", () -> 
+            REDIS_CONTAINER.getMappedPort(6379).toString());
+    }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
static {
GenericContainer<?> REDIS_CONTAINER =
new GenericContainer<>(DockerImageName.parse(REDIS_DOCKER_IMAGE))
.withExposedPorts(6379)
.withReuse(true);
REDIS_CONTAINER.start();
System.setProperty("spring.data.redis.host", REDIS_CONTAINER.getHost());
System.setProperty("spring.data.redis.port",
REDIS_CONTAINER.getMappedPort(6379).toString());
}
static final GenericContainer<?> REDIS_CONTAINER;
static {
REDIS_CONTAINER = new GenericContainer<>(DockerImageName.parse(REDIS_DOCKER_IMAGE))
.withExposedPorts(6379)
.withReuse(true);
REDIS_CONTAINER.start();
}
@DynamicPropertySource
static void redisProperties(DynamicPropertyRegistry registry) {
registry.add("spring.data.redis.host", REDIS_CONTAINER::getHost);
registry.add("spring.data.redis.port", () ->
REDIS_CONTAINER.getMappedPort(6379).toString());
}

Comment on lines +19 to +30
public void testSetAndGetByteArray() {
String key = "test:bytearray";
byte[] expected = new byte[] {10, 20, 30, 40, 50};

// 값 저장
redisTemplate.opsForValue().set(key, expected);

// 값 조회
byte[] actual = redisTemplate.opsForValue().get(key);

assertThat(actual).isEqualTo(expected);
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add more test cases and cleanup.

The test should include more edge cases and cleanup Redis after test execution.

+    @AfterEach
+    void cleanup() {
+        redisTemplate.delete("test:bytearray");
+    }

     @Test
     @DisplayName("작성한 Redis template 테스트")
     public void testSetAndGetByteArray() {
         // ... existing test ...
     }

+    @Test
+    @DisplayName("대용량 바이트 배열 테스트")
+    public void testLargeByteArray() {
+        String key = "test:large:bytearray";
+        byte[] expected = new byte[1024 * 1024]; // 1MB
+        new Random().nextBytes(expected);
+
+        redisTemplate.opsForValue().set(key, expected);
+        byte[] actual = redisTemplate.opsForValue().get(key);
+
+        assertThat(actual).isEqualTo(expected);
+    }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
public void testSetAndGetByteArray() {
String key = "test:bytearray";
byte[] expected = new byte[] {10, 20, 30, 40, 50};
// 값 저장
redisTemplate.opsForValue().set(key, expected);
// 값 조회
byte[] actual = redisTemplate.opsForValue().get(key);
assertThat(actual).isEqualTo(expected);
}
@AfterEach
void cleanup() {
redisTemplate.delete("test:bytearray");
}
@Test
@DisplayName("작성한 Redis template 테스트")
public void testSetAndGetByteArray() {
String key = "test:bytearray";
byte[] expected = new byte[] {10, 20, 30, 40, 50};
// 값 저장
redisTemplate.opsForValue().set(key, expected);
// 값 조회
byte[] actual = redisTemplate.opsForValue().get(key);
assertThat(actual).isEqualTo(expected);
}
@Test
@DisplayName("대용량 바이트 배열 테스트")
public void testLargeByteArray() {
String key = "test:large:bytearray";
byte[] expected = new byte[1024 * 1024]; // 1MB
new Random().nextBytes(expected);
redisTemplate.opsForValue().set(key, expected);
byte[] actual = redisTemplate.opsForValue().get(key);
assertThat(actual).isEqualTo(expected);
}

Comment on lines 21 to 44
public void testInitializeAndBitOperations() {
Long discussionId = 100L;
LocalDateTime dateTime = LocalDateTime.now();

// 1. 초기화: 해당 논의 및 시각에 대해 16비트 크기의 비트맵을 생성하여 Redis에 저장
bitmapService.initializeBitmap(discussionId, dateTime);

// 2. 오프셋 5의 비트를 true로 설정
Boolean previousValue = bitmapService.setBitValue(discussionId, dateTime, 5, true);
// 초기화된 비트맵은 모두 0이므로 이전 값은 false여야 함
assertThat(previousValue).isFalse();

// 3. 수정된 비트 조회: 오프셋 5의 비트 값이 true인지 확인
Boolean bitValue = bitmapService.getBitValue(discussionId, dateTime, 5);
assertThat(bitValue).isTrue();

// 4. 전체 비트맵 데이터 조회 및 검증
byte[] bitmapData = bitmapService.getBitmapData(discussionId, dateTime);
int byteIndex = 5 / 8; // 0
int bitPosition = 5 % 8; // 5
// big-endian 순서로 확인: (7 - bitPosition)
boolean extractedBit = ((bitmapData[byteIndex] >> (7 - bitPosition)) & 1) == 1;
assertThat(extractedBit).isTrue();
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error case tests and boundary checks.

The test should include error cases and boundary checks for bitmap operations.

+    @Test
+    @DisplayName("잘못된 오프셋 값에 대한 예외 처리 테스트")
+    public void testInvalidOffset() {
+        Long discussionId = 100L;
+        LocalDateTime dateTime = LocalDateTime.now();
+        bitmapService.initializeBitmap(discussionId, dateTime);
+
+        assertThatThrownBy(() -> 
+            bitmapService.setBitValue(discussionId, dateTime, -1, true))
+            .isInstanceOf(IllegalArgumentException.class);
+
+        assertThatThrownBy(() -> 
+            bitmapService.setBitValue(discussionId, dateTime, 16, true))
+            .isInstanceOf(IllegalArgumentException.class);
+    }
+
+    @Test
+    @DisplayName("존재하지 않는 비트맵에 대한 예외 처리 테스트")
+    public void testNonExistentBitmap() {
+        Long discussionId = 999L;
+        LocalDateTime dateTime = LocalDateTime.now();
+
+        assertThatThrownBy(() -> 
+            bitmapService.getBitValue(discussionId, dateTime, 0))
+            .isInstanceOf(IllegalStateException.class);
+    }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
public void testInitializeAndBitOperations() {
Long discussionId = 100L;
LocalDateTime dateTime = LocalDateTime.now();
// 1. 초기화: 해당 논의 및 시각에 대해 16비트 크기의 비트맵을 생성하여 Redis에 저장
bitmapService.initializeBitmap(discussionId, dateTime);
// 2. 오프셋 5의 비트를 true로 설정
Boolean previousValue = bitmapService.setBitValue(discussionId, dateTime, 5, true);
// 초기화된 비트맵은 모두 0이므로 이전 값은 false여야 함
assertThat(previousValue).isFalse();
// 3. 수정된 비트 조회: 오프셋 5의 비트 값이 true인지 확인
Boolean bitValue = bitmapService.getBitValue(discussionId, dateTime, 5);
assertThat(bitValue).isTrue();
// 4. 전체 비트맵 데이터 조회 및 검증
byte[] bitmapData = bitmapService.getBitmapData(discussionId, dateTime);
int byteIndex = 5 / 8; // 0
int bitPosition = 5 % 8; // 5
// big-endian 순서로 확인: (7 - bitPosition)
boolean extractedBit = ((bitmapData[byteIndex] >> (7 - bitPosition)) & 1) == 1;
assertThat(extractedBit).isTrue();
}
public void testInitializeAndBitOperations() {
Long discussionId = 100L;
LocalDateTime dateTime = LocalDateTime.now();
// 1. 초기화: 해당 논의 및 시각에 대해 16비트 크기의 비트맵을 생성하여 Redis에 저장
bitmapService.initializeBitmap(discussionId, dateTime);
// 2. 오프셋 5의 비트를 true로 설정
Boolean previousValue = bitmapService.setBitValue(discussionId, dateTime, 5, true);
// 초기화된 비트맵은 모두 0이므로 이전 값은 false여야 함
assertThat(previousValue).isFalse();
// 3. 수정된 비트 조회: 오프셋 5의 비트 값이 true인지 확인
Boolean bitValue = bitmapService.getBitValue(discussionId, dateTime, 5);
assertThat(bitValue).isTrue();
// 4. 전체 비트맵 데이터 조회 및 검증
byte[] bitmapData = bitmapService.getBitmapData(discussionId, dateTime);
int byteIndex = 5 / 8; // 0
int bitPosition = 5 % 8; // 5
// big-endian 순서로 확인: (7 - bitPosition)
boolean extractedBit = ((bitmapData[byteIndex] >> (7 - bitPosition)) & 1) == 1;
assertThat(extractedBit).isTrue();
}
@Test
@DisplayName("잘못된 오프셋 값에 대한 예외 처리 테스트")
public void testInvalidOffset() {
Long discussionId = 100L;
LocalDateTime dateTime = LocalDateTime.now();
bitmapService.initializeBitmap(discussionId, dateTime);
assertThatThrownBy(() ->
bitmapService.setBitValue(discussionId, dateTime, -1, true))
.isInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(() ->
bitmapService.setBitValue(discussionId, dateTime, 16, true))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
@DisplayName("존재하지 않는 비트맵에 대한 예외 처리 테스트")
public void testNonExistentBitmap() {
Long discussionId = 999L;
LocalDateTime dateTime = LocalDateTime.now();
assertThatThrownBy(() ->
bitmapService.getBitValue(discussionId, dateTime, 0))
.isInstanceOf(IllegalStateException.class);
}

Comment on lines +67 to +71
public Boolean getBitValue(Long discussionId, LocalDateTime dateTime, long bitOffset) {
long minuteKey = convertToMinuteKey(dateTime);
String redisKey = buildRedisKey(discussionId, minuteKey);
return redisTemplate.opsForValue().getBit(redisKey, bitOffset);
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add validation for bitOffset range.

Similar to setBitValue, validate that bitOffset is within the valid range.

     public Boolean getBitValue(Long discussionId, LocalDateTime dateTime, long bitOffset) {
+        if (bitOffset < 0 || bitOffset >= BITMAP_SIZE_BYTES * 8) {
+            throw new IllegalArgumentException("bitOffset must be between 0 and " + 
+                (BITMAP_SIZE_BYTES * 8 - 1));
+        }
         long minuteKey = convertToMinuteKey(dateTime);
         String redisKey = buildRedisKey(discussionId, minuteKey);
         return redisTemplate.opsForValue().getBit(redisKey, bitOffset);
     }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
public Boolean getBitValue(Long discussionId, LocalDateTime dateTime, long bitOffset) {
long minuteKey = convertToMinuteKey(dateTime);
String redisKey = buildRedisKey(discussionId, minuteKey);
return redisTemplate.opsForValue().getBit(redisKey, bitOffset);
}
public Boolean getBitValue(Long discussionId, LocalDateTime dateTime, long bitOffset) {
if (bitOffset < 0 || bitOffset >= BITMAP_SIZE_BYTES * 8) {
throw new IllegalArgumentException("bitOffset must be between 0 and " +
(BITMAP_SIZE_BYTES * 8 - 1));
}
long minuteKey = convertToMinuteKey(dateTime);
String redisKey = buildRedisKey(discussionId, minuteKey);
return redisTemplate.opsForValue().getBit(redisKey, bitOffset);
}

Comment on lines +52 to +57
public Boolean setBitValue(Long discussionId, LocalDateTime dateTime, long bitOffset,
boolean value) {
long minuteKey = convertToMinuteKey(dateTime);
String redisKey = buildRedisKey(discussionId, minuteKey);
return redisTemplate.opsForValue().setBit(redisKey, bitOffset, value);
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add validation for bitOffset range.

Since this is a 16-bit bitmap, bitOffset should be between 0 and 15.

     public Boolean setBitValue(Long discussionId, LocalDateTime dateTime, long bitOffset,
         boolean value) {
+        if (bitOffset < 0 || bitOffset >= BITMAP_SIZE_BYTES * 8) {
+            throw new IllegalArgumentException("bitOffset must be between 0 and " + 
+                (BITMAP_SIZE_BYTES * 8 - 1));
+        }
         long minuteKey = convertToMinuteKey(dateTime);
         String redisKey = buildRedisKey(discussionId, minuteKey);
         return redisTemplate.opsForValue().setBit(redisKey, bitOffset, value);
     }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
public Boolean setBitValue(Long discussionId, LocalDateTime dateTime, long bitOffset,
boolean value) {
long minuteKey = convertToMinuteKey(dateTime);
String redisKey = buildRedisKey(discussionId, minuteKey);
return redisTemplate.opsForValue().setBit(redisKey, bitOffset, value);
}
public Boolean setBitValue(Long discussionId, LocalDateTime dateTime, long bitOffset,
boolean value) {
if (bitOffset < 0 || bitOffset >= BITMAP_SIZE_BYTES * 8) {
throw new IllegalArgumentException("bitOffset must be between 0 and " +
(BITMAP_SIZE_BYTES * 8 - 1));
}
long minuteKey = convertToMinuteKey(dateTime);
String redisKey = buildRedisKey(discussionId, minuteKey);
return redisTemplate.opsForValue().setBit(redisKey, bitOffset, value);
}

* LocalDateTime을 분 단위의 long 값(에포크 기준 분 값)으로 변환.
*/
private long convertToMinuteKey(LocalDateTime dateTime) {
return dateTime.toEpochSecond(ZoneOffset.UTC) / 60;
Copy link
Contributor

Choose a reason for hiding this comment

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

p3: 서버 시간이 한국 시간대라서 한국 시간대로 해야 할 거 같습니다.!

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

반영하여 수정했습니다

import org.springframework.data.redis.core.RedisTemplate;

@SpringBootTest
public class RedisTemplateTest {
Copy link
Contributor

Choose a reason for hiding this comment

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

p3: 삭제, 업데이트 테스트 코드도 있으면 좋을 거 같습니다!

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

추가했습니다

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)
backend/src/main/java/endolphin/backend/global/redis/DiscussionBitmapService.java (3)

45-46: Extract byteSize into a constant

Consider defining a constant for the bitmap size instead of using the hardcoded value 2. This improves code readability and makes future adjustments easier.

Apply this diff:

+    private static final int BITMAP_SIZE_BYTES = 2;

     public void initializeBitmap(Long discussionId, LocalDateTime dateTime) {
         try {
-            int byteSize = 2;
+            int byteSize = BITMAP_SIZE_BYTES;

49-50: Set an expiration for the Redis keys

The TODO comment suggests setting an expiration time. It's advisable to define a TTL (Time To Live) for the Redis keys to prevent unused data from persisting indefinitely, which can help manage memory usage effectively.


105-127: Efficiently delete discussion bitmaps using SCAN

The implementation correctly uses SCAN with a pattern to find and delete bitmap keys related to the discussionId. This approach is effective; however, monitor the performance impact if the number of keys is large. If necessary, consider alternative strategies like using key tags or maintaining an index of keys to improve performance.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b4bb03c and aa9e120.

📒 Files selected for processing (2)
  • backend/src/main/java/endolphin/backend/global/redis/DiscussionBitmapService.java (1 hunks)
  • backend/src/test/java/endolphin/backend/global/redis/DiscussionBitmapServiceTest.java (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • backend/src/test/java/endolphin/backend/global/redis/DiscussionBitmapServiceTest.java
🔇 Additional comments (3)
backend/src/main/java/endolphin/backend/global/redis/DiscussionBitmapService.java (3)

34-34: Verify that using ZoneOffset.ofHours(9) aligns with your application's timezone

The method convertToMinuteKey uses ZoneOffset.ofHours(9) (Korea Standard Time) when converting LocalDateTime to epoch seconds. Please ensure that this time zone offset matches your application's expected time zone and the server's configured time zone to prevent any potential time-related issues.


66-71: Add validation for bitOffset range in setBitValue

The method lacks validation for the bitOffset parameter. To ensure correct operation and prevent errors, validate that bitOffset is within the valid range (0 to 15) before proceeding.


81-85: Add validation for bitOffset range in getBitValue

Similarly to setBitValue, add validation for bitOffset in getBitValue to ensure it's within the valid range (0 to 15), preventing potential out-of-bounds access.

Comment on lines +51 to +54
} catch (RedisSystemException e) {
//TODO: 예외 처리
throw e;
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Implement proper exception handling

Currently, the catch block rethrows the exception without additional handling. Consider adding logging or custom exception handling to provide more context and facilitate debugging when an error occurs.

Copy link
Contributor

@kwon204 kwon204 left a comment

Choose a reason for hiding this comment

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

고생하셨습니다.

@efdao efdao merged commit 086f511 into dev Feb 7, 2025
1 check passed
@efdao efdao deleted the feature/be/set-redis branch February 7, 2025 05:20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🛠️ BE Backend

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature] Redis 사용 세팅

3 participants