Skip to content

Conversation

@polyglot-k
Copy link
Contributor

@polyglot-k polyglot-k commented Aug 3, 2025

✨ 구현한 기능

📢 논의하고 싶은 내용

🎸 기타

Summary by CodeRabbit

  • New Features

    • Introduced asynchronous loading and caching of exam quota data, improving performance and responsiveness during application startup.
    • Added a new initializer to ensure exam quota caches are fully loaded before use.
  • Improvements

    • Enhanced cache management for exam quotas with fallback mechanisms and bulk loading capabilities.
    • Improved data completeness in application counts by including exams with no current applications.
    • Added specific error handling and logging for cache operation failures.
  • Refactor

    • Streamlined cache initialization logic for better maintainability and clarity.
    • Replaced hardcoded operation keys with centralized enums for consistency.

@coderabbitai
Copy link

coderabbitai bot commented Aug 3, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

The changes refactor the exam quota caching mechanism. Cache initialization logic is removed from ExamQuotaCacheManager and delegated to new explicit loading methods. A new asynchronous service, ExamQuotaLoadService, is introduced to handle cache population, and a Spring Boot initializer class triggers cache loading at application startup. Repository query logic is adjusted, and an abstract cache initialization method is removed from the base cache manager. Additional improvements include fallback handling for cache atomic operations, enhanced error handling, and the introduction of an OperationType enum.

Changes

Cohort / File(s) Change Summary
ExamQuotaCacheManager Refactor
src/main/java/life/mosu/mosuserver/application/exam/cache/ExamQuotaCacheManager.java
Removed CommandLineRunner implementation and automatic cache initialization. Deleted run and initCache methods. Refactored cache read methods to attempt cache first and fallback to DB if absent. Added fallback mechanism for atomic increment/decrement cache operations with database recovery and retry. Added bulk loading methods for max capacities and current applications. Improved error handling and logging.
New Async Cache Loader Service
src/main/java/life/mosu/mosuserver/application/exam/cache/ExamQuotaLoadService.java
Introduced a service to asynchronously load and cache exam quota data using repository queries. Provides two async methods to load max capacities and current applications, storing results in the cache manager.
Startup Cache Initializer
src/main/java/life/mosu/mosuserver/application/exam/initializer/ExamQuotaCacheInitializer.java
Added a component implementing ApplicationRunner to trigger both cache loading operations in parallel upon application startup, waiting for both to complete.
Repository Query Adjustment
src/main/java/life/mosu/mosuserver/domain/exam/entity/ExamJpaRepository.java
Added method to find exams by ID with exam date filter. Replaced countApplicationsGroupedBySchoolName() with countApplicationsGroupedByExamId() using LEFT JOIN to include exams without applications. Added method to count applications by exam ID.
Base Cache Manager Cleanup
src/main/java/life/mosu/mosuserver/infra/persistence/redis/KeyValueCacheManager.java
Removed the abstract initCache() method and related imports from the base cache manager class.
Atomic Operation Enum and Minor Refactors
src/main/java/life/mosu/mosuserver/application/exam/cache/OperationType.java, AtomicExamQuotaIncrementOperator.java, AtomicExamQuotaDecrementOperator.java
Added OperationType enum for increment/decrement operation keys. Updated increment and decrement operator classes to use enum keys instead of hardcoded strings. Minor formatting and style improvements.
Configuration and Error Codes
src/main/java/life/mosu/mosuserver/global/config/ExamQuotaAtomicOperationConfig.java, src/main/java/life/mosu/mosuserver/global/exception/ErrorCode.java
Replaced hardcoded operator keys with dynamic keys from operator instances in config map. Added new error code CACHE_OPERATION_NOT_SUPPORTED for unsupported cache operations. Minor formatting improvements.

Sequence Diagram(s)

sequenceDiagram
    participant SpringBoot
    participant ExamQuotaCacheInitializer
    participant ExamQuotaLoadService
    participant ExamQuotaCacheManager
    participant ExamJpaRepository

    SpringBoot->>ExamQuotaCacheInitializer: onApplicationStart()
    ExamQuotaCacheInitializer->>ExamQuotaLoadService: loadMaxCapacities() [async]
    ExamQuotaCacheInitializer->>ExamQuotaLoadService: loadCurrentApplications() [async]
    ExamQuotaLoadService->>ExamJpaRepository: fetchUpcomingExamsWithCapacities()
    ExamQuotaLoadService->>ExamQuotaCacheManager: loadMaxCapacities(map)
    ExamQuotaLoadService->>ExamJpaRepository: countApplicationsGroupedByExamId()
    ExamQuotaLoadService->>ExamQuotaCacheManager: loadCurrentApplications(map)
    ExamQuotaCacheInitializer->>ExamQuotaCacheInitializer: Wait for both futures to complete
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15–20 minutes

Possibly related PRs

Poem

🐇 In fields of code where data hops,
Cache refreshed, no more cache stops.
Async loads with futures bright,
Spring boots up, all feels just right.
Increment, decrement, safely done,
Rabbits cheer — the cache has won!
🌿✨🐰


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0a8affc and 4d9804f.

📒 Files selected for processing (8)
  • src/main/java/life/mosu/mosuserver/application/exam/cache/AtomicExamQuotaDecrementOperator.java (3 hunks)
  • src/main/java/life/mosu/mosuserver/application/exam/cache/AtomicExamQuotaIncrementOperator.java (3 hunks)
  • src/main/java/life/mosu/mosuserver/application/exam/cache/ExamQuotaCacheManager.java (3 hunks)
  • src/main/java/life/mosu/mosuserver/application/exam/cache/ExamQuotaLoadService.java (1 hunks)
  • src/main/java/life/mosu/mosuserver/application/exam/cache/OperationType.java (1 hunks)
  • src/main/java/life/mosu/mosuserver/domain/exam/entity/ExamJpaRepository.java (1 hunks)
  • src/main/java/life/mosu/mosuserver/global/config/ExamQuotaAtomicOperationConfig.java (4 hunks)
  • src/main/java/life/mosu/mosuserver/global/exception/ErrorCode.java (1 hunks)
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch refactor/redis-failover

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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests 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.

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Summary of Changes

Hello @polyglot-k, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

I've refactored the Redis cache pre-warming mechanism for exam quotas to address potential data loss and improve miss handling during server synchronization. Previously, the ExamQuotaCacheManager handled its own initialization on startup. This change introduces a dedicated service (ExamQuotaLoadService) to manage the loading of exam capacities and current application counts from the database, and an initializer (ExamQuotaCacheInitializer) that orchestrates this loading asynchronously when the application starts. Additionally, I've updated a database query to ensure all exams are correctly included in application counts, preventing potential data misses in the cache.

Highlights

  • Refactored Cache Initialization: I've refactored the cache pre-warming logic by extracting it from ExamQuotaCacheManager into a new ExamQuotaLoadService and an ExamQuotaCacheInitializer component. This separation of concerns makes the cache management more modular and maintainable.
  • Asynchronous Cache Loading: The new ExamQuotaCacheInitializer now leverages CompletableFuture to load exam capacities and current application counts in parallel on application startup. This asynchronous approach improves the efficiency and speed of cache pre-warming.
  • Enhanced Data Consistency: To ensure the cache is populated with complete and accurate data, I've updated the countApplicationsGroupedBySchoolName query in ExamJpaRepository to use a RIGHT JOIN. This change guarantees that all exams, including those that currently have no applications, are correctly included in the dataset used for cache population, preventing potential data misses.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in issue comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments or fill out our survey to provide feedback.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request refactors the Redis cache pre-warming logic. The initialization is moved into a dedicated ExamQuotaLoadService and an ApplicationRunner (ExamQuotaCacheInitializer), which allows for parallel execution of loading tasks to improve application startup time. Additionally, a bug in the exam application counting query is fixed by using a RIGHT JOIN. The changes are well-structured and improve both performance and correctness. I have a critical suggestion to prevent a potential NullPointerException during cache loading and a medium-severity suggestion to improve logging in the cache initializer for better observability.

Comment on lines 27 to 31
.stream()
.collect(Collectors.toMap(
ExamJpaEntity::getId,
e -> e.getCapacity().longValue()
));

Choose a reason for hiding this comment

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

critical

The code assumes that exam.getCapacity() will never be null. However, the capacity field in ExamJpaEntity is of type Integer, which is nullable. If any ExamJpaEntity returned from the repository has a null capacity, calling .longValue() on it will result in a NullPointerException. This would cause the cache initialization to fail and prevent the application from starting. It's safer to handle this possibility, for example by filtering out entities with a null capacity before collecting them into a map.

Suggested change
.stream()
.collect(Collectors.toMap(
ExamJpaEntity::getId,
e -> e.getCapacity().longValue()
));
.stream()
.filter(e -> e.getCapacity() != null)
.collect(Collectors.toMap(
ExamJpaEntity::getId,
e -> e.getCapacity().longValue()
));

CompletableFuture<Void> maxCapFuture = loadService.loadMaxCapacities();
CompletableFuture<Void> currAppFuture = loadService.loadCurrentApplications();

CompletableFuture.allOf(maxCapFuture, currAppFuture).join();

Choose a reason for hiding this comment

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

medium

While CompletableFuture.allOf(...).join() correctly waits for initialization and propagates exceptions, it would be beneficial for maintainability and debugging to wrap this call in a try-catch block. This allows for explicit logging of success or failure of the cache initialization process. A clear log message upon failure can significantly speed up diagnosing startup issues.

For example:

// Add @Slf4j to the class
try {
    CompletableFuture.allOf(maxCapFuture, currAppFuture).join();
    log.info("Exam quota cache initialized successfully.");
} catch (Exception e) {
    log.error("Failed to initialize exam quota cache.", e);
    throw e; // Re-throw to ensure application startup fails
}

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: 3

🧹 Nitpick comments (1)
src/main/java/life/mosu/mosuserver/application/exam/cache/ExamQuotaLoadService.java (1)

33-33: Consider using asynchronous execution properly.

Returning CompletableFuture.completedFuture(null) defeats the purpose of @Async annotation since all work is completed synchronously before returning the future.

Consider restructuring to make the cache loading truly asynchronous:

-        examQuotaCacheManager.loadMaxCapacities(maxCapacities);
-        return CompletableFuture.completedFuture(null);
+        return CompletableFuture.runAsync(() -> 
+            examQuotaCacheManager.loadMaxCapacities(maxCapacities));

Alternatively, if the current approach is intentional, consider removing the @Async annotation and returning void.

Also applies to: 46-46

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 24c926e and 0a8affc.

📒 Files selected for processing (5)
  • src/main/java/life/mosu/mosuserver/application/exam/cache/ExamQuotaCacheManager.java (2 hunks)
  • src/main/java/life/mosu/mosuserver/application/exam/cache/ExamQuotaLoadService.java (1 hunks)
  • src/main/java/life/mosu/mosuserver/application/exam/initializer/ExamQuotaCacheInitializer.java (1 hunks)
  • src/main/java/life/mosu/mosuserver/domain/exam/entity/ExamJpaRepository.java (1 hunks)
  • src/main/java/life/mosu/mosuserver/infra/persistence/redis/KeyValueCacheManager.java (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: build-and-deploy
🔇 Additional comments (3)
src/main/java/life/mosu/mosuserver/infra/persistence/redis/KeyValueCacheManager.java (1)

12-16: LGTM! Clean removal of abstract cache initialization.

The removal of the abstract initCache() method properly decouples cache initialization from cache management, allowing for more flexible initialization patterns through dedicated services.

src/main/java/life/mosu/mosuserver/domain/exam/entity/ExamJpaRepository.java (1)

41-41: Good change to include all exams in the result set.

Changing from JOIN to RIGHT JOIN ensures that all exams are included in the count, even those with zero applications. This supports comprehensive cache pre-warming and reduces potential cache misses.

src/main/java/life/mosu/mosuserver/application/exam/cache/ExamQuotaCacheManager.java (1)

91-97: LGTM! Clean separation of cache loading from cache management.

The new loadMaxCapacities and loadCurrentApplications methods provide a clean interface for bulk cache population while delegating to existing setter methods. This maintains consistency and reuses existing validation/error handling logic.

Comment on lines 23 to 34
@Async
@Transactional(readOnly = true)
public CompletableFuture<Void> loadMaxCapacities() {
var maxCapacities = examJpaRepository.findByExamDateAfter(LocalDate.now())
.stream()
.collect(Collectors.toMap(
ExamJpaEntity::getId,
e -> e.getCapacity().longValue()
));
examQuotaCacheManager.loadMaxCapacities(maxCapacities);
return CompletableFuture.completedFuture(null);
}
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 handling for database operations.

Both methods lack error handling. Database failures could cause application startup to fail without clear error messages.

Consider adding try-catch blocks with appropriate logging:

    @Async
    @Transactional(readOnly = true)
    public CompletableFuture<Void> loadMaxCapacities() {
+       try {
            var maxCapacities = examJpaRepository.findByExamDateAfter(LocalDate.now())
                    .stream()
                    .filter(e -> e.getCapacity() != null)
                    .collect(Collectors.toMap(
                            ExamJpaEntity::getId,
                            e -> e.getCapacity().longValue()
                    ));
            examQuotaCacheManager.loadMaxCapacities(maxCapacities);
+           log.info("Successfully loaded {} max capacities to cache", maxCapacities.size());
+       } catch (Exception e) {
+           log.error("Failed to load max capacities to cache", e);
+           throw e;
+       }
        return CompletableFuture.completedFuture(null);
    }

Also applies to: 36-47

🤖 Prompt for AI Agents
In
src/main/java/life/mosu/mosuserver/application/exam/cache/ExamQuotaLoadService.java
around lines 23 to 34, the loadMaxCapacities method lacks error handling for
database operations, which could cause silent failures. Wrap the database call
and subsequent processing in a try-catch block, catch any exceptions, and log an
appropriate error message to ensure failures are visible and handled gracefully.
Apply the same pattern to the method spanning lines 36 to 47.

Comment on lines 26 to 31
var maxCapacities = examJpaRepository.findByExamDateAfter(LocalDate.now())
.stream()
.collect(Collectors.toMap(
ExamJpaEntity::getId,
e -> e.getCapacity().longValue()
));
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 null safety check for exam capacity.

The conversion e.getCapacity().longValue() could throw a NullPointerException if the capacity is null.

        var maxCapacities = examJpaRepository.findByExamDateAfter(LocalDate.now())
                .stream()
+               .filter(e -> e.getCapacity() != null)
                .collect(Collectors.toMap(
                        ExamJpaEntity::getId,
                        e -> e.getCapacity().longValue()
                ));
📝 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
var maxCapacities = examJpaRepository.findByExamDateAfter(LocalDate.now())
.stream()
.collect(Collectors.toMap(
ExamJpaEntity::getId,
e -> e.getCapacity().longValue()
));
var maxCapacities = examJpaRepository.findByExamDateAfter(LocalDate.now())
.stream()
.filter(e -> e.getCapacity() != null)
.collect(Collectors.toMap(
ExamJpaEntity::getId,
e -> e.getCapacity().longValue()
));
🤖 Prompt for AI Agents
In
src/main/java/life/mosu/mosuserver/application/exam/cache/ExamQuotaLoadService.java
around lines 26 to 31, the code calls e.getCapacity().longValue() without
checking if getCapacity() returns null, which can cause a NullPointerException.
To fix this, add a null check for e.getCapacity() before calling longValue(),
and provide a default value (e.g., 0L) if it is null to ensure null safety.

Comment on lines +20 to +25
public void run(ApplicationArguments args) {
CompletableFuture<Void> maxCapFuture = loadService.loadMaxCapacities();
CompletableFuture<Void> currAppFuture = loadService.loadCurrentApplications();

CompletableFuture.allOf(maxCapFuture, currAppFuture).join();
}
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 adding timeout and error handling for startup robustness.

The current implementation blocks indefinitely on join() and lacks error handling, which could cause application startup failures or hangs.

Consider adding timeout and graceful error handling:

    @Override
    public void run(ApplicationArguments args) {
+       try {
            CompletableFuture<Void> maxCapFuture = loadService.loadMaxCapacities();
            CompletableFuture<Void> currAppFuture = loadService.loadCurrentApplications();

-           CompletableFuture.allOf(maxCapFuture, currAppFuture).join();
+           CompletableFuture.allOf(maxCapFuture, currAppFuture)
+               .orTimeout(30, TimeUnit.SECONDS)
+               .join();
+           log.info("Cache initialization completed successfully");
+       } catch (Exception e) {
+           log.error("Cache initialization failed, application may have degraded performance", e);
+           // Consider whether to fail fast or continue with empty cache
+       }
    }

You'll need to add these imports:

import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;
🤖 Prompt for AI Agents
In
src/main/java/life/mosu/mosuserver/application/exam/initializer/ExamQuotaCacheInitializer.java
around lines 20 to 25, the current use of CompletableFuture.allOf(...).join()
blocks indefinitely without timeout or error handling, risking startup hangs.
Modify the code to use a timeout with get(timeout, TimeUnit) instead of join(),
and wrap the call in a try-catch block to handle TimeoutException,
InterruptedException, and ExecutionException. Log any exceptions using a logger
(add @Slf4j annotation to the class) and ensure the application can handle these
errors gracefully during startup.

@polyglot-k polyglot-k merged commit 223ec2e into develop Aug 4, 2025
1 of 2 checks passed
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.

[🛠 리팩토링] 서버가 동기화 될 때 Pre-Warm Redis 정보가 유실되는 경우 발생

1 participant