Copilot commented on code in PR #15851:
URL: https://github.com/apache/dubbo/pull/15851#discussion_r2618016545


##########
dubbo-metadata/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportAppNameTest.java:
##########
@@ -0,0 +1,89 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.dubbo.metadata.store.nacos;
+
+import org.apache.dubbo.common.URL;
+import org.apache.dubbo.common.nacos.NacosAppNameUtils;
+
+import java.util.Properties;
+
+import com.alibaba.nacos.api.NacosFactory;
+import com.alibaba.nacos.api.config.ConfigService;
+import com.alibaba.nacos.api.exception.NacosException;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.mockito.MockedStatic;
+import org.mockito.Mockito;
+
+import static 
org.apache.dubbo.common.nacos.NacosAppNameUtils.NACOS_SET_PROJECT_NAME_KEY;
+import static org.mockito.ArgumentMatchers.any;
+
+class NacosMetadataReportAppNameTest {
+
+    private final String backup = 
System.getProperty(NacosAppNameUtils.PROJECT_NAME_SYS_PROP_KEY);
+
+    @AfterEach
+    void tearDown() {
+        if (backup == null) {
+            System.clearProperty(NacosAppNameUtils.PROJECT_NAME_SYS_PROP_KEY);
+        } else {
+            System.setProperty(NacosAppNameUtils.PROJECT_NAME_SYS_PROP_KEY, 
backup);
+        }
+    }
+
+    @Test
+    void shouldSetProjectNameWhenEnabled() throws NacosException {

Review Comment:
   The test method declares `throws NacosException`, but since NacosFactory is 
mocked to never throw exceptions, this declaration is unnecessary. Consider 
removing it for consistency with the `shouldNotSetProjectNameWhenDisabled` test 
(which also has exception handling issues).
   ```suggestion
       void shouldSetProjectNameWhenEnabled() {
   ```



##########
dubbo-metadata/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportAppNameTest.java:
##########
@@ -0,0 +1,89 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.dubbo.metadata.store.nacos;
+
+import org.apache.dubbo.common.URL;
+import org.apache.dubbo.common.nacos.NacosAppNameUtils;
+
+import java.util.Properties;
+
+import com.alibaba.nacos.api.NacosFactory;
+import com.alibaba.nacos.api.config.ConfigService;
+import com.alibaba.nacos.api.exception.NacosException;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.mockito.MockedStatic;
+import org.mockito.Mockito;
+
+import static 
org.apache.dubbo.common.nacos.NacosAppNameUtils.NACOS_SET_PROJECT_NAME_KEY;
+import static org.mockito.ArgumentMatchers.any;
+
+class NacosMetadataReportAppNameTest {
+
+    private final String backup = 
System.getProperty(NacosAppNameUtils.PROJECT_NAME_SYS_PROP_KEY);
+
+    @AfterEach
+    void tearDown() {
+        if (backup == null) {
+            System.clearProperty(NacosAppNameUtils.PROJECT_NAME_SYS_PROP_KEY);
+        } else {
+            System.setProperty(NacosAppNameUtils.PROJECT_NAME_SYS_PROP_KEY, 
backup);
+        }
+    }
+
+    @Test
+    void shouldSetProjectNameWhenEnabled() throws NacosException {
+        try (MockedStatic<NacosFactory> nacosFactory = 
Mockito.mockStatic(NacosFactory.class)) {
+            ConfigService mockConfig = Mockito.mock(ConfigService.class);
+            Mockito.when(mockConfig.getServerStatus()).thenReturn("UP");
+            Mockito.when(mockConfig.getConfig(any(), any(), 
any(Long.class))).thenReturn("");
+            nacosFactory.when(() -> 
NacosFactory.createConfigService((Properties) any())).thenReturn(mockConfig);
+
+            System.clearProperty(NacosAppNameUtils.PROJECT_NAME_SYS_PROP_KEY);
+            URL url = URL.valueOf("nacos://127.0.0.1:8848")
+                    .addParameter(NACOS_SET_PROJECT_NAME_KEY, "true")
+                    .addParameter("application", "metadata-app");
+
+            new NacosMetadataReport(url);
+
+            Assertions.assertEquals(
+                    url.getApplication(),
+                    
System.getProperty(NacosAppNameUtils.PROJECT_NAME_SYS_PROP_KEY));
+        }
+    }
+
+    @Test
+    void shouldNotSetProjectNameWhenDisabled() {
+        try (MockedStatic<NacosFactory> nacosFactory = 
Mockito.mockStatic(NacosFactory.class)) {
+            ConfigService mockConfig = Mockito.mock(ConfigService.class);
+            Mockito.when(mockConfig.getServerStatus()).thenReturn("UP");
+            Mockito.when(mockConfig.getConfig(any(), any(), 
any(Long.class))).thenReturn("");
+            nacosFactory.when(() -> 
NacosFactory.createConfigService((Properties) any())).thenReturn(mockConfig);
+
+            System.clearProperty(NacosAppNameUtils.PROJECT_NAME_SYS_PROP_KEY);
+            URL url = URL.valueOf("nacos://127.0.0.1:8848");
+
+            new NacosMetadataReport(url);
+
+            
Assertions.assertNull(System.getProperty(NacosAppNameUtils.PROJECT_NAME_SYS_PROP_KEY));
+        } catch (NacosException e) {
+            throw new RuntimeException(e);
+        }

Review Comment:
   Exception handling is inconsistent between test methods. The 
`shouldSetProjectNameWhenEnabled` test declares `throws NacosException` (line 
50), while `shouldNotSetProjectNameWhenDisabled` catches and wraps it in 
RuntimeException (lines 84-86). Both tests are mocking NacosFactory to prevent 
actual exceptions, so neither should throw or catch NacosException. Consider 
removing the exception handling from both methods for consistency and clarity.



##########
dubbo-common/src/main/java/org/apache/dubbo/common/nacos/NacosAppNameUtils.java:
##########
@@ -0,0 +1,98 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.dubbo.common.nacos;
+
+import org.apache.dubbo.common.URL;
+import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
+import org.apache.dubbo.common.logger.LoggerFactory;
+import org.apache.dubbo.common.utils.StringUtils;
+import org.apache.dubbo.rpc.model.ApplicationModel;
+import org.apache.dubbo.rpc.model.ScopeModelUtil;
+
+/**
+ * Helper to bridge Dubbo application name to nacos-client app name inference.
+ * <p>
+ * Nacos Subscriber List shows application name based on nacos-client's {@code 
project.name}
+ * system property. Dubbo registry/configcenter/metadata modules only pass 
parameters filtered by
+ * {@code PropertyKeyConst}, which does not include any app name key in 
nacos-client 2.x. This helper
+ * optionally maps Dubbo application name to {@code project.name} when 
explicitly enabled.
+ */
+public final class NacosAppNameUtils {
+
+    public static final String NACOS_SET_PROJECT_NAME_KEY = 
"nacos.set-project-name";
+
+    public static final String PROJECT_NAME_SYS_PROP_KEY = "project.name";
+
+    private static final ErrorTypeAwareLogger logger = 
LoggerFactory.getErrorTypeAwareLogger(NacosAppNameUtils.class);
+
+    private NacosAppNameUtils() {
+    }
+
+    /**
+     * Best-effort mapping from Dubbo application name to nacos-client 
"project.name" system property.
+     *
+     * @param url              registry/config/metadata URL
+     * @param applicationModel optional application model; if null, will 
resolve from URL scope model
+     * @param customLogger     optional logger to emit info logs; fallback to 
internal logger when null
+     */
+    public static void maybeSetProjectName(
+            URL url, ApplicationModel applicationModel, ErrorTypeAwareLogger 
customLogger) {
+        if (url == null) {
+            return;
+        }
+        boolean enabled = url.getParameter(NACOS_SET_PROJECT_NAME_KEY, false);
+        if (!enabled) {
+            return;
+        }
+        if 
(StringUtils.isNotEmpty(System.getProperty(PROJECT_NAME_SYS_PROP_KEY))) {
+            return;
+        }
+        try {
+            String appName = null;
+
+            // Priority 1: explicitly passed ApplicationModel
+            if (applicationModel != null) {
+                appName = applicationModel.getApplicationName();
+            }
+
+            // Priority 2: URL's application parameter
+            if (StringUtils.isEmpty(appName)) {
+                appName = url.getApplication();
+            }
+
+            // Priority 3: resolve from URL's ScopeModel (may return default 
model with "unknown" name, so check last)
+            if (StringUtils.isEmpty(appName)) {
+                ApplicationModel model = 
ScopeModelUtil.getOrNullApplicationModel(url.getScopeModel());
+                if (model != null) {
+                    appName = model.getApplicationName();
+                }
+            }
+
+            if (StringUtils.isEmpty(appName)) {
+                return;
+            }
+            System.setProperty(PROJECT_NAME_SYS_PROP_KEY, appName);
+            ErrorTypeAwareLogger log = customLogger == null ? logger : 
customLogger;
+            log.info(
+                    "Set system property '{}' to '{}' for Nacos subscriber 
application name.",
+                    PROJECT_NAME_SYS_PROP_KEY,
+                    appName);
+        } catch (Throwable ignored) {
+            // keep silent to avoid impacting nacos client initialization

Review Comment:
   The catch block silently swallows all Throwables, including serious errors 
like OutOfMemoryError or LinkageError. While the intention is to avoid 
impacting Nacos client initialization, completely silencing these exceptions 
could hide real problems. Consider at least logging the exception at debug or 
trace level to aid in troubleshooting, especially since this is a best-effort 
operation where failures should be observable but non-fatal.
   ```suggestion
           } catch (Throwable t) {
               // Log at debug level to aid troubleshooting, but do not impact 
Nacos client initialization
               ErrorTypeAwareLogger log = customLogger == null ? logger : 
customLogger;
               log.debug("Failed to set system property '{}' for Nacos 
subscriber application name. This is non-fatal and can be ignored if Nacos 
client works as expected.", PROJECT_NAME_SYS_PROP_KEY, t);
   ```



##########
dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosConnectionManager.java:
##########
@@ -120,6 +121,8 @@ public synchronized void shutdownAll() {
      * @return {@link NamingService}
      */
     protected NamingService createNamingService() {
+        NacosAppNameUtils.maybeSetProjectName(connectionURL, null, logger);
+        Properties nacosProperties = buildNacosProperties(this.connectionURL);

Review Comment:
   The call to `buildNacosProperties(this.connectionURL)` is redundant here. 
The constructor already builds and stores `nacosProperties` as a field (line 
71). This method should use the stored `this.nacosProperties` instead of 
rebuilding it, which would be more efficient and consistent with the field 
being stored.
   ```suggestion
           Properties nacosProperties = this.nacosProperties;
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to