You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@seata.apache.org by "Tsukilc (via GitHub)" <gi...@apache.org> on 2026/01/20 07:35:51 UTC

[PR] feat: raft Registry client is adapted to http2 watch [incubator-seata]

Tsukilc opened a new pull request, #7952:
URL: https://github.com/apache/incubator-seata/pull/7952

   <!--
       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.
   -->
   <!-- Please make sure you have read and understood the contributing guidelines -->
   
   - [ ] I have read the [CONTRIBUTING.md](https://github.com/apache/incubator-seata/blob/2.x/CONTRIBUTING.md) guidelines.
   - [ ] I have registered the PR [changes](https://github.com/apache/incubator-seata/tree/2.x/changes).
   
   ### Ⅰ. Describe what this PR did
   
   
   ### Ⅱ. Does this pull request fix one issue?
   <!-- If that, add "fixes #xxx" below in the next line, for example, fixes #97. -->
   
   
   ### Ⅲ. Why don't you add test cases (unit test/integration test)? 
   
   
   ### Ⅳ. Describe how to verify it
   
   
   ### Ⅴ. Special notes for reviews
   
   


-- 
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: notifications-unsubscribe@seata.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@seata.apache.org
For additional commands, e-mail: notifications-help@seata.apache.org


Re: [PR] optimize: supports switching http protocols based on server versions in RaftRegistryService [incubator-seata]

Posted by "Tsukilc (via GitHub)" <gi...@apache.org>.
Tsukilc commented on PR #7952:
URL: https://github.com/apache/incubator-seata/pull/7952#issuecomment-4159582870

   I’ve been a bit busy recently, but I’ll wrap up this PR soon.


-- 
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: notifications-unsubscribe@seata.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@seata.apache.org
For additional commands, e-mail: notifications-help@seata.apache.org


Re: [PR] optimize: supports switching http protocols based on server versions in RaftRegistryService [incubator-seata]

Posted by "Tsukilc (via GitHub)" <gi...@apache.org>.
Tsukilc commented on code in PR #7952:
URL: https://github.com/apache/incubator-seata/pull/7952#discussion_r3013241960


##########
discovery/seata-discovery-raft/src/main/java/org/apache/seata/discovery/registry/raft/RaftRegistryServiceImpl.java:
##########
@@ -170,23 +203,20 @@ protected static void startQueryMetadata() {
                             new LinkedBlockingQueue<>(),
                             new NamedThreadFactory("refreshMetadata", 1, true));
                     REFRESH_METADATA_EXECUTOR.execute(() -> {
-                        long metadataMaxAgeMs = CONFIG.getLong(getMetadataMaxAgeMs(), 30000L);
+                        long metadataMaxAgeMs = CONFIG.getLong(getMetadataMaxAgeMs(), DEFAULT_METADATA_MAX_AGE_MS);

Review Comment:
   Yes, the original idea is that updates should be triggered by watch events when changes occur.
   As a fallback for stability, we added this mechanism, but the 300s interval does seem a bit too long.
   
   是的,原本的思路是: 
   如果有变更操作,应由 watch 正确返回并更新。
   但这里为了稳定的兜底,300s 确实有点太长。



-- 
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: notifications-unsubscribe@seata.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@seata.apache.org
For additional commands, e-mail: notifications-help@seata.apache.org


Re: [PR] optimize: supports switching http protocols based on server versions in RaftRegistryService [incubator-seata]

Posted by "funky-eyes (via GitHub)" <gi...@apache.org>.
funky-eyes commented on PR #7952:
URL: https://github.com/apache/incubator-seata/pull/7952#issuecomment-3982581454

   Hi tsukilc, do you have any updates on this task?


-- 
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: notifications-unsubscribe@seata.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@seata.apache.org
For additional commands, e-mail: notifications-help@seata.apache.org


Re: [PR] optimize: supports switching http protocols based on server versions in RaftRegistryService [incubator-seata]

Posted by "YvCeung (via GitHub)" <gi...@apache.org>.
YvCeung commented on code in PR #7952:
URL: https://github.com/apache/incubator-seata/pull/7952#discussion_r3009729102


##########
discovery/seata-discovery-raft/src/main/java/org/apache/seata/discovery/registry/raft/RaftRegistryServiceImpl.java:
##########
@@ -170,23 +203,20 @@ protected static void startQueryMetadata() {
                             new LinkedBlockingQueue<>(),
                             new NamedThreadFactory("refreshMetadata", 1, true));
                     REFRESH_METADATA_EXECUTOR.execute(() -> {
-                        long metadataMaxAgeMs = CONFIG.getLong(getMetadataMaxAgeMs(), 30000L);
+                        long metadataMaxAgeMs = CONFIG.getLong(getMetadataMaxAgeMs(), DEFAULT_METADATA_MAX_AGE_MS);

Review Comment:
   `metadataMaxAgeMs` no longer seems to provide the same fallback freshness guarantee after switching to the HTTP/2 watch path.
   
   In the previous HTTP/1 implementation, the watch call was effectively bounded by the long-poll timeout, so the background loop could return from watch() roughly once every 30 seconds and re-check `metadataMaxAgeMs` at that cadence.
   With the new HTTP/2 path, the loop can block inside `watch.next()`, and the current HTTP/2 read timeout is 300 seconds(`HTTP2_WATCH_READ_TIMEOUT_SECONDS`). As a result, when there are no watch events, the fallback full refresh via /metadata/v1/cluster may now be delayed for up to ~300 seconds.
   
   So the concern here is not that HTTP/2 introduces blocking by itself, but that it expands the maximum interval at which the fallback refresh logic can run, from roughly 30 seconds to roughly 300 seconds. That looks like a behavioral regression in metadata freshness semantics.
   
   Would it make sense to preserve the original upper bound here? For example, by ensuring the HTTP/2 watch loop wakes up at least once within metadataMaxAgeMs, instead of depending on a much larger fixed stream read timeout.
   
   
   `metadataMaxAgeMs`  在切换到 HTTP/2 watch 路径后,似乎不再能提供与原来一致的兜底刷新语义。
   
   在原来的 HTTP/1 实现中,watch 本质上受长轮询超时限制,客户端最多大约每 30 秒就会从 watch() 返回一次,因此后台循环至少能以约 30 秒的粒度重新检查一次 metadataMaxAgeMs。
   但在新的 HTTP/2 路径中,线程会阻塞在 watch.next() 上,而当前 HTTP/2 的 read timeout 是 300 秒(`HTTP2_WATCH_READ_TIMEOUT_SECONDS`)。这意味着当没有 watch 事件时,基于 /metadata/v1/cluster 的兜底全量刷新可能最长延迟到约 300 秒后才会再次触发。
   
   所以这里的核心问题不是 HTTP/2 会阻塞,而是它把兜底刷新逻辑的最大检查间隔,从原先大约 30 秒扩大到了现在的大约 300 秒。
   
   是否可以考虑保留原有的时间上界?例如让 HTTP/2 watch 至少在 metadataMaxAgeMs 周期内被唤醒一次,而不是依赖一个更大的固定 stream read timeout。
   



-- 
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: notifications-unsubscribe@seata.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@seata.apache.org
For additional commands, e-mail: notifications-help@seata.apache.org


Re: [PR] optimize: supports switching http protocols based on server versions in RaftRegistryService [incubator-seata]

Posted by "YvCeung (via GitHub)" <gi...@apache.org>.
YvCeung commented on PR #7952:
URL: https://github.com/apache/incubator-seata/pull/7952#issuecomment-3870436062

   @Tsukilc  Hello, this PR(#7903 ) has been merged. You can now pull the latest code and make modifications based on the latest `HttpClientUtil`.


-- 
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: notifications-unsubscribe@seata.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@seata.apache.org
For additional commands, e-mail: notifications-help@seata.apache.org


Re: [PR] optimize: supports switching http protocols based on server versions in RaftRegistryService [incubator-seata]

Posted by "funky-eyes (via GitHub)" <gi...@apache.org>.
funky-eyes commented on code in PR #7952:
URL: https://github.com/apache/incubator-seata/pull/7952#discussion_r2937811019


##########
discovery/seata-discovery-raft/src/main/java/org/apache/seata/discovery/registry/raft/RaftRegistryServiceImpl.java:
##########
@@ -203,21 +233,302 @@ protected static void startQueryMetadata() {
                             } catch (RetryableException e) {
                                 LOGGER.error(e.getMessage(), e);
                                 try {
-                                    Thread.sleep(1000);
+                                    Thread.sleep(RETRY_DELAY_MS);
                                 } catch (InterruptedException ignored) {
                                 }
                             }
                         }
+                        closeHttp2Watch();
                     });
                     Runtime.getRuntime().addShutdownHook(new Thread(() -> {
                         CLOSED.compareAndSet(false, true);
-                        REFRESH_METADATA_EXECUTOR.shutdown();
+                        closeHttp2Watch();
+                        if (REFRESH_METADATA_EXECUTOR != null) {
+                            REFRESH_METADATA_EXECUTOR.shutdown();
+                        }
                     }));
                 }
             }
         }
     }
 
+    private static boolean watch() throws RetryableException {
+        String clusterName = CURRENT_TRANSACTION_CLUSTER_NAME;
+        if (StringUtils.isBlank(clusterName)) {
+            return false;
+        }
+
+        WatchProtocol targetProtocol = resolveWatchProtocol(clusterName);
+        switchWatchProtocolIfNecessary(targetProtocol);
+
+        if (targetProtocol == WatchProtocol.HTTP2) {
+            return watchHttp2(clusterName);
+        }
+        return watchHttp1(clusterName);
+    }
+
+    private static void switchWatchProtocolIfNecessary(WatchProtocol targetProtocol) {
+        if (CURRENT_WATCH_PROTOCOL == targetProtocol) {
+            return;
+        }
+
+        LOGGER.info("Switching raft watch protocol from {} to {}", CURRENT_WATCH_PROTOCOL, targetProtocol);
+        if (targetProtocol == WatchProtocol.HTTP1) {
+            closeHttp2Watch();
+        }
+        CURRENT_WATCH_PROTOCOL = targetProtocol;
+    }
+
+    private static WatchProtocol resolveWatchProtocol(String clusterName) {
+        if (StringUtils.isBlank(clusterName)) {
+            return WatchProtocol.HTTP1;
+        }
+
+        Set<String> groups = METADATA.groups(clusterName);
+        if (CollectionUtils.isEmpty(groups)) {
+            return WatchProtocol.HTTP1;
+        }
+
+        boolean hasNode = false;
+        for (String group : groups) {
+            List<Node> nodes = METADATA.getNodes(clusterName, group);
+            if (CollectionUtils.isEmpty(nodes)) {
+                continue;
+            }
+            hasNode = true;
+            if (!isClusterHttp2Enabled(clusterName, group)) {
+                return WatchProtocol.HTTP1;
+            }
+        }
+
+        return hasNode ? WatchProtocol.HTTP2 : WatchProtocol.HTTP1;
+    }
+
+    private static boolean watchHttp1(String clusterName) throws RetryableException {
+        Map<String, String> header = new HashMap<>();
+        header.put(HTTP.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.getMimeType());
+        Map<String, String> param = new HashMap<>();
+        Map<String, Long> groupTerms = METADATA.getClusterTerm(clusterName);
+        groupTerms.forEach((k, v) -> param.put(k, String.valueOf(v)));
+        for (String group : groupTerms.keySet()) {
+            String tcAddress = queryHttpAddress(clusterName, group);
+            if (StringUtils.isBlank(tcAddress)) {
+                return false;
+            }
+            if (isTokenExpired()) {
+                refreshToken(tcAddress);
+            }
+            if (StringUtils.isNotBlank(jwtToken)) {
+                header.put(AUTHORIZATION_HEADER, jwtToken);
+            }
+            try (Response response = HttpClientUtil.doPost(
+                    "http://" + tcAddress + "/metadata/v1/watch", param, header, (int) WATCH_TIMEOUT_MS)) {
+                if (response != null) {
+                    int statusCode = response.code();
+                    if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
+                        if (StringUtils.isNotBlank(USERNAME) && StringUtils.isNotBlank(PASSWORD)) {
+                            throw new RetryableException("Authentication failed!");
+                        } else {
+                            throw new AuthenticationFailedException(
+                                    "Authentication failed! you should configure the correct username and password.");
+                        }
+                    }
+                    return statusCode == HttpStatus.SC_OK;
+                }
+            } catch (IOException e) {
+                LOGGER.error("watch cluster node: {}, fail: {}", tcAddress, e.getMessage());
+                throw new RetryableException(e.getMessage(), e);
+            }
+            break;
+        }
+        return false;
+    }
+
+    private static boolean watchHttp2(String clusterName) throws RetryableException {
+        Map<String, Long> groupTerms = METADATA.getClusterTerm(clusterName);
+        if (CollectionUtils.isEmpty(groupTerms)) {
+            return false;
+        }
+
+        String group = selectWatchGroup(groupTerms);
+        if (StringUtils.isBlank(group)) {
+            return false;
+        }
+        String tcAddress = queryHttpAddress(clusterName, group);
+        if (StringUtils.isBlank(tcAddress)) {
+            return false;
+        }
+
+        Map<String, String> header = new HashMap<>();
+        header.put(HTTP.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.getMimeType());
+
+        Map<String, String> param = new HashMap<>();
+        groupTerms.forEach((k, v) -> param.put(k, String.valueOf(v)));
+
+        if (isTokenExpired()) {
+            refreshToken(tcAddress);
+        }
+        if (StringUtils.isNotBlank(jwtToken)) {
+            header.put(AUTHORIZATION_HEADER, jwtToken);
+        }
+
+        ensureHttp2Watch(group, tcAddress, param, header);
+        SeataHttpWatch<ClusterWatchEvent> watch = HTTP2_WATCH;
+        if (watch == null) {
+            return false;
+        }
+
+        try {
+            SeataHttpWatch.Response<ClusterWatchEvent> response = watch.next();
+            return shouldRefreshMetadata(clusterName, group, response);
+        } catch (RuntimeException e) {
+            if (CLOSED.get()) {
+                closeHttp2Watch();
+                return false;
+            }
+            closeHttp2Watch();
+            throw new RetryableException("HTTP2 watch failed", e);
+        }
+    }
+
+    private static String selectWatchGroup(Map<String, Long> groupTerms) {
+        if (CollectionUtils.isEmpty(groupTerms)) {
+            return null;
+        }
+
+        if (StringUtils.isNotBlank(HTTP2_WATCH_GROUP) && groupTerms.containsKey(HTTP2_WATCH_GROUP)) {
+            return HTTP2_WATCH_GROUP;
+        }
+
+        List<String> groups = new ArrayList<>(groupTerms.keySet());
+        Collections.sort(groups);
+        return groups.get(0);
+    }
+
+    private static synchronized void ensureHttp2Watch(
+            String group, String tcAddress, Map<String, String> param, Map<String, String> header)
+            throws RetryableException {
+
+        if (HTTP2_WATCH != null && StringUtils.equals(group, HTTP2_WATCH_GROUP)) {
+            return;
+        }
+
+        closeHttp2Watch();
+
+        try {
+            HTTP2_WATCH = HttpClientUtil.watchPost(
+                    "http://" + tcAddress + "/metadata/v1/watch",
+                    param,
+                    header,
+                    ClusterWatchEvent.class,
+                    HTTP2_WATCH_READ_TIMEOUT_SECONDS);
+            HTTP2_WATCH_GROUP = group;
+        } catch (IOException e) {
+            closeHttp2Watch();
+            throw new RetryableException(e.getMessage(), e);
+        } catch (RuntimeException e) {
+            closeHttp2Watch();
+            if (e.getMessage() != null && e.getMessage().contains("401")) {
+                tokenTimeStamp = -1;
+            }
+            throw new RetryableException("Failed to create HTTP2 watch", e);
+        }
+    }
+
+    private static boolean shouldRefreshMetadata(
+            String clusterName, String defaultGroup, SeataHttpWatch.Response<ClusterWatchEvent> response) {
+
+        if (response == null
+                || response.type != SeataHttpWatch.Response.Type.UPDATE
+                || response.object == null
+                || response.object.getMetadata() == null
+                || CollectionUtils.isEmpty(response.object.getMetadata().getNodes())) {
+            return false;
+        }
+
+        ClusterWatchEvent event = response.object;
+        MetadataResponse incomingMetadata = event.getMetadata();
+
+        String eventGroup = StringUtils.isNotBlank(event.getGroup()) ? event.getGroup() : defaultGroup;
+        long localTerm = METADATA.getClusterTerm(clusterName).getOrDefault(eventGroup, 0L);
+        boolean termAdvanced = incomingMetadata.getTerm() > localTerm;
+
+        boolean changed = termAdvanced || hasMetadataChanged(clusterName, eventGroup, incomingMetadata);
+
+        if (changed) {
+            METADATA.refreshMetadata(clusterName, incomingMetadata);
+        }
+
+        return changed;
+    }
+
+    private static boolean hasMetadataChanged(String clusterName, String group, MetadataResponse incomingMetadata) {
+        if (incomingMetadata == null) {
+            return false;
+        }
+
+        List<Node> incomingNodes = incomingMetadata.getNodes();
+        List<Node> localNodes = METADATA.getNodes(clusterName, group);
+
+        if (CollectionUtils.isEmpty(localNodes) != CollectionUtils.isEmpty(incomingNodes)) {
+            return true;
+        }
+
+        if (CollectionUtils.isEmpty(localNodes)) {
+            return false;
+        }
+
+        if (incomingMetadata.getTerm() != METADATA.getClusterTerm(clusterName).getOrDefault(group, 0L)) {

Review Comment:
   ```suggestion
           if (incomingMetadata.getTerm() > METADATA.getClusterTerm(clusterName).getOrDefault(group, -1L)) {
   ```



-- 
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: notifications-unsubscribe@seata.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@seata.apache.org
For additional commands, e-mail: notifications-help@seata.apache.org


Re: [PR] optimize: supports switching http protocols based on server versions in RaftRegistryService [incubator-seata]

Posted by "funky-eyes (via GitHub)" <gi...@apache.org>.
funky-eyes merged PR #7952:
URL: https://github.com/apache/incubator-seata/pull/7952


-- 
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: notifications-unsubscribe@seata.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@seata.apache.org
For additional commands, e-mail: notifications-help@seata.apache.org


Re: [PR] feat: raft Registry client is adapted to http2 watch [incubator-seata]

Posted by "Tsukilc (via GitHub)" <gi...@apache.org>.
Tsukilc closed pull request #7952: feat: raft Registry client is adapted to http2 watch
URL: https://github.com/apache/incubator-seata/pull/7952


-- 
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: notifications-unsubscribe@seata.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@seata.apache.org
For additional commands, e-mail: notifications-help@seata.apache.org


Re: [PR] optimize: supports switching http protocols based on server versions in RaftRegistryService [incubator-seata]

Posted by "funky-eyes (via GitHub)" <gi...@apache.org>.
funky-eyes commented on PR #7952:
URL: https://github.com/apache/incubator-seata/pull/7952#issuecomment-4323710866

   Has there been any progress on this PR?


-- 
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: notifications-unsubscribe@seata.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@seata.apache.org
For additional commands, e-mail: notifications-help@seata.apache.org


Re: [PR] optimize: supports switching http protocols based on server versions in RaftRegistryService [incubator-seata]

Posted by "Tsukilc (via GitHub)" <gi...@apache.org>.
Tsukilc commented on PR #7952:
URL: https://github.com/apache/incubator-seata/pull/7952#issuecomment-3982611107

   > Hi tsukilc, do you have any updates on this task?
   
   Yes, I will push the changes around this week.


-- 
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: notifications-unsubscribe@seata.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@seata.apache.org
For additional commands, e-mail: notifications-help@seata.apache.org


Re: [PR] optimize: supports switching http protocols based on server versions in RaftRegistryService [incubator-seata]

Posted by "funky-eyes (via GitHub)" <gi...@apache.org>.
funky-eyes commented on code in PR #7952:
URL: https://github.com/apache/incubator-seata/pull/7952#discussion_r2734987242


##########
changes/zh-cn/2.x.md:
##########
@@ -39,9 +39,11 @@
 - [[#7943](https://github.com/apache/incubator-seata/pull/7943)] 升级jib-maven-plugin版本和提高ci并行度
 - [[#7934](https://github.com/apache/incubator-seata/pull/7934)] 添加 OkHttp 和 MockWebServer 依赖来解决版本冲突
 - [[#7951](https://github.com/apache/incubator-seata/pull/7951)] 升级qs依赖版本至6.14.1
+- [[#7952](https://github.com/apache/incubator-seata/pull/7952)] : RaftRegistryService 支持基于服务器版本切换 http 协议版本

Review Comment:
   ```suggestion
   - [[#7952](https://github.com/apache/incubator-seata/pull/7952)] RaftRegistryService 支持基于服务器版本切换 http 协议版本
   ```



##########
changes/en-us/2.x.md:
##########
@@ -39,6 +39,8 @@ Add changes here for all PR submitted to the 2.x branch.
 - [[#7943](https://github.com/apache/incubator-seata/pull/7943)] update jib-maven-plugin version and increase parallel test execution limits
 - [[#7934](https://github.com/apache/incubator-seata/pull/7934)] add OkHttp and MockWebServer dependencies to resolve version conflicts
 - [[#7951](https://github.com/apache/incubator-seata/pull/7951)] upgrade qs dependency version to 6.14.1
+- [[#7952](https://github.com/apache/incubator-seata/pull/7952)] : supports switching http protocols based on server

Review Comment:
   ```suggestion
   - [[#7952](https://github.com/apache/incubator-seata/pull/7952)] supports switching http protocols based on server
   ```



-- 
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: notifications-unsubscribe@seata.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@seata.apache.org
For additional commands, e-mail: notifications-help@seata.apache.org


Re: [PR] optimize: supports switching http protocols based on server versions in RaftRegistryService [incubator-seata]

Posted by "funky-eyes (via GitHub)" <gi...@apache.org>.
funky-eyes commented on PR #7952:
URL: https://github.com/apache/incubator-seata/pull/7952#issuecomment-4340333127

   If you're using the DingTalk app, please send your DingTalk account to my email at jianbin@apache.org, and I will invite you to join the Seata developer group


-- 
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: notifications-unsubscribe@seata.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@seata.apache.org
For additional commands, e-mail: notifications-help@seata.apache.org


Re: [PR] feature: supports switching http protocols based on server versions in RaftRegistryService [incubator-seata]

Posted by "codecov[bot] (via GitHub)" <gi...@apache.org>.
codecov[bot] commented on PR #7952:
URL: https://github.com/apache/incubator-seata/pull/7952#issuecomment-3771539863

   ## [Codecov](https://app.codecov.io/gh/apache/incubator-seata/pull/7952?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
   :x: Patch coverage is `45.70552%` with `177 lines` in your changes missing coverage. Please review.
   :white_check_mark: Project coverage is 71.44%. Comparing base ([`e2bd89d`](https://app.codecov.io/gh/apache/incubator-seata/commit/e2bd89da56bda6503b575f1cae5102e1523f9564?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`cf870dc`](https://app.codecov.io/gh/apache/incubator-seata/commit/cf870dc349d7f327118f8f54b7fcf56ac8cc3b34?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
   
   | [Files with missing lines](https://app.codecov.io/gh/apache/incubator-seata/pull/7952?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Patch % | Lines |
   |---|---|---|
   | [...scovery/registry/raft/RaftRegistryServiceImpl.java](https://app.codecov.io/gh/apache/incubator-seata/pull/7952?src=pr&el=tree&filepath=discovery%2Fseata-discovery-raft%2Fsrc%2Fmain%2Fjava%2Forg%2Fapache%2Fseata%2Fdiscovery%2Fregistry%2Fraft%2FRaftRegistryServiceImpl.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-ZGlzY292ZXJ5L3NlYXRhLWRpc2NvdmVyeS1yYWZ0L3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9zZWF0YS9kaXNjb3ZlcnkvcmVnaXN0cnkvcmFmdC9SYWZ0UmVnaXN0cnlTZXJ2aWNlSW1wbC5qYXZh) | 45.09% | [135 Missing and 33 partials :warning: ](https://app.codecov.io/gh/apache/incubator-seata/pull/7952?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [...a/org/apache/seata/common/util/HttpClientUtil.java](https://app.codecov.io/gh/apache/incubator-seata/pull/7952?src=pr&el=tree&filepath=common%2Fsrc%2Fmain%2Fjava%2Forg%2Fapache%2Fseata%2Fcommon%2Futil%2FHttpClientUtil.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-Y29tbW9uL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9zZWF0YS9jb21tb24vdXRpbC9IdHRwQ2xpZW50VXRpbC5qYXZh) | 55.00% | [5 Missing and 4 partials :warning: ](https://app.codecov.io/gh/apache/incubator-seata/pull/7952?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   
   <details><summary>Additional details and impacted files</summary>
   
   
   
   ```diff
   @@             Coverage Diff              @@
   ##                2.x    #7952      +/-   ##
   ============================================
   - Coverage     71.60%   71.44%   -0.17%     
   - Complexity      884      904      +20     
   ============================================
     Files          1300     1300              
     Lines         49701    49932     +231     
     Branches       5895     5940      +45     
   ============================================
   + Hits          35589    35674      +85     
   - Misses        11192    11316     +124     
   - Partials       2920     2942      +22     
   ```
   
   | [Files with missing lines](https://app.codecov.io/gh/apache/incubator-seata/pull/7952?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Coverage Δ | |
   |---|---|---|
   | [...a/org/apache/seata/common/util/HttpClientUtil.java](https://app.codecov.io/gh/apache/incubator-seata/pull/7952?src=pr&el=tree&filepath=common%2Fsrc%2Fmain%2Fjava%2Forg%2Fapache%2Fseata%2Fcommon%2Futil%2FHttpClientUtil.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-Y29tbW9uL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9zZWF0YS9jb21tb24vdXRpbC9IdHRwQ2xpZW50VXRpbC5qYXZh) | `81.09% <55.00%> (-3.63%)` | :arrow_down: |
   | [...scovery/registry/raft/RaftRegistryServiceImpl.java](https://app.codecov.io/gh/apache/incubator-seata/pull/7952?src=pr&el=tree&filepath=discovery%2Fseata-discovery-raft%2Fsrc%2Fmain%2Fjava%2Forg%2Fapache%2Fseata%2Fdiscovery%2Fregistry%2Fraft%2FRaftRegistryServiceImpl.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-ZGlzY292ZXJ5L3NlYXRhLWRpc2NvdmVyeS1yYWZ0L3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9zZWF0YS9kaXNjb3ZlcnkvcmVnaXN0cnkvcmFmdC9SYWZ0UmVnaXN0cnlTZXJ2aWNlSW1wbC5qYXZh) | `58.11% <45.09%> (-18.28%)` | :arrow_down: |
   
   ... and [2 files with indirect coverage changes](https://app.codecov.io/gh/apache/incubator-seata/pull/7952/indirect-changes?src=pr&el=tree-more&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)
   
   [![Impacted file tree graph](https://app.codecov.io/gh/apache/incubator-seata/pull/7952/graphs/tree.svg?width=650&height=150&src=pr&token=tbmHt2ZfxO&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)](https://app.codecov.io/gh/apache/incubator-seata/pull/7952?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)
   </details>
   <details><summary> :rocket: New features to boost your workflow: </summary>
   
   - :snowflake: [Test Analytics](https://docs.codecov.com/docs/test-analytics): Detect flaky tests, report on failures, and find test suite problems.
   - :package: [JS Bundle Analysis](https://docs.codecov.com/docs/javascript-bundle-analysis): Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
   </details>


-- 
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: notifications-unsubscribe@seata.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@seata.apache.org
For additional commands, e-mail: notifications-help@seata.apache.org


Re: [PR] optimize: supports switching http protocols based on server versions in RaftRegistryService [incubator-seata]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #7952:
URL: https://github.com/apache/incubator-seata/pull/7952#discussion_r2944587541


##########
discovery/seata-discovery-raft/src/main/java/org/apache/seata/discovery/registry/raft/RaftRegistryServiceImpl.java:
##########
@@ -203,21 +233,302 @@ protected static void startQueryMetadata() {
                             } catch (RetryableException e) {
                                 LOGGER.error(e.getMessage(), e);
                                 try {
-                                    Thread.sleep(1000);
+                                    Thread.sleep(RETRY_DELAY_MS);
                                 } catch (InterruptedException ignored) {
                                 }
                             }
                         }
+                        closeHttp2Watch();
                     });
                     Runtime.getRuntime().addShutdownHook(new Thread(() -> {
                         CLOSED.compareAndSet(false, true);
-                        REFRESH_METADATA_EXECUTOR.shutdown();
+                        closeHttp2Watch();
+                        if (REFRESH_METADATA_EXECUTOR != null) {
+                            REFRESH_METADATA_EXECUTOR.shutdown();
+                        }
                     }));
                 }
             }
         }
     }
 
+    private static boolean watch() throws RetryableException {
+        String clusterName = CURRENT_TRANSACTION_CLUSTER_NAME;
+        if (StringUtils.isBlank(clusterName)) {
+            return false;
+        }
+
+        WatchProtocol targetProtocol = resolveWatchProtocol(clusterName);
+        switchWatchProtocolIfNecessary(targetProtocol);
+
+        if (targetProtocol == WatchProtocol.HTTP2) {
+            return watchHttp2(clusterName);
+        }
+        return watchHttp1(clusterName);
+    }
+
+    private static void switchWatchProtocolIfNecessary(WatchProtocol targetProtocol) {
+        if (CURRENT_WATCH_PROTOCOL == targetProtocol) {
+            return;
+        }
+
+        LOGGER.info("Switching raft watch protocol from {} to {}", CURRENT_WATCH_PROTOCOL, targetProtocol);
+        if (targetProtocol == WatchProtocol.HTTP1) {
+            closeHttp2Watch();
+        }
+        CURRENT_WATCH_PROTOCOL = targetProtocol;
+    }
+
+    private static WatchProtocol resolveWatchProtocol(String clusterName) {
+        if (StringUtils.isBlank(clusterName)) {
+            return WatchProtocol.HTTP1;
+        }
+
+        Set<String> groups = METADATA.groups(clusterName);
+        if (CollectionUtils.isEmpty(groups)) {
+            return WatchProtocol.HTTP1;
+        }
+
+        boolean hasNode = false;
+        for (String group : groups) {
+            List<Node> nodes = METADATA.getNodes(clusterName, group);
+            if (CollectionUtils.isEmpty(nodes)) {
+                continue;
+            }
+            hasNode = true;
+            if (!isClusterHttp2Enabled(clusterName, group)) {
+                return WatchProtocol.HTTP1;
+            }
+        }
+
+        return hasNode ? WatchProtocol.HTTP2 : WatchProtocol.HTTP1;
+    }
+
+    private static boolean watchHttp1(String clusterName) throws RetryableException {
+        Map<String, String> header = new HashMap<>();
+        header.put(HTTP.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.getMimeType());
+        Map<String, String> param = new HashMap<>();
+        Map<String, Long> groupTerms = METADATA.getClusterTerm(clusterName);
+        groupTerms.forEach((k, v) -> param.put(k, String.valueOf(v)));
+        for (String group : groupTerms.keySet()) {
+            String tcAddress = queryHttpAddress(clusterName, group);
+            if (StringUtils.isBlank(tcAddress)) {
+                return false;
+            }
+            if (isTokenExpired()) {
+                refreshToken(tcAddress);
+            }
+            if (StringUtils.isNotBlank(jwtToken)) {
+                header.put(AUTHORIZATION_HEADER, jwtToken);
+            }
+            try (Response response = HttpClientUtil.doPost(
+                    "http://" + tcAddress + "/metadata/v1/watch", param, header, (int) WATCH_TIMEOUT_MS)) {
+                if (response != null) {
+                    int statusCode = response.code();
+                    if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
+                        if (StringUtils.isNotBlank(USERNAME) && StringUtils.isNotBlank(PASSWORD)) {
+                            throw new RetryableException("Authentication failed!");
+                        } else {
+                            throw new AuthenticationFailedException(
+                                    "Authentication failed! you should configure the correct username and password.");
+                        }
+                    }
+                    return statusCode == HttpStatus.SC_OK;
+                }
+            } catch (IOException e) {
+                LOGGER.error("watch cluster node: {}, fail: {}", tcAddress, e.getMessage());
+                throw new RetryableException(e.getMessage(), e);
+            }
+            break;
+        }
+        return false;
+    }
+
+    private static boolean watchHttp2(String clusterName) throws RetryableException {
+        Map<String, Long> groupTerms = METADATA.getClusterTerm(clusterName);
+        if (CollectionUtils.isEmpty(groupTerms)) {
+            return false;
+        }
+
+        String group = selectWatchGroup(groupTerms);
+        if (StringUtils.isBlank(group)) {
+            return false;
+        }
+        String tcAddress = queryHttpAddress(clusterName, group);
+        if (StringUtils.isBlank(tcAddress)) {
+            return false;
+        }
+
+        Map<String, String> header = new HashMap<>();
+        header.put(HTTP.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.getMimeType());
+
+        Map<String, String> param = new HashMap<>();
+        groupTerms.forEach((k, v) -> param.put(k, String.valueOf(v)));
+
+        if (isTokenExpired()) {
+            refreshToken(tcAddress);
+        }
+        if (StringUtils.isNotBlank(jwtToken)) {
+            header.put(AUTHORIZATION_HEADER, jwtToken);
+        }
+
+        ensureHttp2Watch(group, tcAddress, param, header);
+        SeataHttpWatch<ClusterWatchEvent> watch = HTTP2_WATCH;
+        if (watch == null) {
+            return false;
+        }
+
+        try {
+            SeataHttpWatch.Response<ClusterWatchEvent> response = watch.next();
+            return shouldRefreshMetadata(clusterName, group, response);
+        } catch (RuntimeException e) {
+            if (CLOSED.get()) {
+                closeHttp2Watch();
+                return false;
+            }
+            closeHttp2Watch();
+            throw new RetryableException("HTTP2 watch failed", e);
+        }
+    }
+
+    private static String selectWatchGroup(Map<String, Long> groupTerms) {
+        if (CollectionUtils.isEmpty(groupTerms)) {
+            return null;
+        }
+
+        if (StringUtils.isNotBlank(HTTP2_WATCH_GROUP) && groupTerms.containsKey(HTTP2_WATCH_GROUP)) {
+            return HTTP2_WATCH_GROUP;
+        }
+
+        List<String> groups = new ArrayList<>(groupTerms.keySet());
+        Collections.sort(groups);
+        return groups.get(0);
+    }
+
+    private static synchronized void ensureHttp2Watch(
+            String group, String tcAddress, Map<String, String> param, Map<String, String> header)
+            throws RetryableException {
+
+        if (HTTP2_WATCH != null && StringUtils.equals(group, HTTP2_WATCH_GROUP)) {
+            return;
+        }
+
+        closeHttp2Watch();
+
+        try {
+            HTTP2_WATCH = HttpClientUtil.watchPost(
+                    "http://" + tcAddress + "/metadata/v1/watch",
+                    param,
+                    header,
+                    ClusterWatchEvent.class,
+                    HTTP2_WATCH_READ_TIMEOUT_SECONDS);
+            HTTP2_WATCH_GROUP = group;

Review Comment:
   `HTTP2_WATCH_READ_TIMEOUT_SECONDS` is set to 300s and passed into `HttpClientUtil.watchPost(...)`. In `startQueryMetadata`, the watch call runs on the same loop that enforces `metadataMaxAgeMs` refresh, so a long `watch.next()` block can prevent the periodic refresh from running for up to 5 minutes. Consider tying the HTTP/2 watch read timeout to `WATCH_TIMEOUT_MS` / `metadataMaxAgeMs`, or decoupling the periodic refresh timer from the blocking watch read so metadata refresh deadlines are still honored.



##########
discovery/seata-discovery-raft/pom.xml:
##########
@@ -35,6 +35,11 @@
             <artifactId>seata-discovery-core</artifactId>
             <version>${project.version}</version>
         </dependency>
+        <dependency>
+            <groupId>org.apache.seata</groupId>
+            <artifactId>seata-core</artifactId>
+            <version>${project.version}</version>
+        </dependency>
         <dependency>

Review Comment:
   This module adds a dependency on `seata-core` solely to use `org.apache.seata.core.protocol.Version` for version comparison. That increases coupling and pulls in Netty-related classes transitively, which is heavy for the discovery module and makes layering harder to maintain. Consider moving the version comparison helper to `seata-common` (or duplicating a minimal comparator locally) so `seata-discovery-raft` doesn’t need to depend on `seata-core`.
   



##########
discovery/seata-discovery-raft/src/main/java/org/apache/seata/discovery/registry/raft/RaftRegistryServiceImpl.java:
##########
@@ -574,6 +854,30 @@ private static void refreshToken(String tcAddress) throws RetryableException {
         }
     }
 
+    private static boolean supportsHttp2(Node node) {
+        if (node == null) {
+            return false;
+        }
+        String version = node.getVersion();
+        if (StringUtils.isBlank(version)) {
+            return false;
+        }
+        try {
+            return Version.isAboveOrEqualVersion(version, MIN_HTTP2_VERSION);
+        } catch (Exception e) {
+            LOGGER.warn("Invalid version: {}, fallback to HTTP/1.1", version);
+            return false;
+        }

Review Comment:
   `supportsHttp2` wraps `Version.isAboveOrEqualVersion(...)` in a try/catch, but `Version.isAboveOrEqualVersion` already catches conversion errors internally and returns `false` (logging at ERROR). As written, this catch block will effectively never run for invalid versions, and the WARN log here is misleading/unreachable. Consider removing the try/catch, or switching to a version utility that throws so the warning path is meaningful (and ideally avoid double-logging on invalid versions).
   



##########
discovery/seata-discovery-raft/src/main/java/org/apache/seata/discovery/registry/raft/RaftRegistryServiceImpl.java:
##########
@@ -203,21 +233,302 @@ protected static void startQueryMetadata() {
                             } catch (RetryableException e) {
                                 LOGGER.error(e.getMessage(), e);
                                 try {
-                                    Thread.sleep(1000);
+                                    Thread.sleep(RETRY_DELAY_MS);
                                 } catch (InterruptedException ignored) {
                                 }
                             }
                         }
+                        closeHttp2Watch();
                     });
                     Runtime.getRuntime().addShutdownHook(new Thread(() -> {
                         CLOSED.compareAndSet(false, true);
-                        REFRESH_METADATA_EXECUTOR.shutdown();
+                        closeHttp2Watch();
+                        if (REFRESH_METADATA_EXECUTOR != null) {
+                            REFRESH_METADATA_EXECUTOR.shutdown();
+                        }
                     }));
                 }
             }
         }
     }
 
+    private static boolean watch() throws RetryableException {
+        String clusterName = CURRENT_TRANSACTION_CLUSTER_NAME;
+        if (StringUtils.isBlank(clusterName)) {
+            return false;
+        }
+
+        WatchProtocol targetProtocol = resolveWatchProtocol(clusterName);
+        switchWatchProtocolIfNecessary(targetProtocol);
+
+        if (targetProtocol == WatchProtocol.HTTP2) {
+            return watchHttp2(clusterName);
+        }
+        return watchHttp1(clusterName);
+    }
+
+    private static void switchWatchProtocolIfNecessary(WatchProtocol targetProtocol) {
+        if (CURRENT_WATCH_PROTOCOL == targetProtocol) {
+            return;
+        }
+
+        LOGGER.info("Switching raft watch protocol from {} to {}", CURRENT_WATCH_PROTOCOL, targetProtocol);
+        if (targetProtocol == WatchProtocol.HTTP1) {
+            closeHttp2Watch();
+        }
+        CURRENT_WATCH_PROTOCOL = targetProtocol;
+    }
+
+    private static WatchProtocol resolveWatchProtocol(String clusterName) {
+        if (StringUtils.isBlank(clusterName)) {
+            return WatchProtocol.HTTP1;
+        }
+
+        Set<String> groups = METADATA.groups(clusterName);
+        if (CollectionUtils.isEmpty(groups)) {
+            return WatchProtocol.HTTP1;
+        }
+
+        boolean hasNode = false;
+        for (String group : groups) {
+            List<Node> nodes = METADATA.getNodes(clusterName, group);
+            if (CollectionUtils.isEmpty(nodes)) {
+                continue;
+            }
+            hasNode = true;
+            if (!isClusterHttp2Enabled(clusterName, group)) {
+                return WatchProtocol.HTTP1;
+            }
+        }
+
+        return hasNode ? WatchProtocol.HTTP2 : WatchProtocol.HTTP1;
+    }
+
+    private static boolean watchHttp1(String clusterName) throws RetryableException {
+        Map<String, String> header = new HashMap<>();
+        header.put(HTTP.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.getMimeType());
+        Map<String, String> param = new HashMap<>();
+        Map<String, Long> groupTerms = METADATA.getClusterTerm(clusterName);
+        groupTerms.forEach((k, v) -> param.put(k, String.valueOf(v)));
+        for (String group : groupTerms.keySet()) {
+            String tcAddress = queryHttpAddress(clusterName, group);
+            if (StringUtils.isBlank(tcAddress)) {
+                return false;
+            }
+            if (isTokenExpired()) {
+                refreshToken(tcAddress);
+            }
+            if (StringUtils.isNotBlank(jwtToken)) {
+                header.put(AUTHORIZATION_HEADER, jwtToken);
+            }
+            try (Response response = HttpClientUtil.doPost(
+                    "http://" + tcAddress + "/metadata/v1/watch", param, header, (int) WATCH_TIMEOUT_MS)) {
+                if (response != null) {
+                    int statusCode = response.code();
+                    if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
+                        if (StringUtils.isNotBlank(USERNAME) && StringUtils.isNotBlank(PASSWORD)) {
+                            throw new RetryableException("Authentication failed!");
+                        } else {
+                            throw new AuthenticationFailedException(
+                                    "Authentication failed! you should configure the correct username and password.");
+                        }
+                    }
+                    return statusCode == HttpStatus.SC_OK;
+                }
+            } catch (IOException e) {
+                LOGGER.error("watch cluster node: {}, fail: {}", tcAddress, e.getMessage());
+                throw new RetryableException(e.getMessage(), e);
+            }
+            break;
+        }
+        return false;
+    }
+
+    private static boolean watchHttp2(String clusterName) throws RetryableException {
+        Map<String, Long> groupTerms = METADATA.getClusterTerm(clusterName);
+        if (CollectionUtils.isEmpty(groupTerms)) {
+            return false;
+        }
+
+        String group = selectWatchGroup(groupTerms);
+        if (StringUtils.isBlank(group)) {
+            return false;
+        }
+        String tcAddress = queryHttpAddress(clusterName, group);
+        if (StringUtils.isBlank(tcAddress)) {
+            return false;
+        }
+
+        Map<String, String> header = new HashMap<>();
+        header.put(HTTP.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.getMimeType());
+
+        Map<String, String> param = new HashMap<>();
+        groupTerms.forEach((k, v) -> param.put(k, String.valueOf(v)));
+
+        if (isTokenExpired()) {
+            refreshToken(tcAddress);
+        }
+        if (StringUtils.isNotBlank(jwtToken)) {
+            header.put(AUTHORIZATION_HEADER, jwtToken);
+        }
+
+        ensureHttp2Watch(group, tcAddress, param, header);
+        SeataHttpWatch<ClusterWatchEvent> watch = HTTP2_WATCH;
+        if (watch == null) {
+            return false;
+        }
+
+        try {
+            SeataHttpWatch.Response<ClusterWatchEvent> response = watch.next();
+            return shouldRefreshMetadata(clusterName, group, response);
+        } catch (RuntimeException e) {
+            if (CLOSED.get()) {
+                closeHttp2Watch();
+                return false;
+            }
+            closeHttp2Watch();
+            throw new RetryableException("HTTP2 watch failed", e);
+        }
+    }
+
+    private static String selectWatchGroup(Map<String, Long> groupTerms) {
+        if (CollectionUtils.isEmpty(groupTerms)) {
+            return null;
+        }
+
+        if (StringUtils.isNotBlank(HTTP2_WATCH_GROUP) && groupTerms.containsKey(HTTP2_WATCH_GROUP)) {
+            return HTTP2_WATCH_GROUP;
+        }
+
+        List<String> groups = new ArrayList<>(groupTerms.keySet());
+        Collections.sort(groups);
+        return groups.get(0);
+    }
+
+    private static synchronized void ensureHttp2Watch(
+            String group, String tcAddress, Map<String, String> param, Map<String, String> header)
+            throws RetryableException {
+
+        if (HTTP2_WATCH != null && StringUtils.equals(group, HTTP2_WATCH_GROUP)) {
+            return;
+        }
+
+        closeHttp2Watch();
+
+        try {
+            HTTP2_WATCH = HttpClientUtil.watchPost(
+                    "http://" + tcAddress + "/metadata/v1/watch",
+                    param,
+                    header,
+                    ClusterWatchEvent.class,
+                    HTTP2_WATCH_READ_TIMEOUT_SECONDS);
+            HTTP2_WATCH_GROUP = group;
+        } catch (IOException e) {
+            closeHttp2Watch();
+            throw new RetryableException(e.getMessage(), e);
+        } catch (RuntimeException e) {
+            closeHttp2Watch();
+            if (e.getMessage() != null && e.getMessage().contains("401")) {
+                tokenTimeStamp = -1;
+            }
+            throw new RetryableException("Failed to create HTTP2 watch", e);
+        }
+    }
+
+    private static boolean shouldRefreshMetadata(
+            String clusterName, String defaultGroup, SeataHttpWatch.Response<ClusterWatchEvent> response) {
+
+        if (response == null
+                || response.type != SeataHttpWatch.Response.Type.UPDATE
+                || response.object == null
+                || response.object.getMetadata() == null
+                || CollectionUtils.isEmpty(response.object.getMetadata().getNodes())) {
+            return false;
+        }
+
+        ClusterWatchEvent event = response.object;
+        MetadataResponse incomingMetadata = event.getMetadata();
+
+        String eventGroup = StringUtils.isNotBlank(event.getGroup()) ? event.getGroup() : defaultGroup;
+        long localTerm = METADATA.getClusterTerm(clusterName).getOrDefault(eventGroup, 0L);
+        boolean termAdvanced = incomingMetadata.getTerm() > localTerm;
+
+        boolean changed = termAdvanced || hasMetadataChanged(clusterName, eventGroup, incomingMetadata);
+
+        if (changed) {
+            METADATA.refreshMetadata(clusterName, incomingMetadata);
+        }
+
+        return changed;
+    }
+
+    private static boolean hasMetadataChanged(String clusterName, String group, MetadataResponse incomingMetadata) {
+        if (incomingMetadata == null) {
+            return false;
+        }
+
+        List<Node> incomingNodes = incomingMetadata.getNodes();
+        List<Node> localNodes = METADATA.getNodes(clusterName, group);
+
+        if (CollectionUtils.isEmpty(localNodes) != CollectionUtils.isEmpty(incomingNodes)) {
+            return true;
+        }
+
+        if (CollectionUtils.isEmpty(localNodes)) {
+            return false;
+        }
+
+        if (incomingMetadata.getTerm() != METADATA.getClusterTerm(clusterName).getOrDefault(group, 0L)) {
+            return true;
+        }

Review Comment:
   `hasMetadataChanged` treats any term mismatch as a change (`incomingTerm != localTerm`), and `shouldRefreshMetadata` will then refresh metadata even when the incoming term is *lower* than the local term. That can regress `clusterTerm` and leader selection if an out-of-order/stale watch event is received. Consider ignoring events with `incomingTerm < localTerm` (and only treating term mismatch as change when `incomingTerm > localTerm`) to keep terms monotonic.



-- 
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: notifications-unsubscribe@seata.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@seata.apache.org
For additional commands, e-mail: notifications-help@seata.apache.org


Re: [PR] optimize: supports switching http protocols based on server versions in RaftRegistryService [incubator-seata]

Posted by "Tsukilc (via GitHub)" <gi...@apache.org>.
Tsukilc commented on code in PR #7952:
URL: https://github.com/apache/incubator-seata/pull/7952#discussion_r2901893705


##########
discovery/seata-discovery-raft/src/main/java/org/apache/seata/discovery/registry/raft/RaftRegistryServiceImpl.java:
##########
@@ -203,21 +234,277 @@ protected static void startQueryMetadata() {
                             } catch (RetryableException e) {
                                 LOGGER.error(e.getMessage(), e);
                                 try {
-                                    Thread.sleep(1000);
+                                    Thread.sleep(RETRY_DELAY_MS);
                                 } catch (InterruptedException ignored) {
                                 }
                             }
                         }
+                        closeHttp2Watch();
                     });
                     Runtime.getRuntime().addShutdownHook(new Thread(() -> {
                         CLOSED.compareAndSet(false, true);
-                        REFRESH_METADATA_EXECUTOR.shutdown();
+                        closeHttp2Watch();
+                        if (REFRESH_METADATA_EXECUTOR != null) {
+                            REFRESH_METADATA_EXECUTOR.shutdown();
+                        }
                     }));
                 }
             }
         }
     }
 
+    private static boolean watch() throws RetryableException {
+        String clusterName = CURRENT_TRANSACTION_CLUSTER_NAME;
+        if (StringUtils.isBlank(clusterName)) {
+            return false;
+        }
+
+        WatchProtocol targetProtocol = resolveWatchProtocol(clusterName);
+        switchWatchProtocolIfNecessary(targetProtocol);
+
+        if (targetProtocol == WatchProtocol.HTTP2) {
+            return watchHttp2(clusterName);
+        }
+        return watchHttp1(clusterName);
+    }
+
+    private static void switchWatchProtocolIfNecessary(WatchProtocol targetProtocol) {

Review Comment:
   Switch when the target protocol differs from the current protocol, enabling rolling updates.



##########
discovery/seata-discovery-raft/src/main/java/org/apache/seata/discovery/registry/raft/RaftRegistryServiceImpl.java:
##########
@@ -203,21 +234,277 @@ protected static void startQueryMetadata() {
                             } catch (RetryableException e) {
                                 LOGGER.error(e.getMessage(), e);
                                 try {
-                                    Thread.sleep(1000);
+                                    Thread.sleep(RETRY_DELAY_MS);
                                 } catch (InterruptedException ignored) {
                                 }
                             }
                         }
+                        closeHttp2Watch();
                     });
                     Runtime.getRuntime().addShutdownHook(new Thread(() -> {
                         CLOSED.compareAndSet(false, true);
-                        REFRESH_METADATA_EXECUTOR.shutdown();
+                        closeHttp2Watch();
+                        if (REFRESH_METADATA_EXECUTOR != null) {
+                            REFRESH_METADATA_EXECUTOR.shutdown();
+                        }
                     }));
                 }
             }
         }
     }
 
+    private static boolean watch() throws RetryableException {
+        String clusterName = CURRENT_TRANSACTION_CLUSTER_NAME;
+        if (StringUtils.isBlank(clusterName)) {
+            return false;
+        }
+
+        WatchProtocol targetProtocol = resolveWatchProtocol(clusterName);
+        switchWatchProtocolIfNecessary(targetProtocol);
+
+        if (targetProtocol == WatchProtocol.HTTP2) {
+            return watchHttp2(clusterName);
+        }
+        return watchHttp1(clusterName);
+    }
+
+    private static void switchWatchProtocolIfNecessary(WatchProtocol targetProtocol) {
+        if (CURRENT_WATCH_PROTOCOL == targetProtocol) {
+            return;
+        }
+
+        LOGGER.info("Switching raft watch protocol from {} to {}", CURRENT_WATCH_PROTOCOL, targetProtocol);
+        if (targetProtocol == WatchProtocol.HTTP1) {
+            closeHttp2Watch();
+        }
+        CURRENT_WATCH_PROTOCOL = targetProtocol;
+    }
+
+    private static WatchProtocol resolveWatchProtocol(String clusterName) {
+        if (StringUtils.isBlank(clusterName)) {
+            return WatchProtocol.HTTP1;
+        }
+
+        Set<String> groups = METADATA.groups(clusterName);
+        if (CollectionUtils.isEmpty(groups)) {
+            return WatchProtocol.HTTP1;
+        }
+
+        boolean hasNode = false;
+        for (String group : groups) {
+            List<Node> nodes = METADATA.getNodes(clusterName, group);
+            if (CollectionUtils.isEmpty(nodes)) {
+                continue;
+            }
+            hasNode = true;
+            if (!isClusterHttp2Enabled(clusterName, group)) {
+                return WatchProtocol.HTTP1;
+            }
+        }
+
+        return hasNode ? WatchProtocol.HTTP2 : WatchProtocol.HTTP1;
+    }
+
+    private static boolean watchHttp1(String clusterName) throws RetryableException {
+        Map<String, String> header = new HashMap<>();
+        header.put(HTTP.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.getMimeType());
+        Map<String, String> param = new HashMap<>();
+        Map<String, Long> groupTerms = METADATA.getClusterTerm(clusterName);
+        groupTerms.forEach((k, v) -> param.put(k, String.valueOf(v)));
+        for (String group : groupTerms.keySet()) {
+            String tcAddress = queryHttpAddress(clusterName, group);
+            if (StringUtils.isBlank(tcAddress)) {
+                return false;
+            }
+            if (isTokenExpired()) {
+                refreshToken(tcAddress);
+            }
+            if (StringUtils.isNotBlank(jwtToken)) {
+                header.put(AUTHORIZATION_HEADER, jwtToken);
+            }
+            try (Response response = HttpClientUtil.doPost(
+                    "http://" + tcAddress + "/metadata/v1/watch", param, header, (int) WATCH_TIMEOUT_MS)) {
+                if (response != null) {
+                    int statusCode = response.code();
+                    if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
+                        if (StringUtils.isNotBlank(USERNAME) && StringUtils.isNotBlank(PASSWORD)) {
+                            throw new RetryableException("Authentication failed!");
+                        } else {
+                            throw new AuthenticationFailedException(
+                                    "Authentication failed! you should configure the correct username and password.");
+                        }
+                    }
+                    return statusCode == HttpStatus.SC_OK;
+                }
+            } catch (IOException e) {
+                LOGGER.error("watch cluster node: {}, fail: {}", tcAddress, e.getMessage());
+                throw new RetryableException(e.getMessage(), e);
+            }
+            break;
+        }
+        return false;
+    }
+
+    private static boolean watchHttp2(String clusterName) throws RetryableException {
+        Map<String, Long> groupTerms = METADATA.getClusterTerm(clusterName);
+        if (CollectionUtils.isEmpty(groupTerms)) {
+            return false;
+        }
+
+        String group = groupTerms.keySet().iterator().next();
+        String tcAddress = queryHttpAddress(clusterName, group);
+        if (StringUtils.isBlank(tcAddress)) {
+            return false;
+        }
+
+        Map<String, String> header = new HashMap<>();
+        header.put(HTTP.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.getMimeType());
+
+        Map<String, String> param = new HashMap<>();
+        groupTerms.forEach((k, v) -> param.put(k, String.valueOf(v)));
+
+        if (isTokenExpired()) {
+            refreshToken(tcAddress);
+        }
+        if (StringUtils.isNotBlank(jwtToken)) {
+            header.put(AUTHORIZATION_HEADER, jwtToken);
+        }
+
+        ensureHttp2Watch(group, tcAddress, param, header);
+
+        try {
+            SeataHttpWatch.Response<ClusterWatchEvent> response = HTTP2_WATCH.next();
+            return shouldRefreshMetadata(clusterName, group, response);
+        } catch (RuntimeException e) {
+            closeHttp2Watch();
+            throw new RetryableException("HTTP2 watch failed", e);
+        }
+    }
+
+    private static synchronized void ensureHttp2Watch(
+            String group, String tcAddress, Map<String, String> param, Map<String, String> header)
+            throws RetryableException {
+
+        if (HTTP2_WATCH != null && StringUtils.equals(group, HTTP2_WATCH_GROUP)) {
+            return;
+        }
+
+        closeHttp2Watch();
+
+        try {
+            HTTP2_WATCH = HttpClientUtil.watchPost(
+                    "http://" + tcAddress + "/metadata/v1/watch",
+                    param,
+                    header,
+                    ClusterWatchEvent.class,
+                    HTTP2_WATCH_READ_TIMEOUT_SECONDS);
+            HTTP2_WATCH_GROUP = group;
+        } catch (IOException e) {
+            closeHttp2Watch();
+            throw new RetryableException(e.getMessage(), e);
+        } catch (RuntimeException e) {
+            closeHttp2Watch();
+            if (e.getMessage() != null && e.getMessage().contains("401")) {
+                tokenTimeStamp = -1;
+            }
+            throw new RetryableException("Failed to create HTTP2 watch", e);
+        }
+    }
+
+    private static boolean shouldRefreshMetadata(
+            String clusterName, String defaultGroup, SeataHttpWatch.Response<ClusterWatchEvent> response) {
+
+        if (response == null
+                || response.type != SeataHttpWatch.Response.Type.UPDATE
+                || response.object == null
+                || response.object.getMetadata() == null
+                || CollectionUtils.isEmpty(response.object.getMetadata().getNodes())) {
+            return false;
+        }
+
+        ClusterWatchEvent event = response.object;
+        MetadataResponse incomingMetadata = event.getMetadata();
+
+        String eventGroup = StringUtils.isNotBlank(event.getGroup()) ? event.getGroup() : defaultGroup;
+        long localTerm = METADATA.getClusterTerm(clusterName).getOrDefault(eventGroup, 0L);
+        boolean termAdvanced = incomingMetadata.getTerm() > localTerm;
+
+        boolean changed = termAdvanced || hasMetadataChanged(clusterName, eventGroup, incomingMetadata);
+
+        if (changed) {
+            METADATA.refreshMetadata(clusterName, incomingMetadata);
+        }
+
+        return changed;
+    }
+
+    private static boolean hasMetadataChanged(String clusterName, String group, MetadataResponse incomingMetadata) {

Review Comment:
   Used to determine whether there are changes in the node metadata.to ensure don't refresh if there are no changes.



-- 
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: notifications-unsubscribe@seata.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@seata.apache.org
For additional commands, e-mail: notifications-help@seata.apache.org


Re: [PR] optimize: supports switching http protocols based on server versions in RaftRegistryService [incubator-seata]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #7952:
URL: https://github.com/apache/incubator-seata/pull/7952#discussion_r2921764190


##########
discovery/seata-discovery-raft/src/main/java/org/apache/seata/discovery/registry/raft/RaftRegistryServiceImpl.java:
##########
@@ -203,21 +234,277 @@ protected static void startQueryMetadata() {
                             } catch (RetryableException e) {
                                 LOGGER.error(e.getMessage(), e);
                                 try {
-                                    Thread.sleep(1000);
+                                    Thread.sleep(RETRY_DELAY_MS);
                                 } catch (InterruptedException ignored) {
                                 }
                             }
                         }
+                        closeHttp2Watch();
                     });
                     Runtime.getRuntime().addShutdownHook(new Thread(() -> {
                         CLOSED.compareAndSet(false, true);
-                        REFRESH_METADATA_EXECUTOR.shutdown();
+                        closeHttp2Watch();
+                        if (REFRESH_METADATA_EXECUTOR != null) {
+                            REFRESH_METADATA_EXECUTOR.shutdown();
+                        }
                     }));
                 }
             }
         }
     }
 
+    private static boolean watch() throws RetryableException {
+        String clusterName = CURRENT_TRANSACTION_CLUSTER_NAME;
+        if (StringUtils.isBlank(clusterName)) {
+            return false;
+        }
+
+        WatchProtocol targetProtocol = resolveWatchProtocol(clusterName);
+        switchWatchProtocolIfNecessary(targetProtocol);
+
+        if (targetProtocol == WatchProtocol.HTTP2) {
+            return watchHttp2(clusterName);
+        }
+        return watchHttp1(clusterName);
+    }
+
+    private static void switchWatchProtocolIfNecessary(WatchProtocol targetProtocol) {
+        if (CURRENT_WATCH_PROTOCOL == targetProtocol) {
+            return;
+        }
+
+        LOGGER.info("Switching raft watch protocol from {} to {}", CURRENT_WATCH_PROTOCOL, targetProtocol);
+        if (targetProtocol == WatchProtocol.HTTP1) {
+            closeHttp2Watch();
+        }
+        CURRENT_WATCH_PROTOCOL = targetProtocol;
+    }
+
+    private static WatchProtocol resolveWatchProtocol(String clusterName) {
+        if (StringUtils.isBlank(clusterName)) {
+            return WatchProtocol.HTTP1;
+        }
+
+        Set<String> groups = METADATA.groups(clusterName);
+        if (CollectionUtils.isEmpty(groups)) {
+            return WatchProtocol.HTTP1;
+        }
+
+        boolean hasNode = false;
+        for (String group : groups) {
+            List<Node> nodes = METADATA.getNodes(clusterName, group);
+            if (CollectionUtils.isEmpty(nodes)) {
+                continue;
+            }
+            hasNode = true;
+            if (!isClusterHttp2Enabled(clusterName, group)) {
+                return WatchProtocol.HTTP1;
+            }
+        }
+
+        return hasNode ? WatchProtocol.HTTP2 : WatchProtocol.HTTP1;
+    }
+
+    private static boolean watchHttp1(String clusterName) throws RetryableException {
+        Map<String, String> header = new HashMap<>();
+        header.put(HTTP.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.getMimeType());
+        Map<String, String> param = new HashMap<>();
+        Map<String, Long> groupTerms = METADATA.getClusterTerm(clusterName);
+        groupTerms.forEach((k, v) -> param.put(k, String.valueOf(v)));
+        for (String group : groupTerms.keySet()) {
+            String tcAddress = queryHttpAddress(clusterName, group);
+            if (StringUtils.isBlank(tcAddress)) {
+                return false;
+            }
+            if (isTokenExpired()) {
+                refreshToken(tcAddress);
+            }
+            if (StringUtils.isNotBlank(jwtToken)) {
+                header.put(AUTHORIZATION_HEADER, jwtToken);
+            }
+            try (Response response = HttpClientUtil.doPost(
+                    "http://" + tcAddress + "/metadata/v1/watch", param, header, (int) WATCH_TIMEOUT_MS)) {
+                if (response != null) {
+                    int statusCode = response.code();
+                    if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
+                        if (StringUtils.isNotBlank(USERNAME) && StringUtils.isNotBlank(PASSWORD)) {
+                            throw new RetryableException("Authentication failed!");
+                        } else {
+                            throw new AuthenticationFailedException(
+                                    "Authentication failed! you should configure the correct username and password.");
+                        }
+                    }
+                    return statusCode == HttpStatus.SC_OK;
+                }
+            } catch (IOException e) {
+                LOGGER.error("watch cluster node: {}, fail: {}", tcAddress, e.getMessage());
+                throw new RetryableException(e.getMessage(), e);
+            }
+            break;
+        }
+        return false;
+    }
+
+    private static boolean watchHttp2(String clusterName) throws RetryableException {
+        Map<String, Long> groupTerms = METADATA.getClusterTerm(clusterName);
+        if (CollectionUtils.isEmpty(groupTerms)) {
+            return false;
+        }
+
+        String group = groupTerms.keySet().iterator().next();
+        String tcAddress = queryHttpAddress(clusterName, group);
+        if (StringUtils.isBlank(tcAddress)) {
+            return false;
+        }
+
+        Map<String, String> header = new HashMap<>();
+        header.put(HTTP.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.getMimeType());
+
+        Map<String, String> param = new HashMap<>();
+        groupTerms.forEach((k, v) -> param.put(k, String.valueOf(v)));
+
+        if (isTokenExpired()) {
+            refreshToken(tcAddress);
+        }
+        if (StringUtils.isNotBlank(jwtToken)) {
+            header.put(AUTHORIZATION_HEADER, jwtToken);
+        }
+
+        ensureHttp2Watch(group, tcAddress, param, header);
+
+        try {
+            SeataHttpWatch.Response<ClusterWatchEvent> response = HTTP2_WATCH.next();
+            return shouldRefreshMetadata(clusterName, group, response);
+        } catch (RuntimeException e) {
+            closeHttp2Watch();
+            throw new RetryableException("HTTP2 watch failed", e);

Review Comment:
   `watchHttp2` calls `HTTP2_WATCH.next()` directly on the volatile field. Since `closeHttp2Watch()` can be called concurrently (e.g., via `close()` or the shutdown hook) and sets `HTTP2_WATCH` to null, this can race and throw a `NullPointerException`. Capture `HTTP2_WATCH` into a local variable (or synchronize around read/close) before calling `next()`, and handle the case where it becomes null during shutdown.



##########
discovery/seata-discovery-raft/pom.xml:
##########
@@ -43,9 +48,14 @@
             <groupId>com.squareup.okhttp3</groupId>
             <artifactId>okhttp</artifactId>
         </dependency>
+        <dependency>
+            <groupId>com.squareup.okhttp3</groupId>
+            <artifactId>mockwebserver</artifactId>
+            <scope>test</scope>
+        </dependency>
         <dependency>

Review Comment:
   The `mockwebserver` test dependency appears unused in this module (no references under `src/test/java`). If it's not needed for these tests, it should be removed to avoid pulling in extra artifacts and keeping the module's dependency set minimal.
   ```suggestion
   
   ```



##########
discovery/seata-discovery-raft/src/main/java/org/apache/seata/discovery/registry/raft/RaftRegistryServiceImpl.java:
##########
@@ -203,21 +234,277 @@ protected static void startQueryMetadata() {
                             } catch (RetryableException e) {
                                 LOGGER.error(e.getMessage(), e);
                                 try {
-                                    Thread.sleep(1000);
+                                    Thread.sleep(RETRY_DELAY_MS);
                                 } catch (InterruptedException ignored) {
                                 }
                             }
                         }
+                        closeHttp2Watch();
                     });
                     Runtime.getRuntime().addShutdownHook(new Thread(() -> {
                         CLOSED.compareAndSet(false, true);
-                        REFRESH_METADATA_EXECUTOR.shutdown();
+                        closeHttp2Watch();
+                        if (REFRESH_METADATA_EXECUTOR != null) {
+                            REFRESH_METADATA_EXECUTOR.shutdown();
+                        }
                     }));
                 }
             }
         }
     }
 
+    private static boolean watch() throws RetryableException {
+        String clusterName = CURRENT_TRANSACTION_CLUSTER_NAME;
+        if (StringUtils.isBlank(clusterName)) {
+            return false;
+        }
+
+        WatchProtocol targetProtocol = resolveWatchProtocol(clusterName);
+        switchWatchProtocolIfNecessary(targetProtocol);
+
+        if (targetProtocol == WatchProtocol.HTTP2) {
+            return watchHttp2(clusterName);
+        }
+        return watchHttp1(clusterName);
+    }
+
+    private static void switchWatchProtocolIfNecessary(WatchProtocol targetProtocol) {
+        if (CURRENT_WATCH_PROTOCOL == targetProtocol) {
+            return;
+        }
+
+        LOGGER.info("Switching raft watch protocol from {} to {}", CURRENT_WATCH_PROTOCOL, targetProtocol);
+        if (targetProtocol == WatchProtocol.HTTP1) {
+            closeHttp2Watch();
+        }
+        CURRENT_WATCH_PROTOCOL = targetProtocol;
+    }
+
+    private static WatchProtocol resolveWatchProtocol(String clusterName) {
+        if (StringUtils.isBlank(clusterName)) {
+            return WatchProtocol.HTTP1;
+        }
+
+        Set<String> groups = METADATA.groups(clusterName);
+        if (CollectionUtils.isEmpty(groups)) {
+            return WatchProtocol.HTTP1;
+        }
+
+        boolean hasNode = false;
+        for (String group : groups) {
+            List<Node> nodes = METADATA.getNodes(clusterName, group);
+            if (CollectionUtils.isEmpty(nodes)) {
+                continue;
+            }
+            hasNode = true;
+            if (!isClusterHttp2Enabled(clusterName, group)) {
+                return WatchProtocol.HTTP1;
+            }
+        }
+
+        return hasNode ? WatchProtocol.HTTP2 : WatchProtocol.HTTP1;
+    }
+
+    private static boolean watchHttp1(String clusterName) throws RetryableException {
+        Map<String, String> header = new HashMap<>();
+        header.put(HTTP.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.getMimeType());
+        Map<String, String> param = new HashMap<>();
+        Map<String, Long> groupTerms = METADATA.getClusterTerm(clusterName);
+        groupTerms.forEach((k, v) -> param.put(k, String.valueOf(v)));
+        for (String group : groupTerms.keySet()) {
+            String tcAddress = queryHttpAddress(clusterName, group);
+            if (StringUtils.isBlank(tcAddress)) {
+                return false;
+            }
+            if (isTokenExpired()) {
+                refreshToken(tcAddress);
+            }
+            if (StringUtils.isNotBlank(jwtToken)) {
+                header.put(AUTHORIZATION_HEADER, jwtToken);
+            }
+            try (Response response = HttpClientUtil.doPost(
+                    "http://" + tcAddress + "/metadata/v1/watch", param, header, (int) WATCH_TIMEOUT_MS)) {
+                if (response != null) {
+                    int statusCode = response.code();
+                    if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
+                        if (StringUtils.isNotBlank(USERNAME) && StringUtils.isNotBlank(PASSWORD)) {
+                            throw new RetryableException("Authentication failed!");
+                        } else {
+                            throw new AuthenticationFailedException(
+                                    "Authentication failed! you should configure the correct username and password.");
+                        }
+                    }
+                    return statusCode == HttpStatus.SC_OK;
+                }
+            } catch (IOException e) {
+                LOGGER.error("watch cluster node: {}, fail: {}", tcAddress, e.getMessage());
+                throw new RetryableException(e.getMessage(), e);
+            }
+            break;
+        }
+        return false;
+    }
+
+    private static boolean watchHttp2(String clusterName) throws RetryableException {
+        Map<String, Long> groupTerms = METADATA.getClusterTerm(clusterName);
+        if (CollectionUtils.isEmpty(groupTerms)) {
+            return false;
+        }

Review Comment:
   The newly introduced HTTP/2 watch logic isn’t directly exercised by unit tests in this module (e.g., no test that stubs `HttpClientUtil.watchPost(...)` and asserts watch creation/retry/close behavior). The added tests cover `supportsHttp2` and `shouldRefreshMetadata`, but `watchHttp2`/`ensureHttp2Watch` behavior itself remains unverified.



##########
discovery/seata-discovery-raft/src/main/java/org/apache/seata/discovery/registry/raft/RaftRegistryServiceImpl.java:
##########
@@ -203,21 +234,277 @@ protected static void startQueryMetadata() {
                             } catch (RetryableException e) {
                                 LOGGER.error(e.getMessage(), e);
                                 try {
-                                    Thread.sleep(1000);
+                                    Thread.sleep(RETRY_DELAY_MS);
                                 } catch (InterruptedException ignored) {
                                 }
                             }
                         }
+                        closeHttp2Watch();
                     });
                     Runtime.getRuntime().addShutdownHook(new Thread(() -> {
                         CLOSED.compareAndSet(false, true);
-                        REFRESH_METADATA_EXECUTOR.shutdown();
+                        closeHttp2Watch();
+                        if (REFRESH_METADATA_EXECUTOR != null) {
+                            REFRESH_METADATA_EXECUTOR.shutdown();
+                        }
                     }));
                 }
             }
         }
     }
 
+    private static boolean watch() throws RetryableException {
+        String clusterName = CURRENT_TRANSACTION_CLUSTER_NAME;
+        if (StringUtils.isBlank(clusterName)) {
+            return false;
+        }
+
+        WatchProtocol targetProtocol = resolveWatchProtocol(clusterName);
+        switchWatchProtocolIfNecessary(targetProtocol);
+
+        if (targetProtocol == WatchProtocol.HTTP2) {
+            return watchHttp2(clusterName);
+        }
+        return watchHttp1(clusterName);
+    }
+
+    private static void switchWatchProtocolIfNecessary(WatchProtocol targetProtocol) {
+        if (CURRENT_WATCH_PROTOCOL == targetProtocol) {
+            return;
+        }
+
+        LOGGER.info("Switching raft watch protocol from {} to {}", CURRENT_WATCH_PROTOCOL, targetProtocol);
+        if (targetProtocol == WatchProtocol.HTTP1) {
+            closeHttp2Watch();
+        }
+        CURRENT_WATCH_PROTOCOL = targetProtocol;
+    }
+
+    private static WatchProtocol resolveWatchProtocol(String clusterName) {
+        if (StringUtils.isBlank(clusterName)) {
+            return WatchProtocol.HTTP1;
+        }
+
+        Set<String> groups = METADATA.groups(clusterName);
+        if (CollectionUtils.isEmpty(groups)) {
+            return WatchProtocol.HTTP1;
+        }
+
+        boolean hasNode = false;
+        for (String group : groups) {
+            List<Node> nodes = METADATA.getNodes(clusterName, group);
+            if (CollectionUtils.isEmpty(nodes)) {
+                continue;
+            }
+            hasNode = true;
+            if (!isClusterHttp2Enabled(clusterName, group)) {
+                return WatchProtocol.HTTP1;
+            }
+        }
+
+        return hasNode ? WatchProtocol.HTTP2 : WatchProtocol.HTTP1;
+    }
+
+    private static boolean watchHttp1(String clusterName) throws RetryableException {
+        Map<String, String> header = new HashMap<>();
+        header.put(HTTP.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.getMimeType());
+        Map<String, String> param = new HashMap<>();
+        Map<String, Long> groupTerms = METADATA.getClusterTerm(clusterName);
+        groupTerms.forEach((k, v) -> param.put(k, String.valueOf(v)));
+        for (String group : groupTerms.keySet()) {
+            String tcAddress = queryHttpAddress(clusterName, group);
+            if (StringUtils.isBlank(tcAddress)) {
+                return false;
+            }
+            if (isTokenExpired()) {
+                refreshToken(tcAddress);
+            }
+            if (StringUtils.isNotBlank(jwtToken)) {
+                header.put(AUTHORIZATION_HEADER, jwtToken);
+            }
+            try (Response response = HttpClientUtil.doPost(
+                    "http://" + tcAddress + "/metadata/v1/watch", param, header, (int) WATCH_TIMEOUT_MS)) {
+                if (response != null) {
+                    int statusCode = response.code();
+                    if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
+                        if (StringUtils.isNotBlank(USERNAME) && StringUtils.isNotBlank(PASSWORD)) {
+                            throw new RetryableException("Authentication failed!");
+                        } else {
+                            throw new AuthenticationFailedException(
+                                    "Authentication failed! you should configure the correct username and password.");
+                        }
+                    }
+                    return statusCode == HttpStatus.SC_OK;
+                }
+            } catch (IOException e) {
+                LOGGER.error("watch cluster node: {}, fail: {}", tcAddress, e.getMessage());
+                throw new RetryableException(e.getMessage(), e);
+            }
+            break;
+        }
+        return false;
+    }
+
+    private static boolean watchHttp2(String clusterName) throws RetryableException {
+        Map<String, Long> groupTerms = METADATA.getClusterTerm(clusterName);
+        if (CollectionUtils.isEmpty(groupTerms)) {
+            return false;
+        }
+
+        String group = groupTerms.keySet().iterator().next();

Review Comment:
   `watchHttp2` picks an arbitrary group via `groupTerms.keySet().iterator().next()`. With a `ConcurrentHashMap`, iteration order is not guaranteed, so when multiple groups exist this can flip between groups across iterations and cause unnecessary watch teardown/recreation (because `ensureHttp2Watch` caches by `HTTP2_WATCH_GROUP`). Consider choosing a deterministic group (e.g., sort keys and pick the first, or prefer the configured/default group) or key the watch cache by address+groups instead of a single group name.
   ```suggestion
           List<String> groups = new ArrayList<>(groupTerms.keySet());
           Collections.sort(groups);
           String group = groups.get(0);
   ```



##########
discovery/seata-discovery-raft/src/main/java/org/apache/seata/discovery/registry/raft/RaftRegistryServiceImpl.java:
##########
@@ -64,8 +69,8 @@
 
 /**
  * The type File registry service.
- *
  */
+@SuppressWarnings("ALL")

Review Comment:
   `@SuppressWarnings("ALL")` on the whole class suppresses all compiler warnings (including ones that could indicate real problems) and makes future maintenance harder. Prefer removing it and, if needed, suppress only the specific warning(s) at the narrowest scope (e.g., on the single unchecked cast in `selectExternalEndpoint`).
   ```suggestion
   
   ```



-- 
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: notifications-unsubscribe@seata.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@seata.apache.org
For additional commands, e-mail: notifications-help@seata.apache.org