Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: monitor arg cause npe #86

Merged
merged 7 commits into from
Dec 6, 2024
Merged

Conversation

Rawven
Copy link
Contributor

@Rawven Rawven commented Oct 19, 2024

What's the purpose of this PR

修复当初合并PR #74 时未及时找出来的bug与问题
基于以下仓库持续测试中
apollo-ospp-test apollo-demo-java

Which issue(s) this PR fixes:

Fixes #85

Brief changelog

XXXXX

Follow this checklist to help us incorporate your contribution quickly and easily:

  • [] Read the Contributing Guide before making this pull request.
  • Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
  • Write necessary unit tests to verify the code.
  • Run mvn clean test to make sure this pull request doesn't break anything.
  • Update the CHANGES log.

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Introduced a new DateUtil class for standardized date and time formatting.
    • Enhanced date-time handling in various components for improved accuracy.
    • Added unit tests for the DateUtil class to ensure correct functionality.
  • Bug Fixes

    • Fixed a null pointer exception related to monitor arguments.
    • Updated date formatting for namespace metrics to use the new DateUtil class.
  • Documentation

    • Translated comments to improve clarity for English-speaking users.
  • Refactor

    • Streamlined the process of adding values to bootstrap arguments with a new encapsulated method.
    • Improved logger initialization for better traceability in metrics exporting.
    • Renamed method for retrieving bootstrap arguments for consistency across the API.
    • Changed default value of monitorExternalType for more flexible configuration.

Copy link
Contributor

coderabbitai bot commented Oct 19, 2024

Walkthrough

The changes in this pull request involve modifications to several classes in the apollo-client project. Key updates include the introduction of a DateUtil class for standardized date formatting, enhancements to the ConfigMonitorInitializer to prevent unnecessary logging when the metrics exporter is not enabled, and adjustments in other classes to improve date handling and streamline map updates. These changes collectively aim to enhance the user experience and maintain consistent date formatting across the application.

Changes

File Change Summary
.../ConfigMonitorInitializer.java Added import for StringUtils and modified initializeMetricsExporter to return early under certain conditions.
.../DefaultApolloClientBootstrapArgsApi.java Introduced putAttachmentValue(...) method for consistent map updates and added a new entry for META_FRESH.
.../DefaultApolloClientNamespaceApi.java Updated getNamespaceMetricsString to use DateUtil.formatLocalDateTime() for formatting update time.
.../ApolloClientMonitorMessageProducer.java Added imports for date handling and updated publishMetaServiceEvent to use DateUtil.formatLocalDateTime().
.../util/date/DateUtil.java Added new class DateUtil with MEDIUM_FORMATTER and method formatLocalDateTime(LocalDateTime).
.../ConfigMonitor.java Renamed method getRunningParamsMonitorApi() to getBootstrapArgsMonitorApi().
.../DefaultConfigMonitor.java Renamed method getRunningParamsMonitorApi() to getBootstrapArgsMonitorApi().
.../DefaultConfigMonitorTest.java Updated test to call getBootstrapArgsMonitorApi() instead of getRunningParamsMonitorApi().
.../PrometheusApolloClientMetricsExporter.java Updated logger initialization to use PrometheusApolloClientMetricsExporter.class.
.../util/date/DateUtilTest.java Added unit tests for DateUtil class focusing on formatLocalDateTime method.
CHANGES.md Added entry for bug fix related to null pointer exception caused by monitor argument.

Assessment against linked issues

Objective Addressed Explanation
Prevent redundant logging when metrics exporter is not enabled (#85)
Set default values for monitoring parameters to avoid null pointer issues (#85) No default values were set for monitoring parameters.

Suggested reviewers

  • Anilople

Poem

In the code where rabbits play,
Metrics dance and logs decay.
With dates now bright and clear,
User joy is drawing near!
Hops of change, a joyful cheer! 🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 4f29c75 and 8ce2dac.

📒 Files selected for processing (8)
  • CHANGES.md (1 hunks)
  • apollo-client/src/main/java/com/ctrip/framework/apollo/internals/ConfigMonitorInitializer.java (2 hunks)
  • apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientBootstrapArgsApi.java (2 hunks)
  • apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientNamespaceApi.java (2 hunks)
  • apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/ApolloClientMonitorMessageProducer.java (3 hunks)
  • apollo-client/src/main/java/com/ctrip/framework/apollo/util/ConfigUtil.java (2 hunks)
  • apollo-client/src/main/java/com/ctrip/framework/apollo/util/date/DateUtil.java (1 hunks)
  • apollo-client/src/test/java/com/ctrip/framework/apollo/util/date/DateUtilTest.java (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (6)
  • apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/ApolloClientMonitorMessageProducer.java
  • apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientNamespaceApi.java
  • apollo-client/src/main/java/com/ctrip/framework/apollo/util/date/DateUtil.java
  • apollo-client/src/main/java/com/ctrip/framework/apollo/util/ConfigUtil.java
  • apollo-client/src/test/java/com/ctrip/framework/apollo/util/date/DateUtilTest.java
  • apollo-client/src/main/java/com/ctrip/framework/apollo/internals/ConfigMonitorInitializer.java
🔇 Additional comments (6)
CHANGES.md (1)

14-14: LGTM! Changelog entry is complete and well-formatted.

The new entry properly documents the NPE fix with correct formatting and linking. It maintains consistency with other entries and provides clear information about the changes.

apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientBootstrapArgsApi.java (5)

26-26: LGTM: Import statements are appropriate.

The new imports support the added functionality for date formatting and string handling.

Also applies to: 32-32, 34-37


55-83: LGTM: Improved argument handling and date formatting.

The refactoring to use putAttachmentValue improves consistency and null handling. The date formatting for META_FRESH properly uses Optional to handle potential null values.


91-91: LGTM: Consistent use of putAttachmentValue.

The modification to use putAttachmentValue in collect0 maintains consistency with the rest of the class.


84-84: ⚠️ Potential issue

Empty string initialization of CONFIG_SERVICE_URL may cause issues.

Initializing CONFIG_SERVICE_URL with an empty string could lead to unexpected behavior. Consider using a meaningful default value or omitting the initialization if the value is empty.

-putAttachmentValue(CONFIG_SERVICE_URL,"");
+// Only set CONFIG_SERVICE_URL if a valid value is available
+Optional.ofNullable(configUtil.getConfigServiceUrl())
+    .ifPresent(url -> putAttachmentValue(CONFIG_SERVICE_URL, url));

97-103: 🛠️ Refactor suggestion

Strengthen null handling in putAttachmentValue method.

While the method properly checks for null values, using String.valueOf(value) could cause NPE if the value becomes null due to future code changes. Consider using Optional to make the code more robust.

 private void putAttachmentValue(String argName, Object value) {
   if(StringUtils.isBlank(argName) || value == null) {
     return;
   }
   bootstrapArgs.put(argName, value);
-  bootstrapArgsString.put(argName, String.valueOf(value));
+  bootstrapArgsString.put(argName, Optional.ofNullable(value).map(Object::toString).orElse(""));
 }

Likely invalid or redundant comment.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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 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
Contributor

@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

🧹 Outside diff range and nitpick comments (6)
apollo-client/src/main/java/com/ctrip/framework/apollo/util/date/DateUtil.java (1)

22-26: Enhance class-level Javadoc comment

While the author and date information is provided, it would be beneficial to include a brief description of the class's purpose and functionality. This helps other developers understand the utility's role at a glance.

Consider adding a description like this:

/**
 * Utility class for date and time formatting operations.
 * Provides standardized formatting for LocalDateTime objects.
 *
 * @author Rawven
 * @date 2024/10/19
 */
public class DateUtil {
    // ... existing code ...
}
apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientBootstrapArgsApi.java (2)

94-97: LGTM with suggestion: Add null check in putAttachmentValue method.

The putAttachmentValue method improves code maintainability and ensures consistency between bootstrapArgs and bootstrapArgsString. However, consider adding a null check to prevent potential NullPointerExceptions.

Consider modifying the method as follows:

 private void putAttachmentValue(String argName, Object value) {
   bootstrapArgs.put(argName, value);
-  bootstrapArgsString.put(argName, value.toString());
+  bootstrapArgsString.put(argName, value != null ? value.toString() : "null");
 }

Line range hint 1-114: Overall improvements with some objectives unaddressed.

The changes to DefaultApolloClientBootstrapArgsApi improve code consistency and provide additional useful information (initialization timestamp). However, the modifications don't directly address the issues mentioned in the PR objectives:

  1. Redundant logging when MetricsExporter is not enabled.
  2. Default values for monitoring parameters to prevent null pointer exceptions.

Consider addressing these objectives in this or a follow-up PR to fully meet the goals outlined in issue #85.

apollo-client/src/main/java/com/ctrip/framework/apollo/internals/ConfigMonitorInitializer.java (1)

106-113: LGTM: Early return for disabled metrics exporter

The addition of an early return when the metrics exporter is not enabled effectively addresses the issue of redundant logging mentioned in the PR objectives. This change enhances the Client-Monitor user experience by preventing unnecessary initialization and logging.

A minor suggestion for improvement:

Consider extracting the condition into a separate method for better readability and potential reuse. For example:

private boolean isMetricsExporterDisabled() {
    return StringUtils.isEmpty(m_configUtil.getMonitorExternalType()) 
        || "NONE".equals(m_configUtil.getMonitorExternalType());
}

private static void initializeMetricsExporter() {
    if (isMetricsExporterDisabled()) {
        return;
    }
    // ... rest of the method
}

This extraction would make the main method more concise and the condition more self-explanatory.

apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/ApolloClientMonitorMessageProducer.java (1)

129-129: Improved date-time formatting.

The change from LocalDate.now().toString() to DateUtil.formatLocalDateTime(LocalDateTime.now()) is a good improvement. It provides more precise and standardized date-time formatting, which aligns with the objective of maintaining consistent date handling across the application.

Consider caching the current date-time value if it's used multiple times within the method to avoid repeated calls to LocalDateTime.now().

+ LocalDateTime now = LocalDateTime.now();
- .putAttachment(META_FRESH, DateUtil.formatLocalDateTime(LocalDateTime.now())));
+ .putAttachment(META_FRESH, DateUtil.formatLocalDateTime(now)));
apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientNamespaceApi.java (1)

Line range hint 1-205: Summary: Improved date formatting enhances consistency.

The changes in this file are minimal but impactful. By standardizing the date formatting using DateUtil.formatLocalDateTime(), the code now provides a more consistent and potentially more readable output for namespace metrics. This aligns well with the PR objective of enhancing the user experience.

These changes:

  1. Improve code maintainability by centralizing date formatting logic.
  2. Potentially enhance readability of the output for users and integrating systems.

Consider applying similar date formatting standardization across the entire project for consistency. This could be a good opportunity to create or update coding guidelines regarding date and time handling in the Apollo Client project.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between e43ddf5 and e935f4a.

📒 Files selected for processing (5)
  • apollo-client/src/main/java/com/ctrip/framework/apollo/internals/ConfigMonitorInitializer.java (2 hunks)
  • apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientBootstrapArgsApi.java (2 hunks)
  • apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientNamespaceApi.java (2 hunks)
  • apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/ApolloClientMonitorMessageProducer.java (3 hunks)
  • apollo-client/src/main/java/com/ctrip/framework/apollo/util/date/DateUtil.java (1 hunks)
🧰 Additional context used
🔇 Additional comments (11)
apollo-client/src/main/java/com/ctrip/framework/apollo/util/date/DateUtil.java (1)

1-32: Overall assessment: Good implementation with room for minor improvements

The DateUtil class is a well-structured utility for date formatting, which aligns with the PR objectives of enhancing user experience and maintaining consistent date formatting. The implementation is generally sound, but there are a few areas for improvement:

  1. Enhance the class-level Javadoc with a description of the class's purpose.
  2. Consider making the MEDIUM_FORMATTER field final and possibly private for better encapsulation.
  3. Add method-level Javadoc and null handling to the formatLocalDateTime method.

These suggestions will improve the code's documentation, robustness, and maintainability. Once these minor adjustments are made, the class will be in excellent shape.

apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientBootstrapArgsApi.java (3)

31-31: LGTM: New imports are appropriate for the added functionality.

The addition of DateUtil and LocalDateTime imports aligns with the new date-related functionality in the constructor.

Also applies to: 34-34


52-79: LGTM: Improved code consistency and added initialization timestamp.

The use of putAttachmentValue method improves code consistency and maintainability. The addition of META_FRESH provides a useful timestamp for when the bootstrap args were initialized.


88-88: LGTM: Consistent use of putAttachmentValue method.

The change to use putAttachmentValue in the collect0 method is consistent with the modifications in the constructor and ensures that both bootstrapArgs and bootstrapArgsString are updated.

apollo-client/src/main/java/com/ctrip/framework/apollo/internals/ConfigMonitorInitializer.java (2)

23-23: LGTM: New import for StringUtils

The addition of the StringUtils import is appropriate for the new string checks in the initializeMetricsExporter method.


Line range hint 1-146: Overall assessment: Changes effectively address the PR objectives

The modifications to the ConfigMonitorInitializer class successfully address the issue of redundant logging when the metrics exporter is not enabled. This aligns well with the objectives outlined in the PR and the linked issue #85.

The implementation is clean, focused, and doesn't introduce any apparent issues. It enhances the user experience of the Client-Monitor feature as intended.

apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/ApolloClientMonitorMessageProducer.java (3)

28-31: LGTM: Import statements for improved date handling.

The addition of DateUtil and LocalDateTime imports is appropriate for enhancing date and time handling in the class. This change aligns with the objective of improving date formatting across the application.


102-102: LGTM: Improved comment readability.

The translation of the comment from Chinese to English ("// 不需要收集" to "// No need to collect") enhances code readability for a wider audience. This change aligns with best practices for maintaining English comments in international codebases.


Line range hint 1-205: Overall assessment: Positive changes enhancing code quality.

The modifications in this file contribute to improved date handling, code readability, and consistency. These changes align well with the PR objectives of enhancing the user experience and addressing issues related to the monitoring functionality. The use of DateUtil for standardized date formatting is particularly noteworthy.

No major issues were identified during the review. The suggestions provided are minor and aimed at further optimizing the code.

apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientNamespaceApi.java (2)

31-31: LGTM: DateUtil import added correctly.

The import for DateUtil is appropriately added, which is necessary for the change in the getNamespaceMetricsString method.


186-186: LGTM: Improved date formatting.

The change from toString() to DateUtil.formatLocalDateTime() is a good improvement for standardizing date formatting across the application. This enhances consistency and maintainability.

To ensure this change doesn't affect existing integrations, please run the following verification:

If the search returns any results, those occurrences may need to be updated to use the new DateUtil.formatLocalDateTime() method or to expect the new format.

Copy link

codecov bot commented Oct 19, 2024

Codecov Report

Attention: Patch coverage is 79.06977% with 9 lines in your changes missing coverage. Please review.

Project coverage is 68.65%. Comparing base (d4b76f8) to head (4f29c75).

Files with missing lines Patch % Lines
...nal/tracer/ApolloClientMonitorMessageProducer.java 0.00% 3 Missing ⚠️
...ork/apollo/internals/ConfigMonitorInitializer.java 33.33% 1 Missing and 1 partial ⚠️
...listener/impl/DefaultApolloClientNamespaceApi.java 0.00% 2 Missing ⚠️
...ener/impl/DefaultApolloClientBootstrapArgsApi.java 96.55% 0 Missing and 1 partial ⚠️
...com/ctrip/framework/apollo/util/date/DateUtil.java 75.00% 1 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##               main      #86      +/-   ##
============================================
- Coverage     68.68%   68.65%   -0.03%     
- Complexity     1503     1509       +6     
============================================
  Files           212      213       +1     
  Lines          6396     6407      +11     
  Branches        647      647              
============================================
+ Hits           4393     4399       +6     
- Misses         1673     1679       +6     
+ Partials        330      329       -1     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Copy link
Contributor

@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

🧹 Outside diff range and nitpick comments (1)
apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientBootstrapArgsApi.java (1)

94-97: Consider adding parameter validation.

While the method correctly handles the updates, consider adding validation for the argName parameter to prevent potential NPEs.

 private void putAttachmentValue(String argName, Object value) {
+  if (argName == null) {
+    throw new IllegalArgumentException("argName cannot be null");
+  }
   bootstrapArgs.put(argName, value);
   bootstrapArgsString.put(argName, value == null ? null : value.toString());
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between c35ae02 and 8c308a0.

📒 Files selected for processing (4)
  • apollo-client/src/main/java/com/ctrip/framework/apollo/internals/ConfigMonitorInitializer.java (2 hunks)
  • apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientBootstrapArgsApi.java (2 hunks)
  • apollo-client/src/main/java/com/ctrip/framework/apollo/util/date/DateUtil.java (1 hunks)
  • apollo-plugin/apollo-plugin-client-prometheus/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/impl/PrometheusApolloClientMetricsExporter.java (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • apollo-client/src/main/java/com/ctrip/framework/apollo/internals/ConfigMonitorInitializer.java
  • apollo-client/src/main/java/com/ctrip/framework/apollo/util/date/DateUtil.java
🔇 Additional comments (5)
apollo-plugin/apollo-plugin-client-prometheus/src/main/java/com/ctrip/framework/apollo/monitor/internal/exporter/impl/PrometheusApolloClientMetricsExporter.java (1)

43-43: Good improvement to logger initialization!

The change to use PrometheusApolloClientMetricsExporter.class instead of DefaultApolloClientNamespaceApi.class for logger initialization follows best practices. This ensures that log messages are correctly attributed to their source class, improving traceability and debugging capabilities.

apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientBootstrapArgsApi.java (4)

31-31: LGTM! Appropriate imports added for date handling.

The new imports support the META_FRESH functionality and follow the project's conventions.

Also applies to: 34-34


52-79: LGTM! Improved initialization with consistent method usage and timestamp tracking.

The changes enhance the code by:

  • Using a consistent method for all value assignments
  • Adding META_FRESH timestamp for tracking initialization time

88-88: LGTM! Consistent usage of putAttachmentValue method.

The change ensures atomic updates to both maps and maintains consistency with the rest of the code.


66-67: Verify logging improvement for disabled MetricsExporter.

The PR objectives mention reducing unnecessary logging when MetricsExporter is not enabled. While these lines set the monitor configuration, we should verify if the logging improvement is implemented elsewhere.

✅ Verification successful

Based on the gathered information, I can now generate the final response:

Logging improvement is properly implemented for disabled MetricsExporter

The codebase shows proper handling of disabled monitoring:

  • When monitoring is disabled (isClientMonitorEnabled() == false), a NullApolloClientMetricsExporter is used which only logs a single warning message
  • The monitoring state is checked early in the event publishing flow to prevent unnecessary processing
  • The configuration is properly propagated through ConfigUtil and respected throughout the monitoring system
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for logging related to MetricsExporter
rg -A 5 "MetricsExporter.*not.*enabled" --type java

Length of output: 53


Script:

#!/bin/bash
# Let's search for MetricsExporter class and its usage
ast-grep --pattern 'class MetricsExporter {
  $$$
}'

# Also search for any logging related to metrics or monitoring
rg -A 3 "(?i)(log|logger).*(?:metric|monitor)" --type java

Length of output: 12839


Script:

#!/bin/bash
# Let's search for the implementation of MetricsExporter initialization and configuration
rg -A 5 "class.*MetricsExporter.*implements" --type java

# Also search for where the MetricsExporter is created/configured
rg -A 5 "new.*MetricsExporter" --type java

# Search for configuration related to metrics enabling/disabling
ast-grep --pattern 'isClientMonitorEnabled'

Length of output: 10159


Script:

#!/bin/bash
# Let's check the DefaultApolloClientMetricsExporterFactory implementation to see how it handles disabled state
rg -A 10 "class DefaultApolloClientMetricsExporterFactory" --type java

# Also check for any changes in the initialization of MetricsExporter
rg -A 10 "getMetricsExporter" --type java

Length of output: 12321

Copy link
Contributor

@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

🧹 Outside diff range and nitpick comments (1)
apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/DefaultConfigMonitorTest.java (1)

Line range hint 1-85: Consider adding test cases for the issues mentioned in #85.

The current test suite doesn't cover the specific scenarios mentioned in issue #85:

  1. MetricsExporter disabled state and logging behavior
  2. Default values for monitoring parameters to prevent NPEs

Consider adding these test cases:

@Test
public void testMetricsExporterDisabled() {
    // Given
    when(monitorContext.getMetricsExporter()).thenReturn(null);
    DefaultConfigMonitor configMonitor = new DefaultConfigMonitor();
    
    // When/Then
    assertNull(configMonitor.getExporterData());
}

@Test
public void testBootstrapArgsDefaultValues() {
    // Given
    DefaultConfigMonitor configMonitor = new DefaultConfigMonitor();
    
    // When
    ApolloClientBootstrapArgsMonitorApi api = configMonitor.getBootstrapArgsMonitorApi();
    
    // Then
    assertNotNull(api.getMetaFreshTime()); // Should return default value instead of null
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 8c308a0 and b3f51a4.

📒 Files selected for processing (3)
  • apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ConfigMonitor.java (1 hunks)
  • apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/DefaultConfigMonitor.java (1 hunks)
  • apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/DefaultConfigMonitorTest.java (1 hunks)
🔇 Additional comments (4)
apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/api/ConfigMonitor.java (2)

42-42: LGTM! The method rename improves clarity.

The rename from getRunningParamsMonitorApi to getBootstrapArgsMonitorApi better reflects the actual functionality of retrieving bootstrap arguments.

Let's verify all implementations have been updated:

✅ Verification successful

Let me try a different search strategy to verify the implementations.


Method rename has been properly implemented across the codebase

The verification shows that:

  • The old method name getRunningParamsMonitorApi has no remaining references in the codebase
  • The new method getBootstrapArgsMonitorApi is properly implemented in DefaultConfigMonitor
  • All related test cases have been updated to use the new method name
  • The change is consistently reflected across all relevant files
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any missed implementations or references to the old method name

# Search for any remaining references to the old method name
echo "Checking for any remaining references to getRunningParamsMonitorApi..."
rg "getRunningParamsMonitorApi"

# Search for implementations of ConfigMonitor to verify updates
echo "Checking ConfigMonitor implementations..."
ast-grep --pattern 'class $_ implements ConfigMonitor {
  $$$
}'

Length of output: 342


Script:

#!/bin/bash
# Search for implementations using different patterns

# Find all files that might contain ConfigMonitor implementations
echo "Files containing ConfigMonitor reference:"
rg -l "ConfigMonitor"

# Search for the new method name to verify implementations
echo -e "\nChecking implementations of new method name:"
rg "getBootstrapArgsMonitorApi" -A 2

# Search for files containing ApolloClientBootstrapArgsMonitorApi
echo -e "\nFiles using ApolloClientBootstrapArgsMonitorApi:"
rg -l "ApolloClientBootstrapArgsMonitorApi"

Length of output: 3478


42-42: Update documentation and CHANGES log for this breaking change.

This is a breaking API change that requires:

  1. Documentation updates for the new method name
  2. Entry in the CHANGES log
  3. Migration guide for users updating from previous versions

Let's check for documentation that needs updating:

apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/DefaultConfigMonitor.java (1)

52-52: LGTM! Method name change improves clarity.

The renaming from getRunningParamsMonitorApi to getBootstrapArgsMonitorApi better reflects the actual functionality of retrieving bootstrap arguments.

apollo-client/src/test/java/com/ctrip/framework/apollo/monitor/internal/DefaultConfigMonitorTest.java (1)

67-67: LGTM! Method rename is consistent with the API changes.

The assertion update correctly reflects the method rename from getRunningParamsMonitorApi to getBootstrapArgsMonitorApi.

@nobodyiam
Copy link
Member

@Anilople would you please help to take a look?

@Rawven Rawven changed the title Fix/monitor bug Fix/monitor Oct 27, 2024
@Rawven
Copy link
Contributor Author

Rawven commented Nov 23, 2024

@Anilople PTAL

@Anilople
Copy link
Contributor

@Anilople would you please help to take a look?

Done

@Rawven Please take a look.

Copy link
Contributor

@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: 0

🧹 Outside diff range and nitpick comments (4)
apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientBootstrapArgsApi.java (1)

98-104: Consider thread safety for map updates.

While the current implementation works well for initialization, consider adding synchronization for concurrent modifications:

- private void putAttachmentValue(String argName, Object value) {
+ private synchronized void putAttachmentValue(String argName, Object value) {
    if(StringUtils.isBlank(argName) || value == null) {
      return;
    }
    bootstrapArgs.put(argName, value);
    bootstrapArgsString.put(argName, value.toString());
  }

Alternatively, you could use concurrent map implementations:

private final Map<String, Object> bootstrapArgs = new ConcurrentHashMap<>();
private final Map<String, String> bootstrapArgsString = new ConcurrentHashMap<>();
apollo-client/src/main/java/com/ctrip/framework/apollo/util/date/DateUtil.java (2)

23-27: Enhance class-level documentation

The current documentation only includes author and date. Consider adding a class-level description explaining the purpose and usage of this utility class.

 /**
+ * Utility class providing date formatting functionality for Apollo Client monitoring.
+ * This class standardizes date formatting across the application.
+ *
  * @author Rawven
  * @date 2024/10/19
  */

28-28: Consider making MEDIUM_FORMATTER private

While the formatter is correctly declared as final, consider making it private to prevent external modifications and maintain encapsulation. If external access is needed, provide a getter method.

- public static final DateTimeFormatter MEDIUM_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
+ private static final DateTimeFormatter MEDIUM_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
apollo-client/src/test/java/com/ctrip/framework/apollo/util/date/DateUtilTest.java (1)

26-37: Consider adding more test cases for edge scenarios

While the basic test case is good, consider adding tests for:

  1. Dates at year boundaries (e.g., 9999-12-31 23:59:59)
  2. Different time components (with/without seconds)
  3. Different time zones

Here's an example of additional test cases:

@Test
public void testFormatLocalDateTime_edgeCases() {
    // Test year boundary
    LocalDateTime maxDate = LocalDateTime.of(9999, 12, 31, 23, 59, 59);
    Optional<String> result = DateUtil.formatLocalDateTime(maxDate);
    assertTrue(result.isPresent());
    assertEquals("9999-12-31 23:59:59", result.get());

    // Test minimum date
    LocalDateTime minDate = LocalDateTime.of(1, 1, 1, 0, 0, 0);
    result = DateUtil.formatLocalDateTime(minDate);
    assertTrue(result.isPresent());
    assertEquals("0001-01-01 00:00:00", result.get());
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between b3f51a4 and 8612ef5.

📒 Files selected for processing (7)
  • apollo-client/src/main/java/com/ctrip/framework/apollo/internals/ConfigMonitorInitializer.java (2 hunks)
  • apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientBootstrapArgsApi.java (2 hunks)
  • apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientNamespaceApi.java (2 hunks)
  • apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/ApolloClientMonitorMessageProducer.java (3 hunks)
  • apollo-client/src/main/java/com/ctrip/framework/apollo/util/ConfigUtil.java (2 hunks)
  • apollo-client/src/main/java/com/ctrip/framework/apollo/util/date/DateUtil.java (1 hunks)
  • apollo-client/src/test/java/com/ctrip/framework/apollo/util/date/DateUtilTest.java (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • apollo-client/src/main/java/com/ctrip/framework/apollo/internals/ConfigMonitorInitializer.java
  • apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/ApolloClientMonitorMessageProducer.java
  • apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientNamespaceApi.java
🔇 Additional comments (8)
apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientBootstrapArgsApi.java (4)

26-38: LGTM! Import changes are appropriate.

The new imports support the added functionality for date formatting and null checking.


55-83: LGTM! Good refactoring of map updates.

The change to use putAttachmentValue centralizes the null checking logic and ensures consistent updates to both maps. The addition of monitoring parameters with proper initialization addresses the issue mentioned in PR #85 regarding default values.


84-84: Empty string initialization of CONFIG_SERVICE_URL needs review.

Initializing CONFIG_SERVICE_URL with an empty string may cause issues. Consider:

  1. Using a default value from configUtil
  2. Omitting the initialization if there's no valid default
  3. Using Optional to handle the absence of a value

92-92: LGTM! Consistent use of putAttachmentValue.

The change maintains consistency with the refactoring pattern and ensures proper null checking.

apollo-client/src/main/java/com/ctrip/framework/apollo/util/ConfigUtil.java (2)

559-559: LGTM! Property initialization is consistent with field default

The change to use "" as the fallback value in getProperty maintains consistency with the field's default value, ensuring uniform behavior regardless of initialization path.


77-77: LGTM! Verify the impact on ConfigMonitorInitializer

The change from "NONE" to "" as the default value is appropriate and aligns with the PR objective to prevent redundant logging when monitoring is not configured.

Let's verify the integration with ConfigMonitorInitializer:

✅ Verification successful

LGTM! The change from "NONE" to "" is safe and working as intended

The code review shows that changing monitorExternalType's default value from "NONE" to "" is safe and properly integrated with ConfigMonitorInitializer. The initialization logic in ConfigMonitorInitializer.initializeMetricsExporter() explicitly checks for empty strings using StringUtils.isEmpty() and returns early when the type is empty, which aligns perfectly with the new default value. This change effectively prevents redundant logging while maintaining the expected behavior of skipping metrics initialization when monitoring is not configured.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check how ConfigMonitorInitializer uses monitorExternalType
# Expected: Should find early return condition when type is empty

ast-grep --pattern 'if ($condition) {
  return;
}' apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/ConfigMonitorInitializer.java

Length of output: 285


Script:

#!/bin/bash
# Let's first find the correct path for ConfigMonitorInitializer
fd -t f "ConfigMonitorInitializer.java"

# Then search for any files that use monitorExternalType
rg -l "monitorExternalType"

Length of output: 238


Script:

#!/bin/bash
# Let's check how ConfigMonitorInitializer uses the monitorExternalType
rg -A 5 "monitorExternalType" apollo-client/src/main/java/com/ctrip/framework/apollo/internals/ConfigMonitorInitializer.java

# Also check the complete implementation of ConfigMonitorInitializer
cat apollo-client/src/main/java/com/ctrip/framework/apollo/internals/ConfigMonitorInitializer.java

Length of output: 6531

apollo-client/src/main/java/com/ctrip/framework/apollo/util/date/DateUtil.java (1)

36-39: LGTM! Well-implemented null handling using Optional

The implementation correctly uses Optional to handle null values, addressing the previous review comment. The method is concise and follows functional programming principles.

apollo-client/src/test/java/com/ctrip/framework/apollo/util/date/DateUtilTest.java (1)

39-46: LGTM! Null handling test is well implemented

The test case properly verifies the Optional behavior for null input.

@Rawven
Copy link
Contributor Author

Rawven commented Nov 30, 2024

@Anilople Fixed completed ,sir

Copy link
Contributor

@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: 0

🧹 Outside diff range and nitpick comments (1)
apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientBootstrapArgsApi.java (1)

97-103: Improve null safety in string conversion.

While the null check prevents null values from being processed, using String.valueOf directly could lead to "null" strings being stored if the validation changes in the future. Consider using Optional for more robust null handling.

 private void putAttachmentValue(String argName, Object value) {
   if(StringUtils.isBlank(argName) || value == null) {
     return;
   }
   bootstrapArgs.put(argName, value);
-  bootstrapArgsString.put(argName, String.valueOf(value));
+  bootstrapArgsString.put(argName, Optional.ofNullable(value)
+      .map(Object::toString)
+      .orElse(""));
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 648e5d1 and 4f29c75.

📒 Files selected for processing (7)
  • apollo-client/src/main/java/com/ctrip/framework/apollo/internals/ConfigMonitorInitializer.java (2 hunks)
  • apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientBootstrapArgsApi.java (2 hunks)
  • apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientNamespaceApi.java (2 hunks)
  • apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/ApolloClientMonitorMessageProducer.java (3 hunks)
  • apollo-client/src/main/java/com/ctrip/framework/apollo/util/ConfigUtil.java (2 hunks)
  • apollo-client/src/main/java/com/ctrip/framework/apollo/util/date/DateUtil.java (1 hunks)
  • apollo-client/src/test/java/com/ctrip/framework/apollo/util/date/DateUtilTest.java (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (6)
  • apollo-client/src/main/java/com/ctrip/framework/apollo/internals/ConfigMonitorInitializer.java
  • apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/tracer/ApolloClientMonitorMessageProducer.java
  • apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientNamespaceApi.java
  • apollo-client/src/main/java/com/ctrip/framework/apollo/util/date/DateUtil.java
  • apollo-client/src/test/java/com/ctrip/framework/apollo/util/date/DateUtilTest.java
  • apollo-client/src/main/java/com/ctrip/framework/apollo/util/ConfigUtil.java
🔇 Additional comments (5)
apollo-client/src/main/java/com/ctrip/framework/apollo/monitor/internal/listener/impl/DefaultApolloClientBootstrapArgsApi.java (5)

26-38: LGTM! The new imports support the added functionality.

The added imports for StringUtils, DateUtil, and LocalDateTime are appropriate for the new date formatting and string handling capabilities.


82-83: Good use of Optional for safe date handling.

The use of Optional with DateUtil.formatLocalDateTime ensures null-safe handling of the date value, and the ifPresent consumer provides a clean way to conditionally set the value.


90-91: LGTM! Good use of centralized value setting.

The change to use putAttachmentValue maintains consistency with the rest of the class and ensures proper validation of values.


84-84: ⚠️ Potential issue

Initialization of CONFIG_SERVICE_URL needs improvement.

Initializing CONFIG_SERVICE_URL with an empty string may cause issues. Consider either:

  1. Initializing it with a meaningful default value
  2. Skipping the initialization if there's no valid value
-putAttachmentValue(CONFIG_SERVICE_URL,"");
+// Only set CONFIG_SERVICE_URL if a valid value is available
+Optional.ofNullable(configUtil.getConfigServiceUrl())
+    .ifPresent(url -> putAttachmentValue(CONFIG_SERVICE_URL, url));

69-70: Verify monitor configuration handling.

Let's verify that the monitor configuration is properly handled across the codebase.

✅ Verification successful

Based on the search results, I can verify that the monitor configuration changes are properly integrated across the codebase. Let me explain my findings:

Monitor configuration is properly integrated and tested

The changes are well-integrated because:

  • The configuration constants are properly defined in apollo-core/.../ApolloClientSystemConsts.java
  • The configuration is used consistently across multiple components:
    • ConfigMonitorInitializer for initialization logic
    • DefaultApolloClientMetricsExporterFactory for metrics export
    • ApolloClientBootstrapArgsMonitorApi for API access
    • ConfigUtil for core configuration handling
  • Comprehensive test coverage exists in:
    • ConfigUtilTest for configuration handling
    • ConfigMonitorInitializerTest for initialization
    • DefaultApolloClientMetricsExporterFactoryTest for metrics export
    • ApolloClientMonitorEventPublisherTest for event handling
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for monitor configuration usage
echo "Checking monitor configuration handling..."

# Search for monitor type configuration
echo "Monitor type configuration:"
rg --type java "getMonitorExternalType|APOLLO_CLIENT_MONITOR_EXTERNAL_TYPE"

# Search for monitor enabled configuration
echo "Monitor enabled configuration:"
rg --type java "isClientMonitorEnabled|APOLLO_CLIENT_MONITOR_ENABLED"

# Search for related test cases
echo "Related test cases:"
rg --type java -l "class.*Test.*Monitor" 

Length of output: 7459

Anilople
Anilople previously approved these changes Dec 1, 2024
Copy link
Contributor

@Anilople Anilople left a comment

Choose a reason for hiding this comment

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

LGTM

@Anilople Anilople changed the title Fix/monitor fix: monitor arg cause npe Dec 1, 2024
@Anilople
Copy link
Contributor

Anilople commented Dec 1, 2024

@Rawven
Copy link
Contributor Author

Rawven commented Dec 1, 2024

@Anilople @nobodyiam Done,you can merge it now

@nobodyiam nobodyiam merged commit e64c35b into apolloconfig:main Dec 6, 2024
7 checks passed
@github-actions github-actions bot locked and limited conversation to collaborators Dec 6, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[bug] 修复Client-Monitor存在的问题
3 participants