Skip to content

Conversation

@yuhaowin
Copy link
Contributor

@yuhaowin yuhaowin commented Apr 24, 2025

What's the purpose of this PR

Get instance count by namespaces

Which issue(s) this PR fixes:

For #87

Brief changelog

Added a new feature to get instance count by namespace.

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

  • New Features

    • Added the ability to retrieve the count of instances for a specified namespace within an application, environment, and cluster using the OpenAPI client.
  • Tests

    • Introduced new tests to verify the correct retrieval of instance counts and proper construction of API endpoint paths.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Apr 24, 2025

Walkthrough

A new API interface and its implementation for retrieving the count of instances by namespace were introduced. The ApolloOpenApiClient class was updated to integrate this new service and expose a corresponding public method. Unit tests for the new service and an additional test for path building were added to ensure correct functionality and endpoint construction. The changes are focused on enabling and verifying the ability to query instance counts for a specific namespace via the open API.

Changes

File(s) Change Summary
.../api/InstanceOpenApiService.java Added a new interface with a method to get instance count by namespace.
.../client/service/InstanceOpenApiService.java Added a new class implementing the interface, providing logic to fetch instance count via HTTP GET with validation and error handling.
.../client/ApolloOpenApiClient.java Integrated the new service, added a field, and exposed a new public method delegating to the service implementation.
.../client/service/InstanceOpenApiServiceTest.java Added a new test class to verify the instance count retrieval logic and HTTP request construction.
.../client/url/OpenApiPathBuilderTest.java Added a test case to verify correct path building for the new instance count endpoint.
CHANGES.md Updated changelog to document the new feature for getting instance count by namespace.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant ApolloOpenApiClient
    participant InstanceOpenApiService
    participant HTTP_Server

    Client->>ApolloOpenApiClient: getInstanceCountByNamespace(appId, env, cluster, namespace)
    ApolloOpenApiClient->>InstanceOpenApiService: getInstanceCountByNamespace(appId, env, cluster, namespace)
    InstanceOpenApiService->>HTTP_Server: HTTP GET /envs/{env}/apps/{appId}/clusters/{cluster}/namespaces/{namespace}/instances
    HTTP_Server-->>InstanceOpenApiService: Instance count (JSON)
    InstanceOpenApiService-->>ApolloOpenApiClient: instance count (int)
    ApolloOpenApiClient-->>Client: instance count (int)
Loading

Poem

In the warren of code, a new path appears,
Counting instances—no more guessing, cheers!
With tests to confirm and endpoints so neat,
The client now queries, results are complete.
A hop and a skip, the API’s grown,
Rabbits rejoice—new features are sown! 🐇


📜 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 e5e41ba and 1192c38.

📒 Files selected for processing (1)
  • CHANGES.md (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • CHANGES.md
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build (8)

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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in 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.

@github-actions
Copy link

github-actions bot commented Apr 24, 2025

CLA Assistant Lite bot All contributors have signed the CLA ✍️ ✅

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

🧹 Nitpick comments (4)
apollo-openapi/src/test/java/com/ctrip/framework/apollo/openapi/client/service/InstanceOpenApiServiceTest.java (1)

47-62: Consider adding more comprehensive tests.

While the current test verifies the correct URI construction and HTTP client interaction, consider adding tests for:

  1. Validating the returned count matches the response value
  2. Error handling scenarios when the HTTP request fails
  3. Edge cases with null or empty parameters
  4. Default value handling for clusterName and namespaceName
@Test
public void testGetInstanceCountByNamespaceReturnsCorrectValue() throws Exception {
    // Setup
    StringEntity responseEntity = new StringEntity("42");
    when(someHttpResponse.getEntity()).thenReturn(responseEntity);
    
    // Execute
    int result = instanceOpenApiService.getInstanceCountByNamespace(someAppId, someEnv, someCluster, someNamespace);
    
    // Verify
    assertEquals(42, result);
}

@Test
public void testGetInstanceCountWithDefaultValues() throws Exception {
    // Setup
    StringEntity responseEntity = new StringEntity("1");
    when(someHttpResponse.getEntity()).thenReturn(responseEntity);
    
    // Execute with null cluster and namespace
    instanceOpenApiService.getInstanceCountByNamespace(someAppId, someEnv, null, null);
    
    // Capture and verify the request
    ArgumentCaptor<HttpGet> request = ArgumentCaptor.forClass(HttpGet.class);
    verify(httpClient, times(1)).execute(request.capture());
    HttpGet get = request.getValue();
    
    // Should use default values "default" for cluster and "application" for namespace
    assertTrue(get.getURI().toString().contains("/clusters/default/"));
    assertTrue(get.getURI().toString().contains("/namespaces/application/"));
}

@Test(expected = RuntimeException.class)
public void testGetInstanceCountWithHttpError() throws Exception {
    // Setup
    when(httpClient.execute(any(HttpGet.class))).thenThrow(new IOException("Connection error"));
    
    // This should throw a RuntimeException
    instanceOpenApiService.getInstanceCountByNamespace(someAppId, someEnv, someCluster, someNamespace);
}
apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/client/service/InstanceOpenApiService.java (3)

34-35: Add Javadoc for this method

Consider adding Javadoc to document the purpose of this method, its parameters, return values, and possible exceptions. This would help API consumers understand how to use this method properly.

+/**
+ * Gets the count of instances for a specified namespace.
+ *
+ * @param appId The application ID
+ * @param env The environment
+ * @param clusterName The cluster name (defaults to "default" if null or empty)
+ * @param namespaceName The namespace name (defaults to "application" if null or empty)
+ * @return The number of instances for the specified namespace
+ * @throws RuntimeException if the API call fails
+ */
 @Override
 public int getInstanceCountByNamespace(String appId, String env, String clusterName, String namespaceName) {

46-52: Consider extracting "instances" as a constant

For better maintainability and to avoid hardcoded strings, consider extracting "instances" as a class constant.

+private static final String INSTANCES_RESOURCE = "instances";

 @Override
 public int getInstanceCountByNamespace(String appId, String env, String clusterName, String namespaceName) {
     // existing code...
     
     OpenApiPathBuilder pathBuilder = OpenApiPathBuilder.newBuilder()
             .envsPathVal(env)
             .appsPathVal(appId)
             .clustersPathVal(clusterName)
             .namespacesPathVal(namespaceName)
-            .customResource("instances");
+            .customResource(INSTANCES_RESOURCE);

53-58: Consider using a more specific exception type

The method currently throws a generic RuntimeException. Consider creating or using a more specific exception type to help API consumers better handle different error scenarios.

 try (CloseableHttpResponse response = get(pathBuilder)) {
     return gson.fromJson(EntityUtils.toString(response.getEntity()), Integer.class);
 } catch (Throwable ex) {
-    throw new RuntimeException(String.format("Get instance count: appId: %s, cluster: %s, namespace: %s in env: %s failed",
+    throw new ApolloOpenApiException(String.format("Get instance count: appId: %s, cluster: %s, namespace: %s in env: %s failed",
             appId, clusterName, namespaceName, env), ex);
 }

Note: If ApolloOpenApiException doesn't exist, you would need to create this class or use another appropriate exception type from your codebase.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 27fc0a5 and e5e41ba.

📒 Files selected for processing (5)
  • apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/api/InstanceOpenApiService.java (1 hunks)
  • apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/client/ApolloOpenApiClient.java (4 hunks)
  • apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/client/service/InstanceOpenApiService.java (1 hunks)
  • apollo-openapi/src/test/java/com/ctrip/framework/apollo/openapi/client/service/InstanceOpenApiServiceTest.java (1 hunks)
  • apollo-openapi/src/test/java/com/ctrip/framework/apollo/openapi/client/url/OpenApiPathBuilderTest.java (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (4)
apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/api/InstanceOpenApiService.java (1)
apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/client/service/InstanceOpenApiService.java (1)
  • InstanceOpenApiService (27-60)
apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/client/ApolloOpenApiClient.java (1)
apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/client/service/InstanceOpenApiService.java (1)
  • InstanceOpenApiService (27-60)
apollo-openapi/src/test/java/com/ctrip/framework/apollo/openapi/client/url/OpenApiPathBuilderTest.java (1)
apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/client/url/OpenApiPathBuilder.java (1)
  • OpenApiPathBuilder (34-164)
apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/client/service/InstanceOpenApiService.java (1)
apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/client/url/OpenApiPathBuilder.java (1)
  • OpenApiPathBuilder (34-164)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build (8)
🔇 Additional comments (10)
apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/api/InstanceOpenApiService.java (1)

19-26: Clear and concise API interface design.

The interface is well-defined with a single method that has a clear purpose and appropriate parameters for retrieving the instance count by namespace. The Javadoc indicates this feature is available since version 2.5.0, which aligns with the PR objective of adding a new feature to get instance count by namespace.

apollo-openapi/src/test/java/com/ctrip/framework/apollo/openapi/client/url/OpenApiPathBuilderTest.java (1)

227-240: Appropriate test case for new endpoint path construction.

The test case correctly verifies that the URL path for the instances endpoint is accurately constructed using the expected pattern: "envs/{env}/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/instances". This test follows the same pattern as other service path tests in the file and ensures the consistency of the API path construction.

apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/client/ApolloOpenApiClient.java (4)

25-25: Appropriate import for the new service.

Adding the import for the InstanceOpenApiService is correctly placed with the other service imports, maintaining code organization.


55-55: Consistent field declaration.

The private final field for the instanceService follows the same pattern as other service fields in the class, maintaining consistency in the codebase.


71-71: Proper initialization of the new service.

The instanceService is initialized in the constructor following the same pattern as other services, using the shared HTTP client, base URL, and GSON instance.


249-255: Well-documented public API method.

The getInstanceCountByNamespace method is properly documented with the @SInCE 2.5.0 annotation, and it correctly delegates to the instanceService. This follows the established pattern in the ApolloOpenApiClient class for exposing service functionality.

apollo-openapi/src/test/java/com/ctrip/framework/apollo/openapi/client/service/InstanceOpenApiServiceTest.java (1)

28-45: Good test setup and initialization.

The test class properly extends AbstractOpenApiServiceTest and has a clear setup method that initializes test data and the service under test. The test variables and service initialization follow the established patterns.

apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/client/service/InstanceOpenApiService.java (3)

27-32: Class structure looks good

The class extension and implementation hierarchy is appropriate. The constructor properly passes parameters to the superclass.


36-41: Default parameter values are handled correctly

The code properly handles null or empty parameters by setting default values for clusterName and namespaceName. This aligns with Apollo's convention of using ConfigConsts for default values.


43-44: Input validation is implemented correctly

The code properly validates that required parameters (appId and env) are not empty before proceeding.

@yuhaowin
Copy link
Contributor Author

I have read the CLA Document and I hereby sign the CLA

Copy link
Member

@nobodyiam nobodyiam left a comment

Choose a reason for hiding this comment

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

LGTM

@nobodyiam nobodyiam merged commit 5821922 into apolloconfig:main Apr 25, 2025
7 of 8 checks passed
@github-actions github-actions bot locked and limited conversation to collaborators Apr 25, 2025
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.

2 participants