Repository: apolloconfig/apollo
Pull request #5381: [issue-87][apollo-java]: Added a new feature to get instance count by namespace.
Author: login: yuhaowin
Labels: name: size:M
description: This PR changes 30-99 lines, ignoring generated files.
name: lgtm
description: This PR has been approved by a maintainer
Created: 2025-04-24T17:15:47Z | Merged: 2025-04-25T01:26:31Z

## What's the purpose of this PR

Get instance count by namespaces

## Which issue(s) this PR fixes:
For #[87](https://github.com/apolloconfig/apollo-java/issues/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:

- [x] Read the [Contributing Guide](https://github.com/apolloconfig/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/apolloconfig/apollo/blob/master/CHANGES.md).


<!-- This is an auto-generated comment: release notes by coderabbit.ai -->
## Summary by CodeRabbit

- **New Features**
  - Added a new REST API endpoint to retrieve the count of instances for a specific namespace, accessible via the OpenAPI.
  - Users can now query instance counts by specifying application ID, environment, cluster name, and namespace name.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->


Diff:
diff --git a/CHANGES.md b/CHANGES.md
index 807bbb2a054..04fa00d569b 100644
--- a/CHANGES.md
+++ b/CHANGES.md
@@ -11,6 +11,7 @@ Apollo 2.5.0
 * [Feature: Provide a new open API to return the organization list](https://github.com/apolloconfig/apollo/pull/5365)
 * [Refactor: Exception handler adds root cause information](https://github.com/apolloconfig/apollo/pull/5367)
 * [Feature: Enhanced parameter verification for edit item](https://github.com/apolloconfig/apollo/pull/5376)
+* [Feature: Added a new feature to get instance count by namespace.](https://github.com/apolloconfig/apollo/pull/5381)
 
 ------------------
 All issues and pull requests are [here](https://github.com/apolloconfig/apollo/milestone/16?closed=1)
diff --git a/apollo-portal/src/main/java/com/ctrip/framework/apollo/openapi/server/service/ServerInstanceOpenApiService.java b/apollo-portal/src/main/java/com/ctrip/framework/apollo/openapi/server/service/ServerInstanceOpenApiService.java
new file mode 100644
index 00000000000..e93c5c9731b
--- /dev/null
+++ b/apollo-portal/src/main/java/com/ctrip/framework/apollo/openapi/server/service/ServerInstanceOpenApiService.java
@@ -0,0 +1,37 @@
+/*
+ * Copyright 2024 Apollo Authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+package com.ctrip.framework.apollo.openapi.server.service;
+
+import com.ctrip.framework.apollo.openapi.api.InstanceOpenApiService;
+import com.ctrip.framework.apollo.portal.environment.Env;
+import com.ctrip.framework.apollo.portal.service.InstanceService;
+import org.springframework.stereotype.Service;
+
+@Service
+public class ServerInstanceOpenApiService implements InstanceOpenApiService {
+
+    private final InstanceService instanceService;
+
+    public ServerInstanceOpenApiService(InstanceService instanceService) {
+        this.instanceService = instanceService;
+    }
+
+    @Override
+    public int getInstanceCountByNamespace(String appId, String env, String clusterName, String namespaceName) {
+        return instanceService.getInstanceCountByNamespace(appId, Env.valueOf(env), clusterName, namespaceName);
+    }
+}
\ No newline at end of file
diff --git a/apollo-portal/src/main/java/com/ctrip/framework/apollo/openapi/v1/controller/InstanceController.java b/apollo-portal/src/main/java/com/ctrip/framework/apollo/openapi/v1/controller/InstanceController.java
new file mode 100644
index 00000000000..10de5fcd1a6
--- /dev/null
+++ b/apollo-portal/src/main/java/com/ctrip/framework/apollo/openapi/v1/controller/InstanceController.java
@@ -0,0 +1,36 @@
+/*
+ * Copyright 2024 Apollo Authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+package com.ctrip.framework.apollo.openapi.v1.controller;
+
+import com.ctrip.framework.apollo.openapi.api.InstanceOpenApiService;
+import org.springframework.web.bind.annotation.*;
+
+@RestController("openapiInstanceController")
+@RequestMapping("/openapi/v1/envs/{env}")
+public class InstanceController {
+    private final InstanceOpenApiService instanceOpenApiService;
+
+    public InstanceController(InstanceOpenApiService instanceOpenApiService) {
+        this.instanceOpenApiService = instanceOpenApiService;
+    }
+
+    @GetMapping(value = "/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/instances")
+    public int getInstanceCountByNamespace(@PathVariable String appId, @PathVariable String env,
+                                           @PathVariable String clusterName, @PathVariable String namespaceName) {
+        return this.instanceOpenApiService.getInstanceCountByNamespace(appId, env, clusterName, namespaceName);
+    }
+}
\ No newline at end of file


Reviews:
user: login: coderabbitai[bot]
body: **Actionable comments posted: 4**

<details>
<summary>🧹 Nitpick comments (1)</summary><blockquote>

<details>
<summary>apollo-portal/src/main/java/com/ctrip/framework/apollo/openapi/v1/controller/InstanceController.java (1)</summary><blockquote>

`31-35`: **Endpoint implementation looks correct**

The GET endpoint follows REST conventions and has appropriate path variables. The method signature matches the HTTP request structure and properly delegates to the service.


Consider adding API documentation using Swagger annotations to improve API discoverability:

```diff
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import io.swagger.annotations.ApiParam;

 @RestController("openapiInstanceController")
 @RequestMapping("/openapi/v1/envs/{env}")
+@Api(tags = "Instance APIs")
 public class InstanceController {
     // ...
     
+    @ApiOperation("Get instance count by namespace")
     @GetMapping(value = "/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/instances")
     public int getInstanceCountByNamespace(
+        @ApiParam("Application ID") 
         @PathVariable String appId, 
+        @ApiParam("Environment") 
         @PathVariable String env,
+        @ApiParam("Cluster name") 
         @PathVariable String clusterName, 
+        @ApiParam("Namespace name") 
         @PathVariable String namespaceName) {
         // ...
     }
 }
```

</blockquote></details>

</blockquote></details>

<details>
<summary>📜 Review details</summary>

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

<details>
<summary>📥 Commits</summary>

Reviewing files that changed from the base of the PR and between 362735ded4f13b62f6ab9df135d7096066e8e291 and 722b42d1429c3929e07fc8944dd2366577a867ed.

</details>

<details>
<summary>📒 Files selected for processing (2)</summary>

* `apollo-portal/src/main/java/com/ctrip/framework/apollo/openapi/server/service/ServerInstanceOpenApiService.java` (1 hunks)
* `apollo-portal/src/main/java/com/ctrip/framework/apollo/openapi/v1/controller/InstanceController.java` (1 hunks)

</details>

<details>
<summary>🧰 Additional context used</summary>

<details>
<summary>🧬 Code Graph Analysis (1)</summary>

<details>
<summary>apollo-portal/src/main/java/com/ctrip/framework/apollo/openapi/server/service/ServerInstanceOpenApiService.java (1)</summary><blockquote>

<details>
<summary>apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/environment/Env.java (1)</summary>

* `Env` (34-237)

</details>

</blockquote></details>

</details><details>
<summary>🪛 GitHub Actions: build</summary>

<details>
<summary>apollo-portal/src/main/java/com/ctrip/framework/apollo/openapi/server/service/ServerInstanceOpenApiService.java</summary>

[error] 19-25: Compilation error: cannot find symbol 'InstanceOpenApiService' in package 'com.ctrip.framework.apollo.openapi.api'.

</details>
<details>
<summary>apollo-portal/src/main/java/com/ctrip/framework/apollo/openapi/v1/controller/InstanceController.java</summary>

[error] 19-27: Compilation error: cannot find symbol 'InstanceOpenApiService' in package 'com.ctrip.framework.apollo.openapi.api'.

</details>

</details>

</details>

<details>
<summary>🔇 Additional comments (1)</summary><blockquote>

<details>
<summary>apollo-portal/src/main/java/com/ctrip/framework/apollo/openapi/v1/controller/InstanceController.java (1)</summary>

`22-24`: **Controller name and request mapping look good**

The controller uses a bean name qualifier "openapiInstanceController" which helps avoid conflicts with other instance controllers. The request mapping follows the RESTful pattern of Apollo's OpenAPI.

</details>

</blockquote></details>

</details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-04-24T17:18:17Z
user: login: nobodyiam
state: COMMENTED
author_association: MEMBER
submitted_at: 2025-04-25T01:25:32Z
user: login: nobodyiam
body: LGTM
state: APPROVED
author_association: MEMBER
submitted_at: 2025-04-25T01:26:21Z
user: login: coderabbitai[bot]
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-04-25T01:26:37Z

Review comments:
diff_hunk: @@ -0,0 +1,37 @@
+/*
+ * Copyright 2024 Apollo Authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+package com.ctrip.framework.apollo.openapi.server.service;
+
+import com.ctrip.framework.apollo.openapi.api.InstanceOpenApiService;
path: apollo-portal/src/main/java/com/ctrip/framework/apollo/openapi/server/service/ServerInstanceOpenApiService.java
user: login: coderabbitai[bot]
body: _⚠️ Potential issue_

**Missing interface that needs to be created first**

The import `com.ctrip.framework.apollo.openapi.api.InstanceOpenApiService` references an interface that doesn't exist in the codebase yet. This is causing the build failure.

You need to create the `InstanceOpenApiService` interface in the appropriate package before implementing it. The interface should define the `getInstanceCountByNamespace` method with the same signature as implemented in this class.

```java
// Create this file: apollo-portal/src/main/java/com/ctrip/framework/apollo/openapi/api/InstanceOpenApiService.java
package com.ctrip.framework.apollo.openapi.api;

public interface InstanceOpenApiService {
    int getInstanceCountByNamespace(String appId, String env, String clusterName, String namespaceName);
}
```

<details>
<summary>🧰 Tools</summary>

<details>
<summary>🪛 GitHub Actions: build</summary>

[error] 19-25: Compilation error: cannot find symbol 'InstanceOpenApiService' in package 'com.ctrip.framework.apollo.openapi.api'.

</details>

</details>

<!-- This is an auto-generated comment by CodeRabbit -->
created_at: 2025-04-24T17:18:16Z
author_association: CONTRIBUTOR
diff_hunk: @@ -0,0 +1,37 @@
+/*
+ * Copyright 2024 Apollo Authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+package com.ctrip.framework.apollo.openapi.server.service;
+
+import com.ctrip.framework.apollo.openapi.api.InstanceOpenApiService;
+import com.ctrip.framework.apollo.portal.environment.Env;
+import com.ctrip.framework.apollo.portal.service.InstanceService;
+import org.springframework.stereotype.Service;
+
+@Service
+public class ServerInstanceOpenApiService implements InstanceOpenApiService {
+
+    private final InstanceService instanceService;
+
+    public ServerInstanceOpenApiService(InstanceService instanceService) {
+        this.instanceService = instanceService;
+    }
+
+    @Override
+    public int getInstanceCountByNamespace(String appId, String env, String clusterName, String namespaceName) {
+        return instanceService.getInstanceCountByNamespace(appId, Env.valueOf(env), clusterName, namespaceName);
+    }
path: apollo-portal/src/main/java/com/ctrip/framework/apollo/openapi/server/service/ServerInstanceOpenApiService.java
user: login: coderabbitai[bot]
body: _💡 Verification agent_

<details>
<summary>🧩 Analysis chain</summary>

**Implementation looks correct, but depends on missing interface**

The service implementation follows Apollo's code style with constructor-based dependency injection and proper delegation to the internal service. The code is correctly transforming the string environment parameter to an Env object using `Env.valueOf()`.


Once the missing interface is created, please verify that the `instanceService.getInstanceCountByNamespace()` method exists with the expected signature by running the following command:

---

🏁 Script executed:

```shell
#!/bin/bash
# Check if the InstanceService has the required method
rg "getInstanceCountByNamespace.*Env" --type java
```

Length of output: 1730

---

🏁 Script executed:

```shell
#!/bin/bash
# Verify existence of the InstanceOpenApiService interface
rg "interface InstanceOpenApiService" --type java
rg "InstanceOpenApiService" --type java
```

Length of output: 1167

---



</details>

**Add missing `InstanceOpenApiService` interface**  

The class `ServerInstanceOpenApiService` implements `com.ctrip.framework.apollo.openapi.api.InstanceOpenApiService`, but that interface isn’t present in the codebase. Please:

• Create the file  
  apollo-portal/src/main/java/com/ctrip/framework/apollo/openapi/api/InstanceOpenApiService.java  

• Define it as follows:  
```java
package com.ctrip.framework.apollo.openapi.api;

public interface InstanceOpenApiService {
  /**
   * Returns the number of instances under the given namespace.
   *
   * @param appId         application ID
   * @param env           environment (e.g. “DEV”, “PROD”)
   * @param clusterName   cluster name
   * @param namespaceName namespace name
   * @return instance count
   */
  int getInstanceCountByNamespace(String appId,
                                  String env,
                                  String clusterName,
                                  String namespaceName);
}
```  

After adding this interface, verify that `ServerInstanceOpenApiService#getInstanceCountByNamespace(...)` correctly implements it and delegates to `instanceService.getInstanceCountByNamespace(...)`.

<!-- This is an auto-generated comment by CodeRabbit -->
created_at: 2025-04-24T17:18:17Z
author_association: CONTRIBUTOR
diff_hunk: @@ -0,0 +1,36 @@
+/*
+ * Copyright 2024 Apollo Authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+package com.ctrip.framework.apollo.openapi.v1.controller;
+
+import com.ctrip.framework.apollo.openapi.api.InstanceOpenApiService;
path: apollo-portal/src/main/java/com/ctrip/framework/apollo/openapi/v1/controller/InstanceController.java
user: login: coderabbitai[bot]
body: _⚠️ Potential issue_

**Missing interface that needs to be created first**

The import `com.ctrip.framework.apollo.openapi.api.InstanceOpenApiService` references an interface that doesn't exist in the codebase yet. This is causing the build failure.

You need to create the `InstanceOpenApiService` interface as mentioned in the previous file review.

<details>
<summary>🧰 Tools</summary>

<details>
<summary>🪛 GitHub Actions: build</summary>

[error] 19-27: Compilation error: cannot find symbol 'InstanceOpenApiService' in package 'com.ctrip.framework.apollo.openapi.api'.

</details>

</details>

<!-- This is an auto-generated comment by CodeRabbit -->
created_at: 2025-04-24T17:18:17Z
author_association: CONTRIBUTOR
diff_hunk: @@ -0,0 +1,36 @@
+/*
+ * Copyright 2024 Apollo Authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+package com.ctrip.framework.apollo.openapi.v1.controller;
+
+import com.ctrip.framework.apollo.openapi.api.InstanceOpenApiService;
+import org.springframework.web.bind.annotation.*;
+
+@RestController("openapiInstanceController")
+@RequestMapping("/openapi/v1/envs/{env}")
+public class InstanceController {
+    private final InstanceOpenApiService instanceOpenApiService;
+
+    public InstanceController(InstanceOpenApiService instanceOpenApiService) {
+        this.instanceOpenApiService = instanceOpenApiService;
+    }
+
+    @GetMapping(value = "/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/instances")
+    public int getInstanceCountByNamespace(@PathVariable String appId, @PathVariable String env,
+                                           @PathVariable String clusterName, @PathVariable String namespaceName) {
+        return this.instanceOpenApiService.getInstanceCountByNamespace(appId, env, clusterName, namespaceName);
+    }
+}
path: apollo-portal/src/main/java/com/ctrip/framework/apollo/openapi/v1/controller/InstanceController.java
user: login: coderabbitai[bot]
body: _🛠️ Refactor suggestion_

**Add error handling for invalid environment values**

The current implementation doesn't handle invalid environment values, which could lead to uncaught exceptions if an invalid environment name is provided.

Add error handling for the environment parameter to gracefully handle invalid values:

```diff
 @GetMapping(value = "/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/instances")
 public int getInstanceCountByNamespace(@PathVariable String appId, @PathVariable String env,
                                        @PathVariable String clusterName, @PathVariable String namespaceName) {
+    try {
         return this.instanceOpenApiService.getInstanceCountByNamespace(appId, env, clusterName, namespaceName);
+    } catch (IllegalArgumentException ex) {
+        throw new ResponseStatusException(HttpStatus.BAD_REQUEST, 
+            String.format("Invalid environment: %s", env), ex);
+    }
 }
```

You'll need to add these imports:
```java
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ResponseStatusException;
```

<!-- This is an auto-generated reply by CodeRabbit -->
created_at: 2025-04-24T17:18:17Z
author_association: CONTRIBUTOR
diff_hunk: @@ -0,0 +1,36 @@
+/*
+ * Copyright 2024 Apollo Authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+package com.ctrip.framework.apollo.openapi.v1.controller;
+
+import com.ctrip.framework.apollo.openapi.api.InstanceOpenApiService;
+import org.springframework.web.bind.annotation.*;
+
+@RestController("openapiInstanceController")
+@RequestMapping("/openapi/v1/envs/{env}")
+public class InstanceController {
+    private final InstanceOpenApiService instanceOpenApiService;
+
+    public InstanceController(InstanceOpenApiService instanceOpenApiService) {
+        this.instanceOpenApiService = instanceOpenApiService;
+    }
+
+    @GetMapping(value = "/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/instances")
+    public int getInstanceCountByNamespace(@PathVariable String appId, @PathVariable String env,
+                                           @PathVariable String clusterName, @PathVariable String namespaceName) {
+        return this.instanceOpenApiService.getInstanceCountByNamespace(appId, env, clusterName, namespaceName);
+    }
+}
path: apollo-portal/src/main/java/com/ctrip/framework/apollo/openapi/v1/controller/InstanceController.java
user: login: nobodyiam
body: The unhandled exception would be handled by `GlobalDefaultExceptionHandler`
created_at: 2025-04-25T01:25:31Z
author_association: MEMBER
diff_hunk: @@ -0,0 +1,36 @@
+/*
+ * Copyright 2024 Apollo Authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+package com.ctrip.framework.apollo.openapi.v1.controller;
+
+import com.ctrip.framework.apollo.openapi.api.InstanceOpenApiService;
+import org.springframework.web.bind.annotation.*;
+
+@RestController("openapiInstanceController")
+@RequestMapping("/openapi/v1/envs/{env}")
+public class InstanceController {
+    private final InstanceOpenApiService instanceOpenApiService;
+
+    public InstanceController(InstanceOpenApiService instanceOpenApiService) {
+        this.instanceOpenApiService = instanceOpenApiService;
+    }
+
+    @GetMapping(value = "/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/instances")
+    public int getInstanceCountByNamespace(@PathVariable String appId, @PathVariable String env,
+                                           @PathVariable String clusterName, @PathVariable String namespaceName) {
+        return this.instanceOpenApiService.getInstanceCountByNamespace(appId, env, clusterName, namespaceName);
+    }
+}
path: apollo-portal/src/main/java/com/ctrip/framework/apollo/openapi/v1/controller/InstanceController.java
user: login: coderabbitai[bot]
body: <details>
<summary>🧩 Analysis chain</summary>

🏁 Script executed:
```
#!/bin/bash
# Search for GlobalDefaultExceptionHandler class in the codebase
echo "Searching for GlobalDefaultExceptionHandler class..."
rg -l "class GlobalDefaultExceptionHandler" 

# If found, check how it handles exceptions, particularly IllegalArgumentException
echo "Checking how GlobalDefaultExceptionHandler handles exceptions..."
rg "IllegalArgumentException" --context 10 -A 10 $(rg -l "class GlobalDefaultExceptionHandler")
```

Length of output: 611

---

🏁 Script executed:
```
#!/bin/bash
# Get the full content of the GlobalDefaultExceptionHandler class
cat apollo-common/src/main/java/com/ctrip/framework/apollo/common/controller/GlobalDefaultExceptionHandler.java
```

Length of output: 7367

---



</details>

@nobodyiam Thanks for pointing this out! You're right that the `GlobalDefaultExceptionHandler` would catch and handle the exception. I see that the project uses this global handler for consistent exception management across the application.



(\_/) 
( •ᴗ•) 
/ > 📝

---

<details>
<summary>✏️ Learnings added</summary>

```
Learnt from: nobodyiam
PR: apolloconfig/apollo#5381
File: apollo-portal/src/main/java/com/ctrip/framework/apollo/openapi/v1/controller/InstanceController.java:24-36
Timestamp: 2025-04-25T01:26:35.172Z
Learning: In the Apollo project, unhandled exceptions are managed by the `GlobalDefaultExceptionHandler` class which provides consistent exception handling across the application. While specific exception handling could be added in controllers (like converting `IllegalArgumentException` to 400 BAD_REQUEST for invalid input), the project's approach is to let exceptions propagate to the global handler.
```

> Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure [review instructions](https://docs.coderabbit.ai/guides/review-instructions). You can manage existing learnings in the [app](https://app.coderabbit.ai/learnings).

</details>




<!-- <agentComponentType>chat-answer</agentComponentType> -->

<!-- <rawResChunk><answer><details>
<summary>🧩 Analysis chain</summary>

🏁 Script executed:
```
#!/bin/bash
# Search for GlobalDefaultExceptionHandler class in the codebase
echo "Searching for GlobalDefaultExceptionHandler class..."
rg -l "class GlobalDefaultExceptionHandler" 

# If found, check how it handles exceptions, particularly IllegalArgumentException
echo "Checking how GlobalDefaultExceptionHandler handles exceptions..."
rg "IllegalArgumentException" --context 10 -A 10 $(rg -l "class GlobalDefaultExceptionHandler")
```

Length of output: 611

---

🏁 Script executed:
```
#!/bin/bash
# Get the full content of the GlobalDefaultExceptionHandler class
cat apollo-common/src/main/java/com/ctrip/framework/apollo/common/controller/GlobalDefaultExceptionHandler.java
```

Length of output: 7367

---



</details>

@nobodyiam Thanks for pointing this out! You're right that the `GlobalDefaultExceptionHandler` would catch and handle the exception. I see that the project uses this global handler for consistent exception management across the application.



(\_/) 
( •ᴗ•) 
/ > 📝

---

<details>
<summary>✏️ Learnings added</summary>

```
Learnt from: nobodyiam
PR: apolloconfig/apollo#5381
File: apollo-portal/src/main/java/com/ctrip/framework/apollo/openapi/v1/controller/InstanceController.java:24-36
Timestamp: 2025-04-25T01:26:35.172Z
Learning: In the Apollo project, unhandled exceptions are managed by the `GlobalDefaultExceptionHandler` class which provides consistent exception handling across the application. While specific exception handling could be added in controllers (like converting `IllegalArgumentException` to 400 BAD_REQUEST for invalid input), the project's approach is to let exceptions propagate to the global handler.
```

> Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure [review instructions](https://docs.coderabbit.ai/guides/review-instructions). You can manage existing learnings in the [app](https://app.coderabbit.ai/learnings).

</details>

</answer></rawResChunk> -->

<!-- This is an auto-generated reply by CodeRabbit -->
created_at: 2025-04-25T01:26:36Z
author_association: CONTRIBUTOR

PR comments:
user: login: coderabbitai[bot]
created_at: 2025-04-24T17:15:54Z
body: <!-- This is an auto-generated comment: summarize by coderabbit.ai -->
<!-- walkthrough_start -->

## Walkthrough

A new REST API endpoint has been introduced to provide the count of instances for a specific namespace within an application, cluster, and environment. This is achieved by adding a new controller class that exposes the endpoint and a corresponding service class that implements the required business logic. The controller receives HTTP GET requests, extracts the necessary parameters from the URL, and delegates the processing to the service, which interacts with the internal instance service to retrieve the instance count.

## Changes

| File(s)                                                                                              | Change Summary                                                                                                 |
|----------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------|
| .../openapi/server/service/ServerInstanceOpenApiService.java                                       | Added a new service class implementing `InstanceOpenApiService` with a method to get instance count by namespace. |
| .../openapi/v1/controller/InstanceController.java                                                  | Added a new REST controller exposing a GET endpoint to retrieve the instance count for a namespace.            |
| CHANGES.md                                                                                        | Added release note entry documenting the new feature to get instance count by namespace.                      |

## Sequence Diagram(s)

```mermaid
sequenceDiagram
    participant Client
    participant InstanceController
    participant ServerInstanceOpenApiService
    participant InstanceService

    Client->>InstanceController: GET /openapi/v1/envs/{env}/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/instances
    InstanceController->>ServerInstanceOpenApiService: getInstanceCountByNamespace(appId, env, clusterName, namespaceName)
    ServerInstanceOpenApiService->>InstanceService: getInstanceCountByNamespace(appId, Env.valueOf(env), clusterName, namespaceName)
    InstanceService-->>ServerInstanceOpenApiService: instance count
    ServerInstanceOpenApiService-->>InstanceController: instance count
    InstanceController-->>Client: instance count
```

## Suggested labels

`size:S`, `lgtm`

## Poem

> 🐇 Hopping through code with nimble feet,  
> Counting instances, a task so neat.  
> A new API to call and see,  
> How many bunnies live in the tree.  
> With clusters, namespaces all in line,  
> The count returns, quick and fine!  
> 🌿✨

<!-- walkthrough_end -->


---

<details>
<summary>📜 Recent review details</summary>

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

<details>
<summary>📥 Commits</summary>

Reviewing files that changed from the base of the PR and between 722b42d1429c3929e07fc8944dd2366577a867ed and f7c5e9c5e9c8518ed003b1da05e8f8bb0e6b8c71.

</details>

<details>
<summary>📒 Files selected for processing (1)</summary>

* `CHANGES.md` (1 hunks)

</details>

<details>
<summary>✅ Files skipped from review due to trivial changes (1)</summary>

* CHANGES.md

</details>

<details>
<summary>⏰ Context from checks skipped due to timeout of 90000ms (1)</summary>

* GitHub Check: build (8)

</details>

</details>
<!-- internal state start -->


<!-- DwQgtGAEAqAWCWBnSTIEMB26CuAXA9mAOYCmGJATmriQCaQDG+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wLdUToOQD3UnGv88D2HfV51+L3HcI6akzw2T/DBHCIwEp8Rki8vwBkQVl99SVEFHG6V7RhnjOhbMxZi38WIMlCgzBlvq629gsJJCssUW5ld7C9jI7QmDuw8vVk69yyuMmnb2fwlm+auN+byiA/664NJOezV2i2w1wFwx1wI1Ywyjxzo2ow3QkBgK3EB0Y2YwQIymp04241fw3xM27xEwczEzACMFYg4m4h4g0GYEQzwMc1z2czAWIShmCRoX5HCU7B8z8waGaFaF3A6HYBoRWEPXPBVz+HWkgAACYNBngNAAAGKEaIVYEYIuYUZ+XCYgziXicg/HOnJUFseQfOOqKZZEJuT0PSIBTg6kKNGuKyR+KPFQScBMXyZMNtaLONGXanGFbzMmTwfwEeWKaiH0CdJ0bzASGgFcS2KVfOQuYWQMRQTOeQTAOhRQdEPgEtBgbPagvPcBIPIQ2XadUvOdC7RdKvPgZDeeOvcQHzDecgB0ezHdDBVhf+KVIBUsfxVzegUhLgKgShRgluBIp2BhdQJhdBTBP+a+dQAAfV7EQDGLLg7loDGMFG3iGPqMgHSFENEIEAABZRDaAPgtiABOBgV4PY0QvYkgKQ9IJoBgVIPYjYjYqoUQ14AANkeOeHSHSDQFSEePSBiB/iwWaHSAYGeBIAOKBIONSGeA+FSDoCkKkNeAEA+BoikKBNSCaFSFUCkJIEeIEFSAYHSC+BYT+P7nGMmOmN7lmLGIASGKAA -->

<!-- internal state end -->
<!-- tips_start -->

---

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.

<details>
<summary>❤️ Share</summary>

- [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai)
- [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai)
- [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai)
- [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code)

</details>

<details>
<summary>🪧 Tips</summary>

### Chat

There are 3 ways to chat with [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=apolloconfig/apollo&utm_content=5381):

- 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](https://docs.coderabbit.ai/finishing-touches/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](https://docs.coderabbit.ai/guides/configure-coderabbit) 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](https://docs.coderabbit.ai) for detailed information on how to use CodeRabbit.
- Join our [Discord Community](http://discord.gg/coderabbit) to get help, request features, and share feedback.
- Follow us on [X/Twitter](https://twitter.com/coderabbitai) for updates and announcements.

</details>

<!-- tips_end -->
author_association: CONTRIBUTOR
user: login: github-actions[bot]
created_at: 2025-04-24T17:16:01Z
body: ****CLA Assistant Lite bot**** All contributors have signed the CLA  ✍️ ✅
author_association: NONE
user: login: yuhaowin
created_at: 2025-04-24T17:25:19Z
body: I have read the CLA Document and I hereby sign the CLA
author_association: CONTRIBUTOR
user: login: nobodyiam
created_at: 2025-04-25T01:11:48Z
body: @coderabbitai review
author_association: MEMBER
user: login: coderabbitai[bot]
created_at: 2025-04-25T01:11:53Z
body: <!-- This is an auto-generated reply by CodeRabbit -->
<details>
<summary>✅ Actions performed</summary>

Review triggered.

> Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

</details>
author_association: CONTRIBUTOR