repo stringclasses 1k
values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 6
values | commit_sha stringclasses 1k
values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/test/TestRunner.java | dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/test/TestRunner.java | /*
* 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.rpc.protocol.tri.test;
import java.util.List;
public interface TestRunner {
TestResponse run(TestRequest request);
<T> T run(TestRequest request, Class<T> type);
<T> T get(TestRequest request, Class<T> type);
String get(TestRequest request);
<T> T get(String path, Class<T> type);
<T> List<T> gets(String path, Class<T> type);
String get(String path);
List<String> gets(String path);
<T> T post(TestRequest request, Class<T> type);
String post(TestRequest request);
<T> T post(String path, Object body, Class<T> type);
<T> List<T> posts(String path, Object body, Class<T> type);
String post(String path, Object body);
List<String> posts(String path, Object body);
<T> T put(TestRequest request, Class<T> type);
String put(TestRequest request);
<T> T put(String path, Object body, Class<T> type);
String put(String path, Object body);
<T> T patch(TestRequest request, Class<T> type);
String patch(TestRequest request);
<T> T patch(String path, Object body, Class<T> type);
String patch(String path, Object body);
<T> T delete(TestRequest request, Class<T> type);
String delete(TestRequest request);
<T> T delete(String path, Class<T> type);
String delete(String path);
void destroy();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/test/TestRequest.java | dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/test/TestRequest.java | /*
* 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.rpc.protocol.tri.test;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.remoting.http12.HttpHeaderNames;
import org.apache.dubbo.remoting.http12.HttpHeaders;
import org.apache.dubbo.remoting.http12.HttpMethods;
import org.apache.dubbo.remoting.http12.h2.Http2Header;
import org.apache.dubbo.remoting.http12.h2.Http2MetadataFrame;
import org.apache.dubbo.remoting.http12.message.MediaType;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import io.netty.handler.codec.http2.Http2Headers.PseudoHeaderName;
@SuppressWarnings("UnusedReturnValue")
public class TestRequest {
private final HttpHeaders headers = HttpHeaders.create();
private final Map<String, String> cookies = new LinkedHashMap<>();
private final Map<String, Object> params = new LinkedHashMap<>();
private final Map<String, String> providerParams = new LinkedHashMap<>();
private List<Object> bodies;
public TestRequest(HttpMethods method, String path) {
setMethod(method);
setPath(path);
}
public TestRequest(String path) {
setPath(path);
}
public TestRequest() {}
public String getPath() {
return headers.getFirst(PseudoHeaderName.PATH.value());
}
public TestRequest setPath(String path) {
headers.set(PseudoHeaderName.PATH.value(), path);
return this;
}
public String getMethod() {
return headers.getFirst(PseudoHeaderName.METHOD.value());
}
public TestRequest setMethod(String method) {
headers.set(PseudoHeaderName.METHOD.value(), method);
return this;
}
public TestRequest setMethod(HttpMethods method) {
return setMethod(method.name());
}
public String getContentType() {
return headers.getFirst(HttpHeaderNames.CONTENT_TYPE.getKey());
}
public TestRequest setContentType(String contentType) {
if (StringUtils.isNotEmpty(contentType)) {
headers.set(HttpHeaderNames.CONTENT_TYPE.getKey(), contentType);
}
return this;
}
public TestRequest setContentType(MediaType mediaType) {
return setContentType(mediaType.getName());
}
public TestRequest setContentType(MediaType mediaType, String charset) {
return setContentType(mediaType.getName() + "; charset=" + charset);
}
public TestRequest setContentType(MediaType mediaType, Charset charset) {
return setContentType(mediaType.getName() + "; charset=" + charset.name());
}
public TestRequest setAccept(String accept) {
if (StringUtils.isNotEmpty(accept)) {
headers.set(HttpHeaderNames.ACCEPT.getKey(), accept);
}
return this;
}
public TestRequest setAccept(MediaType mediaType) {
return setAccept(mediaType.getName());
}
public TestRequest setHeader(String name, Object value) {
if (value != null) {
headers.set(name, value.toString());
}
return this;
}
@SuppressWarnings("unchecked")
public TestRequest setHeaders(Map<String, ?> headers) {
for (Map.Entry<String, ?> entry : headers.entrySet()) {
Object value = entry.getValue();
if (value instanceof List) {
List<String> items = new ArrayList<>();
for (Object obj : (List<Object>) value) {
if (obj != null) {
items.add(obj.toString());
}
}
this.headers.add(entry.getKey(), items);
} else if (value instanceof Object[]) {
List<String> items = new ArrayList<>();
for (Object obj : (Object[]) value) {
if (obj != null) {
items.add(obj.toString());
}
}
this.headers.add(entry.getKey(), items);
} else if (value != null) {
this.headers.set(entry.getKey(), value.toString());
}
}
return this;
}
public TestRequest setCookie(String name, String value) {
cookies.put(name, value);
return this;
}
public TestRequest setCookies(Map<String, String> cookies) {
this.cookies.putAll(cookies);
return this;
}
public Map<String, String> getCookies() {
return cookies;
}
public TestRequest param(String name, Object value) {
params.put(name, value);
return this;
}
public TestRequest setParams(Map<String, ?> params) {
this.params.putAll(params);
return this;
}
public Map<String, Object> getParams() {
return params;
}
public TestRequest setProviderParam(String name, String value) {
providerParams.put(name, value);
return this;
}
public TestRequest setProviderParams(Map<String, String> params) {
providerParams.putAll(params);
return this;
}
public Map<String, String> getProviderParams() {
return providerParams;
}
public TestRequest setBody(Object body) {
List<Object> bodies = this.bodies;
if (bodies == null) {
bodies = new ArrayList<>();
this.bodies = bodies;
}
bodies.add(body);
return this;
}
public List<Object> getBodies() {
return bodies;
}
public TestRequest post(Object body) {
setMethod(HttpMethods.POST);
setBody(body);
return this;
}
public TestRequest post() {
setMethod(HttpMethods.POST);
return this;
}
public Http2Header toMetadata() {
return new Http2MetadataFrame(headers, !HttpMethods.supportBody(getMethod()));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/compressor/GzipTest.java | dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/compressor/GzipTest.java | /*
* 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.rpc.protocol.tri.compressor;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
class GzipTest {
private static final String TEST_STR;
static {
StringBuilder builder = new StringBuilder();
int charNum = 1000000;
for (int i = 0; i < charNum; i++) {
builder.append("a");
}
TEST_STR = builder.toString();
}
@ValueSource(strings = {"gzip"})
@ParameterizedTest
void compression(String compressorName) {
Compressor compressor = ApplicationModel.defaultModel()
.getDefaultModule()
.getExtensionLoader(Compressor.class)
.getExtension(compressorName);
String loadByStatic =
Compressor.getCompressor(new FrameworkModel(), compressorName).getMessageEncoding();
Assertions.assertEquals(loadByStatic, compressor.getMessageEncoding());
byte[] compressedByteArr = compressor.compress(TEST_STR.getBytes());
DeCompressor deCompressor = ApplicationModel.defaultModel()
.getDefaultModule()
.getExtensionLoader(DeCompressor.class)
.getExtension(compressorName);
byte[] decompressedByteArr = deCompressor.decompress(compressedByteArr);
Assertions.assertEquals(new String(decompressedByteArr), TEST_STR);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/compressor/IdentityTest.java | dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/compressor/IdentityTest.java | /*
* 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.rpc.protocol.tri.compressor;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class IdentityTest {
@Test
void getMessageEncoding() {
Assertions.assertEquals("identity", Identity.IDENTITY.getMessageEncoding());
}
@Test
void compress() {
byte[] input = new byte[] {1, 2, 3, 4, 5};
final byte[] compressed = Identity.IDENTITY.compress(input);
Assertions.assertEquals(input, compressed);
}
@Test
void decompress() {
byte[] input = new byte[] {1, 2, 3, 4, 5};
final byte[] decompressed = Identity.IDENTITY.decompress(input);
Assertions.assertEquals(input, decompressed);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/compressor/Bzip2Test.java | dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/compressor/Bzip2Test.java | /*
* 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.rpc.protocol.tri.compressor;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
/**
* test for Bzip2
*/
class Bzip2Test {
private static final String TEST_STR;
static {
StringBuilder builder = new StringBuilder();
int charNum = 1000000;
for (int i = 0; i < charNum; i++) {
builder.append("a");
}
TEST_STR = builder.toString();
}
@ValueSource(strings = {"bzip2"})
@ParameterizedTest
void compression(String compressorName) {
Compressor compressor = ApplicationModel.defaultModel()
.getDefaultModule()
.getExtensionLoader(Compressor.class)
.getExtension(compressorName);
String loadByStatic =
Compressor.getCompressor(new FrameworkModel(), compressorName).getMessageEncoding();
Assertions.assertEquals(loadByStatic, compressor.getMessageEncoding());
byte[] compressedByteArr = compressor.compress(TEST_STR.getBytes());
DeCompressor deCompressor = ApplicationModel.defaultModel()
.getDefaultModule()
.getExtensionLoader(DeCompressor.class)
.getExtension(compressorName);
byte[] decompressedByteArr = deCompressor.decompress(compressedByteArr);
Assertions.assertEquals(new String(decompressedByteArr), TEST_STR);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/compressor/SnappyTest.java | dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/compressor/SnappyTest.java | /*
* 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.rpc.protocol.tri.compressor;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
/**
* test for snappy
*/
class SnappyTest {
private static final String TEST_STR;
static {
StringBuilder builder = new StringBuilder();
int charNum = 1000000;
for (int i = 0; i < charNum; i++) {
builder.append("a");
}
TEST_STR = builder.toString();
}
@ValueSource(strings = {"snappy"})
@ParameterizedTest
void compression(String compressorName) {
Compressor compressor = ApplicationModel.defaultModel()
.getDefaultModule()
.getExtensionLoader(Compressor.class)
.getExtension(compressorName);
String loadByStatic =
Compressor.getCompressor(new FrameworkModel(), compressorName).getMessageEncoding();
Assertions.assertEquals(loadByStatic, compressor.getMessageEncoding());
byte[] compressedByteArr = compressor.compress(TEST_STR.getBytes());
DeCompressor deCompressor = ApplicationModel.defaultModel()
.getDefaultModule()
.getExtensionLoader(DeCompressor.class)
.getExtension(compressorName);
byte[] decompressedByteArr = deCompressor.decompress(compressedByteArr);
Assertions.assertEquals(new String(decompressedByteArr), TEST_STR);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/frame/TriDecoderTest.java | dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/frame/TriDecoderTest.java | /*
* 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.rpc.protocol.tri.frame;
import org.apache.dubbo.rpc.protocol.tri.compressor.DeCompressor;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class TriDecoderTest {
@Test
void decode() {
final RecordListener listener = new RecordListener();
TriDecoder decoder = new TriDecoder(DeCompressor.NONE, listener);
final ByteBuf buf = Unpooled.buffer();
buf.writeByte(0);
buf.writeInt(1);
buf.writeByte(2);
decoder.deframe(buf);
final ByteBuf buf2 = Unpooled.buffer();
buf2.writeByte(0);
buf2.writeInt(2);
buf2.writeByte(2);
buf2.writeByte(3);
decoder.deframe(buf2);
Assertions.assertEquals(0, listener.dataCount);
decoder.request(1);
Assertions.assertEquals(1, listener.dataCount);
Assertions.assertEquals(1, listener.lastData.length);
decoder.request(1);
Assertions.assertEquals(2, listener.dataCount);
Assertions.assertEquals(2, listener.lastData.length);
decoder.close();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/frame/RecordListener.java | dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/frame/RecordListener.java | /*
* 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.rpc.protocol.tri.frame;
public class RecordListener implements TriDecoder.Listener {
byte[] lastData;
int dataCount;
boolean close;
@Override
public void onRawMessage(byte[] data) {
dataCount += 1;
lastData = data;
}
@Override
public void close() {
close = true;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/GeneralTypeConverterTest.java | dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/GeneralTypeConverterTest.java | /*
* 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.rpc.protocol.tri.rest;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.protocol.tri.rest.argument.GeneralTypeConverter;
import org.apache.dubbo.rpc.protocol.tri.rest.util.TypeUtils;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class GeneralTypeConverterTest {
private static final Logger logger = LoggerFactory.getLogger(GeneralTypeConverterTest.class);
public List<? extends Number>[] items;
@Test
void convert() throws NoSuchFieldException {
GeneralTypeConverter smartConverter = new GeneralTypeConverter(FrameworkModel.defaultModel());
smartConverter.convert(
"23,56", GeneralTypeConverterTest.class.getField("items").getGenericType());
}
@Test
void convert1() {
Object convert = JsonUtils.toJavaObject("[1,\"aa\"]", List.class);
Assertions.assertEquals(2, ((List) convert).size());
}
@Test
void convert2() throws NoSuchFieldException {
Class<?> type = TypeUtils.getActualType(
GeneralTypeConverterTest.class.getField("items").getGenericType());
logger.info(String.valueOf(type));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/RequestMappingRegisterTest.java | dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/RequestMappingRegisterTest.java | /*
* 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.rpc.protocol.tri.rest.mapping;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.ClassUtils;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Protocol;
import org.apache.dubbo.rpc.ProxyFactory;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ModuleServiceRepository;
import org.apache.dubbo.rpc.model.ProviderModel;
import org.apache.dubbo.rpc.model.ServiceDescriptor;
import org.apache.dubbo.rpc.model.ServiceMetadata;
import org.apache.dubbo.rpc.protocol.tri.TripleProtocol;
import org.apache.dubbo.rpc.protocol.tri.support.IGreeter;
import org.apache.dubbo.rpc.protocol.tri.support.IGreeterImpl;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* Tests for the RequestMapping registration process.
*/
public class RequestMappingRegisterTest {
ApplicationModel applicationModel = ApplicationModel.defaultModel();
Invoker<IGreeter> invoker = null;
/**
* Setup method, initializes the testing environment.
* Registers a service provider and creates an Invoker instance for subsequent tests.
*/
@BeforeEach
public void setup() {
// Initialize the service implementation
IGreeter serviceImpl = new IGreeterImpl();
// Select an available port
int availablePort = NetUtils.getAvailablePort();
// Construct the provider's URL
URL providerUrl = URL.valueOf("http://127.0.0.1:" + availablePort + "/" + IGreeter.class.getName());
// Register the service
ModuleServiceRepository serviceRepository =
applicationModel.getDefaultModule().getServiceRepository();
ServiceDescriptor serviceDescriptor = serviceRepository.registerService(IGreeter.class);
// Construct and register the provider model
ProviderModel providerModel = new ProviderModel(
providerUrl.getServiceKey(),
serviceImpl,
serviceDescriptor,
new ServiceMetadata(),
ClassUtils.getClassLoader(IGreeter.class));
serviceRepository.registerProvider(providerModel);
providerUrl = providerUrl.setServiceModel(providerModel);
// Initialize the protocol and proxy factory
Protocol protocol = new TripleProtocol(providerUrl.getOrDefaultFrameworkModel());
ProxyFactory proxyFactory =
applicationModel.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension();
// Create and export the Invoker
invoker = proxyFactory.getInvoker(serviceImpl, IGreeter.class, providerUrl);
protocol.export(invoker);
}
/**
* Tests whether the service lookup mechanism is functioning properly.
* Ensures that the DefaultRequestMappingRegistry instance can be obtained.
*/
@Test
public void testServiceLookup() {
// Obtain the DefaultRequestMappingRegistry instance
DefaultRequestMappingRegistry registry =
applicationModel.getFrameworkModel().getBeanFactory().getBean(DefaultRequestMappingRegistry.class);
assertNotNull(registry, "The DefaultRequestMappingRegistry should not be null.");
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/service/Book.java | dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/service/Book.java | /*
* 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.rpc.protocol.tri.rest.service;
import java.util.Date;
import java.util.Objects;
public class Book {
private String name;
private int price;
private Date publishDate;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public Date getPublishDate() {
return publishDate;
}
public void setPublishDate(Date publishDate) {
this.publishDate = publishDate;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o instanceof Book) {
Book book = (Book) o;
return price == book.price
&& Objects.equals(name, book.name)
&& Objects.equals(publishDate, book.publishDate);
}
return false;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/service/DemoServiceImpl.java | dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/service/DemoServiceImpl.java | /*
* 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.rpc.protocol.tri.rest.service;
import org.apache.dubbo.common.stream.StreamObserver;
import org.apache.dubbo.common.utils.Assert;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.remoting.http12.rest.Mapping;
import org.apache.dubbo.rpc.protocol.tri.rest.service.User.Group;
import org.apache.dubbo.rpc.protocol.tri.rest.service.User.UserEx;
import java.util.List;
import java.util.Map;
import io.grpc.health.v1.HealthCheckRequest;
import io.grpc.health.v1.HealthCheckResponse;
import io.grpc.health.v1.HealthCheckResponse.ServingStatus;
public class DemoServiceImpl implements DemoService {
@Override
public String hello(String name) {
return "hello " + name;
}
@Override
public String argTest(String name, int age) {
return name + " is " + age + " years old";
}
@Override
public Book beanArgTest(Book book, Integer quote) {
if (book == null) {
book = new Book();
}
if (quote != null) {
book.setPrice(quote);
}
return book;
}
@Override
public Book beanArgTest2(Book book) {
return beanArgTest(book, null);
}
@Override
public UserEx advanceBeanArgTest(UserEx user) {
return user;
}
@Override
public List<Integer> listArgBodyTest(List<Integer> list, int age) {
Assert.assertTrue(age == 2, "age must be 2");
return list;
}
@Override
public List<Integer> listArgBodyTest2(List<Integer> list, int age) {
return listArgBodyTest(list, age);
}
@Override
public Map<Integer, List<Long>> mapArgBodyTest(Map<Integer, List<Long>> map, int age) {
Assert.assertTrue(age == 2, "age must be 2");
return map;
}
@Override
public Map<Integer, List<Long>> mapArgBodyTest2(Map<Integer, List<Long>> map, int age) {
return mapArgBodyTest(map, age);
}
@Override
public List<Group> beanBodyTest(List<Group> groups, int age) {
Assert.assertTrue(age == 2, "age must be 2");
return groups;
}
@Override
public List<Group> beanBodyTest2(List<Group> groups, int age) {
return beanBodyTest(groups, age);
}
@Override
public Book buy(Book book) {
return book;
}
@Override
public Book buy(Book book, int count) {
return book;
}
@Override
public String say(String name, Long count) {
return "2";
}
@Override
public String say(String name) {
return "1";
}
@Mapping
public String noInterface() {
return "ok";
}
public String noInterfaceAndMapping() {
return "ok";
}
@Override
public String argNameTest(String name1) {
return name1;
}
@Override
public void pbServerStream(HealthCheckRequest request, StreamObserver<HealthCheckResponse> responseObserver) {
String service = request.getService();
if (StringUtils.isNotEmpty(service)) {
int count = Integer.parseInt(service);
for (int i = 0; i < count; i++) {
responseObserver.onNext(HealthCheckResponse.newBuilder()
.setStatus(ServingStatus.SERVING)
.build());
}
}
responseObserver.onCompleted();
}
@Override
public String produceTest(String name) {
return name;
}
@Override
public String mismatchTest(String name) {
return name;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/service/DemoService.java | dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/service/DemoService.java | /*
* 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.rpc.protocol.tri.rest.service;
import org.apache.dubbo.common.stream.StreamObserver;
import org.apache.dubbo.remoting.http12.HttpMethods;
import org.apache.dubbo.remoting.http12.rest.Mapping;
import org.apache.dubbo.remoting.http12.rest.Param;
import org.apache.dubbo.rpc.protocol.tri.rest.service.User.Group;
import org.apache.dubbo.rpc.protocol.tri.rest.service.User.UserEx;
import java.util.List;
import java.util.Map;
import io.grpc.health.v1.HealthCheckRequest;
import io.grpc.health.v1.HealthCheckResponse;
import static org.apache.dubbo.remoting.http12.rest.ParamType.Body;
@Mapping("/")
public interface DemoService {
String hello(String name);
String argTest(String name, int age);
Book beanArgTest(Book book, Integer quote);
Book beanArgTest2(Book book);
@Mapping("/bean")
UserEx advanceBeanArgTest(UserEx user);
List<Integer> listArgBodyTest(@Param(type = Body) List<Integer> list, int age);
List<Integer> listArgBodyTest2(List<Integer> list, int age);
Map<Integer, List<Long>> mapArgBodyTest(@Param(type = Body) Map<Integer, List<Long>> map, int age);
Map<Integer, List<Long>> mapArgBodyTest2(Map<Integer, List<Long>> map, int age);
List<Group> beanBodyTest(@Param(type = Body) List<Group> groups, int age);
List<Group> beanBodyTest2(List<Group> groups, int age);
Book buy(Book book);
@Mapping("/buy2")
Book buy(Book book, int count);
String say(String name, Long count);
String say(String name);
String argNameTest(String name);
void pbServerStream(HealthCheckRequest request, StreamObserver<HealthCheckResponse> responseObserver);
@Mapping(produces = "text/plain")
String produceTest(String name);
@Mapping(method = HttpMethods.POST, consumes = "text/plain", produces = "text/plain", params = "name=world")
String mismatchTest(String name);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/service/User.java | dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/service/User.java | /*
* 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.rpc.protocol.tri.rest.service;
import org.apache.dubbo.remoting.http12.rest.Param;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class User {
private Long id;
private String name;
private Group group;
private long[] ids;
private List<Integer> scores;
private List<Tag> tags;
private Tag[] tagsA;
private List<Tag> tagsB = new ArrayList<>();
private Tag[] tagsC = new Tag[] {new Tag("a", "b")};
private List<Map<String, Group>> groupMaps;
private Map<String, String> features;
private Map<String, Tag> tagMap;
private Map<String, Tag> tagMapA = new HashMap<>();
private Map<Integer, Tag> tagMapB;
private Map<String, List<Group>> groupsMap;
public User() {
tagsB.add(new Tag("a", "b"));
tagMapA.put("a", new Tag("a", "b"));
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Group getGroup() {
return group;
}
public void setGroup(Group group) {
this.group = group;
}
public long[] getIds() {
return ids;
}
public void setIds(long[] ids) {
this.ids = ids;
}
public List<Integer> getScores() {
return scores;
}
public void setScores(List<Integer> scores) {
this.scores = scores;
}
public List<Tag> getTags() {
return tags;
}
public void setTags(List<Tag> tags) {
this.tags = tags;
}
public Tag[] getTagsA() {
return tagsA;
}
public void setTagsA(Tag[] tagsA) {
this.tagsA = tagsA;
}
public List<Tag> getTagsB() {
return tagsB;
}
public void setTagsB(List<Tag> tagsB) {
this.tagsB = tagsB;
}
public Tag[] getTagsC() {
return tagsC;
}
public void setTagsC(Tag[] tagsC) {
this.tagsC = tagsC;
}
public List<Map<String, Group>> getGroupMaps() {
return groupMaps;
}
public void setGroupMaps(List<Map<String, Group>> groupMaps) {
this.groupMaps = groupMaps;
}
public Map<String, String> getFeatures() {
return features;
}
public void setFeatures(Map<String, String> features) {
this.features = features;
}
public Map<String, Tag> getTagMap() {
return tagMap;
}
public void setTagMap(Map<String, Tag> tagMap) {
this.tagMap = tagMap;
}
public Map<String, Tag> getTagMapA() {
return tagMapA;
}
public void setTagMapA(Map<String, Tag> tagMapA) {
this.tagMapA = tagMapA;
}
public Map<Integer, Tag> getTagMapB() {
return tagMapB;
}
public void setTagMapB(Map<Integer, Tag> tagMapB) {
this.tagMapB = tagMapB;
}
public Map<String, List<Group>> getGroupsMap() {
return groupsMap;
}
public void setGroupsMap(Map<String, List<Group>> groupsMap) {
this.groupsMap = groupsMap;
}
public static class UserEx extends User {
private String email;
@Param(value = "p")
private String phone;
public UserEx(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
public static class Group {
private int id;
private String name;
private User owner;
private Group parent;
private List<Group> children;
private Map<String, String> features;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public User getOwner() {
return owner;
}
public void setOwner(User owner) {
this.owner = owner;
}
public Group getParent() {
return parent;
}
public void setParent(Group parent) {
this.parent = parent;
}
public List<Group> getChildren() {
return children;
}
public void setChildren(List<Group> children) {
this.children = children;
}
public Map<String, String> getFeatures() {
return features;
}
public void setFeatures(Map<String, String> features) {
this.features = features;
}
}
public static class Tag {
private String name;
private String value;
public Tag() {}
public Tag(String name, String value) {
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/filter/TestRestFilter.java | dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/filter/TestRestFilter.java | /*
* 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.rpc.protocol.tri.rest.filter;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.remoting.http12.HttpRequest;
import org.apache.dubbo.remoting.http12.HttpResponse;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.protocol.tri.rest.filter.RestFilter.Listener;
public class TestRestFilter implements RestFilter, Listener {
private static final Logger LOGGER = LoggerFactory.getLogger(TestRestFilter.class);
private final int priority;
private final String[] patterns;
public TestRestFilter() {
this(50);
}
public TestRestFilter(int priority, String... patterns) {
this.priority = priority;
this.patterns = patterns;
}
@Override
public int getPriority() {
return priority;
}
@Override
public String[] getPatterns() {
return patterns;
}
@Override
public void doFilter(HttpRequest request, HttpResponse response, FilterChain chain) throws Exception {
LOGGER.info("{} path '{}' doFilter", request.path(), this);
chain.doFilter(request, response);
}
@Override
public void onResponse(Result result, HttpRequest request, HttpResponse response) throws Exception {
LOGGER.info("{} path '{}' onResponse", request.path(), this);
}
@Override
public void onError(Throwable t, HttpRequest request, HttpResponse response) throws Exception {
LOGGER.info("{} path '{}' onError", request.path(), this);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/filter/TestRestFilterFactory.java | dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/filter/TestRestFilterFactory.java | /*
* 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.rpc.protocol.tri.rest.filter;
import org.apache.dubbo.common.extension.Activate;
import java.util.function.Supplier;
@Activate
public class TestRestFilterFactory implements RestExtension, Supplier<RestFilter> {
@Override
public RestFilter get() {
return new TestRestFilter(100, "/filter/*", "/*.filter", "!/filter/one");
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/cors/CorsHeaderFilterTest.java | dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/cors/CorsHeaderFilterTest.java | /*
* 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.rpc.protocol.tri.rest.cors;
import org.apache.dubbo.remoting.http12.HttpConstants;
import org.apache.dubbo.remoting.http12.HttpMethods;
import org.apache.dubbo.remoting.http12.HttpRequest;
import org.apache.dubbo.remoting.http12.HttpResponse;
import org.apache.dubbo.remoting.http12.HttpStatus;
import org.apache.dubbo.remoting.http12.exception.HttpResultPayloadException;
import org.apache.dubbo.remoting.http12.message.DefaultHttpResponse;
import org.apache.dubbo.rpc.protocol.tri.rest.RestConstants;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.RequestMapping;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.CorsMeta;
import java.util.Arrays;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
class CorsHeaderFilterTest {
private HttpRequest request;
private HttpResponse response;
private MockCorsHeaderFilter processor;
private RequestMapping build;
static class MockCorsHeaderFilter extends CorsHeaderFilter {
public void process(HttpRequest request, HttpResponse response) {
invoke(null, null, request, response);
}
public void preLightProcess(HttpRequest request, HttpResponse response, int code) {
try {
process(request, response);
Assertions.fail();
} catch (HttpResultPayloadException e) {
Assertions.assertEquals(code, e.getStatusCode());
} catch (Exception e) {
Assertions.fail();
}
}
}
private CorsMeta defaultCorsMeta() {
return CorsMeta.builder().maxAge(1000L).build();
}
@BeforeEach
public void setup() {
build = Mockito.mock(RequestMapping.class);
request = Mockito.mock(HttpRequest.class);
Mockito.when(request.attribute(RestConstants.MAPPING_ATTRIBUTE)).thenReturn(build);
Mockito.when(request.uri()).thenReturn("/test.html");
Mockito.when(request.serverName()).thenReturn("domain1.example");
Mockito.when(request.scheme()).thenReturn(HttpConstants.HTTP);
Mockito.when(request.serverPort()).thenReturn(80);
Mockito.when(request.remoteHost()).thenReturn("127.0.0.1");
response = new DefaultHttpResponse();
response.setStatus(HttpStatus.OK.getCode());
processor = new MockCorsHeaderFilter();
}
@Test
void requestWithoutOriginHeader() {
Mockito.when(request.method()).thenReturn(HttpMethods.GET.name());
Mockito.when(build.getCors()).thenReturn(CorsMeta.builder().build());
Mockito.when(build.getCors()).thenReturn(defaultCorsMeta());
processor.process(request, response);
Assertions.assertFalse(response.hasHeader(CorsHeaderFilter.ACCESS_CONTROL_ALLOW_ORIGIN));
Assertions.assertTrue(response.header(CorsHeaderFilter.VARY).contains(CorsHeaderFilter.ORIGIN));
Assertions.assertTrue(
response.header(CorsHeaderFilter.VARY).contains(CorsHeaderFilter.ACCESS_CONTROL_REQUEST_METHOD));
Assertions.assertTrue(
response.header(CorsHeaderFilter.VARY).contains(CorsHeaderFilter.ACCESS_CONTROL_REQUEST_HEADERS));
Assertions.assertEquals(HttpStatus.OK.getCode(), response.status());
}
@Test
void sameOriginRequest() {
Mockito.when(request.method()).thenReturn(HttpMethods.GET.name());
Mockito.when(request.header(CorsHeaderFilter.ORIGIN)).thenReturn("http://domain1.example");
Mockito.when(build.getCors()).thenReturn(defaultCorsMeta());
processor.process(request, response);
Assertions.assertFalse(response.hasHeader(CorsHeaderFilter.ACCESS_CONTROL_ALLOW_ORIGIN));
Assertions.assertTrue(response.header(CorsHeaderFilter.VARY).contains(CorsHeaderFilter.ORIGIN));
Assertions.assertTrue(
response.header(CorsHeaderFilter.VARY).contains(CorsHeaderFilter.ACCESS_CONTROL_REQUEST_METHOD));
Assertions.assertTrue(
response.header(CorsHeaderFilter.VARY).contains(CorsHeaderFilter.ACCESS_CONTROL_REQUEST_HEADERS));
Assertions.assertEquals(HttpStatus.OK.getCode(), response.status());
}
@Test
void actualRequestWithOriginHeader() {
Mockito.when(request.method()).thenReturn(HttpMethods.GET.name());
Mockito.when(request.header(CorsHeaderFilter.ORIGIN)).thenReturn("https://domain2.com");
Mockito.when(build.getCors()).thenReturn(defaultCorsMeta());
Assertions.assertThrows(HttpResultPayloadException.class, () -> processor.process(request, response));
}
@Test
void actualRequestWithOriginHeaderAndNullConfig() {
Mockito.when(request.method()).thenReturn(HttpMethods.GET.name());
Mockito.when(request.header(CorsHeaderFilter.ORIGIN)).thenReturn("https://domain2.com");
Mockito.when(build.getCors()).thenReturn(null);
processor.process(request, response);
Assertions.assertFalse(response.hasHeader(CorsHeaderFilter.ACCESS_CONTROL_ALLOW_ORIGIN));
Assertions.assertEquals(HttpStatus.OK.getCode(), response.status());
}
@Test
void actualRequestWithOriginHeaderAndAllowedOrigin() {
Mockito.when(request.method()).thenReturn(HttpMethods.GET.name());
Mockito.when(request.header(CorsHeaderFilter.ORIGIN)).thenReturn("https://domain2.com");
Mockito.when(build.getCors()).thenReturn(CorsMeta.builder().build().applyDefault());
processor.process(request, response);
Assertions.assertTrue(response.hasHeader(CorsHeaderFilter.ACCESS_CONTROL_ALLOW_ORIGIN));
Assertions.assertEquals("*", response.header(CorsHeaderFilter.ACCESS_CONTROL_ALLOW_ORIGIN));
Assertions.assertFalse(response.hasHeader(CorsHeaderFilter.ACCESS_CONTROL_MAX_AGE));
Assertions.assertFalse(response.hasHeader(CorsHeaderFilter.ACCESS_CONTROL_EXPOSE_HEADERS));
Assertions.assertTrue(response.header(CorsHeaderFilter.VARY).contains(CorsHeaderFilter.ORIGIN));
Assertions.assertTrue(
response.header(CorsHeaderFilter.VARY).contains(CorsHeaderFilter.ACCESS_CONTROL_REQUEST_METHOD));
Assertions.assertTrue(
response.header(CorsHeaderFilter.VARY).contains(CorsHeaderFilter.ACCESS_CONTROL_REQUEST_HEADERS));
Assertions.assertEquals(HttpStatus.OK.getCode(), response.status());
}
@Test
void actualRequestCaseInsensitiveOriginMatch() {
Mockito.when(request.method()).thenReturn(HttpMethods.GET.name());
Mockito.when(request.header(CorsHeaderFilter.ORIGIN)).thenReturn("https://domain2.com");
Mockito.when(build.getCors())
.thenReturn(CorsMeta.builder()
.allowedOrigins("https://DOMAIN2.com")
.build()
.applyDefault());
processor.process(request, response);
Assertions.assertEquals(HttpStatus.OK.getCode(), response.status());
Assertions.assertTrue(response.hasHeader(CorsHeaderFilter.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
void actualRequestTrailingSlashOriginMatch() {
Mockito.when(request.method()).thenReturn(HttpMethods.GET.name());
Mockito.when(request.header(CorsHeaderFilter.ORIGIN)).thenReturn("https://domain2.com");
Mockito.when(build.getCors())
.thenReturn(CorsMeta.builder()
.allowedOrigins("https://domain2.com/")
.build()
.applyDefault());
processor.process(request, response);
Assertions.assertEquals(HttpStatus.OK.getCode(), response.status());
Assertions.assertTrue(response.hasHeader(CorsHeaderFilter.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
void actualRequestExposedHeaders() {
Mockito.when(request.method()).thenReturn(HttpMethods.GET.name());
Mockito.when(request.header(CorsHeaderFilter.ORIGIN)).thenReturn("https://domain2.com");
Mockito.doReturn(CorsMeta.builder()
.allowedOrigins("https://domain2.com")
.exposedHeaders("header1", "header2")
.build()
.applyDefault())
.when(build)
.getCors();
processor.process(request, response);
Assertions.assertTrue(response.hasHeader(CorsHeaderFilter.ACCESS_CONTROL_ALLOW_ORIGIN));
Assertions.assertEquals("https://domain2.com", response.header(CorsHeaderFilter.ACCESS_CONTROL_ALLOW_ORIGIN));
Assertions.assertTrue(response.hasHeader(CorsHeaderFilter.ACCESS_CONTROL_EXPOSE_HEADERS));
Assertions.assertTrue(
response.header(CorsHeaderFilter.ACCESS_CONTROL_EXPOSE_HEADERS).contains("header1"));
Assertions.assertTrue(
response.header(CorsHeaderFilter.ACCESS_CONTROL_EXPOSE_HEADERS).contains("header2"));
Assertions.assertTrue(response.header(CorsHeaderFilter.VARY).contains(CorsHeaderFilter.ORIGIN));
Assertions.assertTrue(
response.header(CorsHeaderFilter.VARY).contains(CorsHeaderFilter.ACCESS_CONTROL_REQUEST_METHOD));
Assertions.assertTrue(
response.header(CorsHeaderFilter.VARY).contains(CorsHeaderFilter.ACCESS_CONTROL_REQUEST_HEADERS));
Assertions.assertEquals(HttpStatus.OK.getCode(), response.status());
}
@Test
void actualRequestCredentials() {
Mockito.when(request.method()).thenReturn(HttpMethods.GET.name());
Mockito.when(request.header(CorsHeaderFilter.ORIGIN)).thenReturn("https://domain2.com");
Mockito.doReturn(CorsMeta.builder()
.allowedOrigins("https://domain1.com", "https://domain2.com")
.allowCredentials(true)
.build()
.applyDefault())
.when(build)
.getCors();
processor.process(request, response);
Assertions.assertTrue(response.hasHeader(CorsHeaderFilter.ACCESS_CONTROL_ALLOW_ORIGIN));
Assertions.assertEquals("https://domain2.com", response.header(CorsHeaderFilter.ACCESS_CONTROL_ALLOW_ORIGIN));
Assertions.assertTrue(response.hasHeader(CorsHeaderFilter.ACCESS_CONTROL_ALLOW_CREDENTIALS));
Assertions.assertEquals("true", response.header(CorsHeaderFilter.ACCESS_CONTROL_ALLOW_CREDENTIALS));
Assertions.assertTrue(response.header(CorsHeaderFilter.VARY).contains(CorsHeaderFilter.ORIGIN));
Assertions.assertEquals(HttpStatus.OK.getCode(), response.status());
}
@Test
void actualRequestCredentialsWithWildcardOrigin() {
Mockito.when(request.method()).thenReturn(HttpMethods.GET.name());
Mockito.when(request.header(CorsHeaderFilter.ORIGIN)).thenReturn("https://domain2.com");
Mockito.doReturn(CorsMeta.builder()
.allowedOrigins("*")
.allowCredentials(true)
.build()
.applyDefault())
.when(build)
.getCors();
Assertions.assertThrows(IllegalArgumentException.class, () -> processor.process(request, response));
}
@Test
void preflightRequestWrongAllowedMethod() {
Mockito.when(request.method()).thenReturn(HttpMethods.OPTIONS.name());
Mockito.when(request.header(CorsHeaderFilter.ORIGIN)).thenReturn("https://domain2.com");
Mockito.when(request.header(CorsHeaderFilter.ACCESS_CONTROL_REQUEST_METHOD))
.thenReturn("DELETE");
Mockito.when(request.hasHeader(CorsHeaderFilter.ACCESS_CONTROL_REQUEST_METHOD))
.thenReturn(true);
Mockito.when(build.getCors())
.thenReturn(CorsMeta.builder().allowedOrigins("*").build());
processor.preLightProcess(request, response, HttpStatus.FORBIDDEN.getCode());
}
@Test
void preflightRequestMatchedAllowedMethod() {
Mockito.when(request.method()).thenReturn(HttpMethods.OPTIONS.name());
Mockito.when(request.header(CorsHeaderFilter.ORIGIN)).thenReturn("https://domain2.com");
Mockito.when(request.header(CorsHeaderFilter.ACCESS_CONTROL_REQUEST_METHOD))
.thenReturn("GET");
Mockito.when(request.hasHeader(CorsHeaderFilter.ACCESS_CONTROL_REQUEST_METHOD))
.thenReturn(true);
Mockito.when(build.getCors()).thenReturn(CorsMeta.builder().build().applyDefault());
processor.preLightProcess(request, response, HttpStatus.NO_CONTENT.getCode());
}
@Test
void preflightRequestTestWithOriginButWithoutOtherHeaders() {
Mockito.when(request.method()).thenReturn(HttpMethods.OPTIONS.name());
Mockito.when(request.header(CorsHeaderFilter.ORIGIN)).thenReturn("https://domain2.com");
Mockito.when(request.hasHeader(CorsHeaderFilter.ACCESS_CONTROL_REQUEST_METHOD))
.thenReturn(true);
Mockito.when(build.getCors()).thenReturn(defaultCorsMeta());
processor.preLightProcess(request, response, HttpStatus.FORBIDDEN.getCode());
}
@Test
void preflightRequestWithoutRequestMethod() {
Mockito.when(request.method()).thenReturn(HttpMethods.OPTIONS.name());
Mockito.when(request.header(CorsHeaderFilter.ORIGIN)).thenReturn("https://domain2.com");
Mockito.when(request.header(CorsHeaderFilter.ACCESS_CONTROL_REQUEST_HEADERS))
.thenReturn("Header1");
Mockito.when(request.hasHeader(CorsHeaderFilter.ACCESS_CONTROL_REQUEST_METHOD))
.thenReturn(true);
Mockito.when(build.getCors()).thenReturn(defaultCorsMeta());
processor.preLightProcess(request, response, HttpStatus.FORBIDDEN.getCode());
}
@Test
void preflightRequestWithRequestAndMethodHeaderButNoConfig() {
Mockito.when(request.method()).thenReturn(HttpMethods.OPTIONS.name());
Mockito.when(request.header(CorsHeaderFilter.ORIGIN)).thenReturn("https://domain2.com");
Mockito.when(request.header(CorsHeaderFilter.ACCESS_CONTROL_REQUEST_METHOD))
.thenReturn("GET");
Mockito.when(request.header(CorsHeaderFilter.ACCESS_CONTROL_REQUEST_HEADERS))
.thenReturn("Header1");
Mockito.when(request.hasHeader(CorsHeaderFilter.ACCESS_CONTROL_REQUEST_METHOD))
.thenReturn(true);
Mockito.when(build.getCors()).thenReturn(defaultCorsMeta());
processor.preLightProcess(request, response, HttpStatus.FORBIDDEN.getCode());
}
@Test
void preflightRequestValidRequestAndConfig() {
Mockito.when(request.method()).thenReturn(HttpMethods.OPTIONS.name());
Mockito.when(request.header(CorsHeaderFilter.ORIGIN)).thenReturn("https://domain2.com");
Mockito.when(request.header(CorsHeaderFilter.ACCESS_CONTROL_REQUEST_METHOD))
.thenReturn("GET");
Mockito.when(request.header(CorsHeaderFilter.ACCESS_CONTROL_REQUEST_HEADERS))
.thenReturn("Header1");
Mockito.when(request.hasHeader(CorsHeaderFilter.ACCESS_CONTROL_REQUEST_METHOD))
.thenReturn(true);
Mockito.when(build.getCors())
.thenReturn(CorsMeta.builder()
.allowedOrigins("*")
.allowedMethods("GET", "PUT")
.allowedHeaders("Header1", "Header2")
.build());
processor.preLightProcess(request, response, HttpStatus.NO_CONTENT.getCode());
}
@Test
void preflightRequestAllowedHeaders() {
Mockito.when(request.method()).thenReturn(HttpMethods.OPTIONS.name());
Mockito.when(request.header(CorsHeaderFilter.ORIGIN)).thenReturn("https://domain2.com");
Mockito.when(request.header(CorsHeaderFilter.ACCESS_CONTROL_REQUEST_METHOD))
.thenReturn("GET");
Mockito.when(request.hasHeader(CorsHeaderFilter.ACCESS_CONTROL_REQUEST_METHOD))
.thenReturn(true);
Mockito.doReturn(Arrays.asList("Header1", "Header2"))
.when(request)
.headerValues(CorsHeaderFilter.ACCESS_CONTROL_REQUEST_HEADERS);
Mockito.doReturn(CorsMeta.builder()
.allowedOrigins("https://domain2.com")
.allowedHeaders("Header1", "Header2")
.build()
.applyDefault())
.when(build)
.getCors();
processor.preLightProcess(request, response, HttpStatus.NO_CONTENT.getCode());
}
@Test
void preflightRequestAllowsAllHeaders() {
Mockito.when(request.method()).thenReturn(HttpMethods.OPTIONS.name());
Mockito.when(request.header(CorsHeaderFilter.ORIGIN)).thenReturn("https://domain2.com");
Mockito.when(request.header(CorsHeaderFilter.ACCESS_CONTROL_REQUEST_METHOD))
.thenReturn("GET");
Mockito.when(request.hasHeader(CorsHeaderFilter.ACCESS_CONTROL_REQUEST_METHOD))
.thenReturn(true);
Mockito.when(request.headerValues(CorsHeaderFilter.ACCESS_CONTROL_REQUEST_HEADERS))
.thenReturn(Arrays.asList("Header1", "Header2"));
Mockito.when(build.getCors())
.thenReturn(CorsMeta.builder()
.allowedOrigins("https://domain2.com")
.allowedHeaders("*")
.build()
.applyDefault());
processor.preLightProcess(request, response, HttpStatus.NO_CONTENT.getCode());
}
@Test
void preflightRequestWithEmptyHeaders() {
Mockito.when(request.method()).thenReturn(HttpMethods.OPTIONS.name());
Mockito.when(request.header(CorsHeaderFilter.ORIGIN)).thenReturn("https://domain2.com");
Mockito.when(request.header(CorsHeaderFilter.ACCESS_CONTROL_REQUEST_METHOD))
.thenReturn("GET");
Mockito.when(request.hasHeader(CorsHeaderFilter.ACCESS_CONTROL_REQUEST_METHOD))
.thenReturn(true);
Mockito.when(request.header(CorsHeaderFilter.ACCESS_CONTROL_REQUEST_HEADERS))
.thenReturn("");
Mockito.when(build.getCors())
.thenReturn(CorsMeta.builder()
.allowedOrigins("https://domain2.com")
.allowedHeaders("*")
.build()
.applyDefault());
processor.preLightProcess(request, response, HttpStatus.NO_CONTENT.getCode());
}
@Test
void preflightRequestWithNullConfig() {
Mockito.when(request.method()).thenReturn(HttpMethods.OPTIONS.name());
Mockito.when(request.header(CorsHeaderFilter.ORIGIN)).thenReturn("https://domain2.com");
Mockito.when(request.header(CorsHeaderFilter.ACCESS_CONTROL_REQUEST_METHOD))
.thenReturn("GET");
Mockito.when(build.getCors())
.thenReturn(CorsMeta.builder().allowedOrigins("*").build());
processor.preLightProcess(request, response, HttpStatus.FORBIDDEN.getCode());
}
@Test
void preflightRequestCredentials() {
Mockito.when(request.method()).thenReturn(HttpMethods.OPTIONS.name());
Mockito.when(request.header(CorsHeaderFilter.ORIGIN)).thenReturn("https://domain2.com");
Mockito.when(request.header(CorsHeaderFilter.ACCESS_CONTROL_REQUEST_METHOD))
.thenReturn("GET");
Mockito.doReturn(true).when(request).hasHeader(CorsHeaderFilter.ACCESS_CONTROL_REQUEST_METHOD);
Mockito.when(request.header(CorsHeaderFilter.ACCESS_CONTROL_REQUEST_HEADERS))
.thenReturn("Header1");
Mockito.doReturn(CorsMeta.builder()
.allowedOrigins("https://domain1.com", "https://domain2.com", "http://domain3.example")
.allowedHeaders("Header1")
.allowCredentials(true)
.build()
.applyDefault())
.when(build)
.getCors();
processor.preLightProcess(request, response, HttpStatus.NO_CONTENT.getCode());
}
@Test
void preventDuplicatedVaryHeaders() {
Mockito.when(request.method()).thenReturn(HttpMethods.GET.name());
response.setHeader(
CorsHeaderFilter.VARY,
CorsHeaderFilter.ORIGIN + "," + CorsHeaderFilter.ACCESS_CONTROL_REQUEST_METHOD + ","
+ CorsHeaderFilter.ACCESS_CONTROL_REQUEST_HEADERS);
processor.process(request, response);
Assertions.assertTrue(response.header(CorsHeaderFilter.VARY).contains(CorsHeaderFilter.ORIGIN));
Assertions.assertTrue(
response.header(CorsHeaderFilter.VARY).contains(CorsHeaderFilter.ACCESS_CONTROL_REQUEST_METHOD));
Assertions.assertTrue(
response.header(CorsHeaderFilter.VARY).contains(CorsHeaderFilter.ACCESS_CONTROL_REQUEST_HEADERS));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/transport/WriteQueueTest.java | dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/transport/WriteQueueTest.java | /*
* 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.rpc.protocol.tri.transport;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.TriRpcStatus;
import org.apache.dubbo.rpc.protocol.tri.command.CancelQueueCommand;
import org.apache.dubbo.rpc.protocol.tri.command.DataQueueCommand;
import org.apache.dubbo.rpc.protocol.tri.command.HeaderQueueCommand;
import org.apache.dubbo.rpc.protocol.tri.command.QueuedCommand;
import org.apache.dubbo.rpc.protocol.tri.command.TextDataQueueCommand;
import org.apache.dubbo.rpc.protocol.tri.stream.TripleStreamChannelFuture;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import io.netty.channel.Channel;
import io.netty.channel.ChannelPromise;
import io.netty.channel.DefaultEventLoop;
import io.netty.channel.EventLoop;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.http2.DefaultHttp2Headers;
import io.netty.handler.codec.http2.Http2Error;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.mockito.stubbing.Answer;
import static org.apache.dubbo.rpc.protocol.tri.transport.WriteQueue.DEQUE_CHUNK_SIZE;
/**
* {@link WriteQueue}
*/
class WriteQueueTest {
private final AtomicInteger writeMethodCalledTimes = new AtomicInteger(0);
private Channel channel;
@BeforeEach
public void init() {
channel = Mockito.mock(Channel.class);
Channel parent = Mockito.mock(Channel.class);
ChannelPromise promise = Mockito.mock(ChannelPromise.class);
EventLoop eventLoop = new DefaultEventLoop();
Mockito.when(parent.eventLoop()).thenReturn(eventLoop);
Mockito.when(channel.parent()).thenReturn(parent);
Mockito.when(channel.eventLoop()).thenReturn(eventLoop);
Mockito.when(channel.isActive()).thenReturn(true);
Mockito.when(channel.newPromise()).thenReturn(promise);
Mockito.when(channel.write(Mockito.any(), Mockito.any()))
.thenAnswer((Answer<ChannelPromise>) invocationOnMock -> {
writeMethodCalledTimes.incrementAndGet();
return promise;
});
writeMethodCalledTimes.set(0);
}
@Test
@Disabled
void test() throws Exception {
WriteQueue writeQueue = new WriteQueue();
EmbeddedChannel embeddedChannel = new EmbeddedChannel();
TripleStreamChannelFuture tripleStreamChannelFuture = new TripleStreamChannelFuture(embeddedChannel);
writeQueue.enqueue(HeaderQueueCommand.createHeaders(tripleStreamChannelFuture, new DefaultHttp2Headers())
.channel(channel));
writeQueue.enqueue(DataQueueCommand.create(tripleStreamChannelFuture, new byte[0], false, 0)
.channel(channel));
TriRpcStatus status =
TriRpcStatus.UNKNOWN.withCause(new RpcException()).withDescription("Encode Response data error");
writeQueue.enqueue(CancelQueueCommand.createCommand(tripleStreamChannelFuture, Http2Error.CANCEL)
.channel(channel));
writeQueue.enqueue(TextDataQueueCommand.createCommand(tripleStreamChannelFuture, status.description, true)
.channel(channel));
while (writeMethodCalledTimes.get() != 4) {
Thread.sleep(50);
}
ArgumentCaptor<QueuedCommand> commandArgumentCaptor = ArgumentCaptor.forClass(QueuedCommand.class);
ArgumentCaptor<ChannelPromise> promiseArgumentCaptor = ArgumentCaptor.forClass(ChannelPromise.class);
Mockito.verify(channel, Mockito.times(4))
.write(commandArgumentCaptor.capture(), promiseArgumentCaptor.capture());
List<QueuedCommand> queuedCommands = commandArgumentCaptor.getAllValues();
Assertions.assertEquals(queuedCommands.size(), 4);
Assertions.assertTrue(queuedCommands.get(0) instanceof HeaderQueueCommand);
Assertions.assertTrue(queuedCommands.get(1) instanceof DataQueueCommand);
Assertions.assertTrue(queuedCommands.get(2) instanceof CancelQueueCommand);
Assertions.assertTrue(queuedCommands.get(3) instanceof TextDataQueueCommand);
}
@Test
@Disabled
void testChunk() throws Exception {
WriteQueue writeQueue = new WriteQueue();
// test deque chunk size
EmbeddedChannel embeddedChannel = new EmbeddedChannel();
TripleStreamChannelFuture tripleStreamChannelFuture = new TripleStreamChannelFuture(embeddedChannel);
writeMethodCalledTimes.set(0);
for (int i = 0; i < DEQUE_CHUNK_SIZE; i++) {
writeQueue.enqueue(HeaderQueueCommand.createHeaders(tripleStreamChannelFuture, new DefaultHttp2Headers())
.channel(channel));
}
writeQueue.enqueue(HeaderQueueCommand.createHeaders(tripleStreamChannelFuture, new DefaultHttp2Headers())
.channel(channel));
while (writeMethodCalledTimes.get() != (DEQUE_CHUNK_SIZE + 1)) {
Thread.sleep(50);
}
Mockito.verify(channel, Mockito.times(DEQUE_CHUNK_SIZE + 1)).write(Mockito.any(), Mockito.any());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleHttp2ClientResponseHandlerTest.java | dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleHttp2ClientResponseHandlerTest.java | /*
* 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.rpc.protocol.tri.transport;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http2.DefaultHttp2GoAwayFrame;
import io.netty.handler.codec.http2.DefaultHttp2Headers;
import io.netty.handler.codec.http2.DefaultHttp2HeadersFrame;
import io.netty.handler.codec.http2.DefaultHttp2ResetFrame;
import io.netty.handler.codec.http2.Http2Error;
import io.netty.handler.codec.http2.Http2GoAwayFrame;
import io.netty.handler.codec.http2.Http2Headers;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
/**
* {@link TripleHttp2ClientResponseHandler }
*/
class TripleHttp2ClientResponseHandlerTest {
private TripleHttp2ClientResponseHandler handler;
private ChannelHandlerContext ctx;
private AbstractH2TransportListener transportListener;
@BeforeEach
public void init() {
transportListener = Mockito.mock(AbstractH2TransportListener.class);
handler = new TripleHttp2ClientResponseHandler(transportListener);
ctx = Mockito.mock(ChannelHandlerContext.class);
Channel channel = Mockito.mock(Channel.class);
Mockito.when(ctx.channel()).thenReturn(channel);
}
@Test
void testUserEventTriggered() throws Exception {
// test Http2GoAwayFrame
Http2GoAwayFrame goAwayFrame = new DefaultHttp2GoAwayFrame(
Http2Error.NO_ERROR, ByteBufUtil.writeAscii(ByteBufAllocator.DEFAULT, "app_requested"));
handler.userEventTriggered(ctx, goAwayFrame);
Mockito.verify(ctx, Mockito.times(1)).close();
// test Http2ResetFrame
DefaultHttp2ResetFrame resetFrame = new DefaultHttp2ResetFrame(Http2Error.CANCEL);
handler.userEventTriggered(ctx, resetFrame);
Mockito.verify(ctx, Mockito.times(2)).close();
}
@Test
void testChannelRead0() throws Exception {
final Http2Headers headers = new DefaultHttp2Headers(true);
DefaultHttp2HeadersFrame headersFrame = new DefaultHttp2HeadersFrame(headers, true);
handler.channelRead0(ctx, headersFrame);
Mockito.verify(transportListener, Mockito.times(1)).onHeader(headers, true);
}
@Test
void testExceptionCaught() {
RuntimeException exception = new RuntimeException();
handler.exceptionCaught(ctx, exception);
Mockito.verify(ctx).close();
Mockito.verify(transportListener).cancelByRemote(Http2Error.INTERNAL_ERROR.code());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/transport/AbstractH2TransportListenerTest.java | dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/transport/AbstractH2TransportListenerTest.java | /*
* 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.rpc.protocol.tri.transport;
import java.util.Map;
import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http2.DefaultHttp2Headers;
import io.netty.handler.codec.http2.Http2Headers;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static io.netty.handler.codec.http.HttpScheme.HTTPS;
class AbstractH2TransportListenerTest {
@Test
void headersToMap() {
AbstractH2TransportListener listener = new AbstractH2TransportListener() {
@Override
public void onHeader(Http2Headers headers, boolean endStream) {}
@Override
public void onData(ByteBuf data, boolean endStream) {}
@Override
public void cancelByRemote(long errorCode) {}
@Override
public void onClose() {}
};
DefaultHttp2Headers headers = new DefaultHttp2Headers();
headers.scheme(HTTPS.name()).path("/foo.bar").method(HttpMethod.POST.asciiName());
headers.set("foo", "bar");
final Map<String, Object> map = listener.headersToMap(headers, () -> null);
Assertions.assertEquals(4, map.size());
}
@Test
void filterReservedHeaders() {}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/StatusRpcException.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/StatusRpcException.java | /*
* 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.rpc;
public class StatusRpcException extends RpcException {
public TriRpcStatus getStatus() {
return status;
}
private final TriRpcStatus status;
public StatusRpcException(TriRpcStatus status) {
super(TriRpcStatus.triCodeToDubboCode(status.code), status.toMessageWithoutCause(), status.cause);
this.status = status;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/TriRpcStatus.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/TriRpcStatus.java | /*
* 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.rpc;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.remoting.TimeoutException;
import org.apache.dubbo.remoting.http12.exception.HttpStatusException;
import java.io.Serializable;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.QueryStringDecoder;
import io.netty.handler.codec.http.QueryStringEncoder;
import static org.apache.dubbo.rpc.RpcException.AUTHORIZATION_EXCEPTION;
import static org.apache.dubbo.rpc.RpcException.FORBIDDEN_EXCEPTION;
import static org.apache.dubbo.rpc.RpcException.LIMIT_EXCEEDED_EXCEPTION;
import static org.apache.dubbo.rpc.RpcException.METHOD_NOT_FOUND;
import static org.apache.dubbo.rpc.RpcException.NETWORK_EXCEPTION;
import static org.apache.dubbo.rpc.RpcException.SERIALIZATION_EXCEPTION;
import static org.apache.dubbo.rpc.RpcException.TIMEOUT_EXCEPTION;
import static org.apache.dubbo.rpc.RpcException.TIMEOUT_TERMINATE;
import static org.apache.dubbo.rpc.RpcException.UNKNOWN_EXCEPTION;
/**
* See <a href="https://github.com/grpc/grpc/blob/master/doc/statuscodes.md">status codes</a>
*/
public class TriRpcStatus implements Serializable {
private static final long serialVersionUID = 1L;
public static final TriRpcStatus OK = fromCode(Code.OK);
public static final TriRpcStatus UNKNOWN = fromCode(Code.UNKNOWN);
public static final TriRpcStatus INTERNAL = fromCode(Code.INTERNAL);
public static final TriRpcStatus NOT_FOUND = fromCode(Code.NOT_FOUND);
public static final TriRpcStatus CANCELLED = fromCode(Code.CANCELLED);
public static final TriRpcStatus UNAVAILABLE = fromCode(Code.UNAVAILABLE);
public static final TriRpcStatus UNIMPLEMENTED = fromCode(Code.UNIMPLEMENTED);
public static final TriRpcStatus DEADLINE_EXCEEDED = fromCode(Code.DEADLINE_EXCEEDED);
public final Code code;
public final Throwable cause;
public final String description;
public TriRpcStatus(Code code, Throwable cause, String description) {
this.code = code;
this.cause = cause;
this.description = description;
}
public static TriRpcStatus fromCode(int code) {
return fromCode(Code.fromCode(code));
}
public static TriRpcStatus fromCode(Code code) {
return new TriRpcStatus(code, null, null);
}
/**
* todo The remaining exceptions are converted to status
*/
public static TriRpcStatus getStatus(Throwable throwable) {
return getStatus(throwable, null);
}
public static TriRpcStatus getStatus(Throwable throwable, String description) {
if (throwable instanceof HttpStatusException) {
int statusCode = ((HttpStatusException) throwable).getStatusCode();
return new TriRpcStatus(httpStatusToGrpcCode(statusCode), throwable, description);
}
if (throwable instanceof StatusRpcException) {
return ((StatusRpcException) throwable).getStatus();
}
if (throwable instanceof RpcException) {
RpcException rpcException = (RpcException) throwable;
Code code = dubboCodeToTriCode(rpcException.getCode());
return new TriRpcStatus(code, throwable, description);
}
if (throwable instanceof TimeoutException) {
return new TriRpcStatus(Code.DEADLINE_EXCEEDED, throwable, description);
}
return new TriRpcStatus(Code.UNKNOWN, throwable, description);
}
public static int triCodeToDubboCode(Code triCode) {
int code;
switch (triCode) {
case DEADLINE_EXCEEDED:
code = TIMEOUT_EXCEPTION;
break;
case PERMISSION_DENIED:
code = FORBIDDEN_EXCEPTION;
break;
case UNAVAILABLE:
code = NETWORK_EXCEPTION;
break;
case UNIMPLEMENTED:
code = METHOD_NOT_FOUND;
break;
default:
code = UNKNOWN_EXCEPTION;
}
return code;
}
public static Code dubboCodeToTriCode(int rpcExceptionCode) {
Code code;
switch (rpcExceptionCode) {
case TIMEOUT_EXCEPTION:
case TIMEOUT_TERMINATE:
code = Code.DEADLINE_EXCEEDED;
break;
case FORBIDDEN_EXCEPTION:
code = Code.PERMISSION_DENIED;
break;
case AUTHORIZATION_EXCEPTION:
code = Code.UNAUTHENTICATED;
break;
case LIMIT_EXCEEDED_EXCEPTION:
case NETWORK_EXCEPTION:
code = Code.UNAVAILABLE;
break;
case METHOD_NOT_FOUND:
code = Code.UNIMPLEMENTED;
break;
case SERIALIZATION_EXCEPTION:
code = Code.INTERNAL;
break;
default:
code = Code.UNKNOWN;
break;
}
return code;
}
public static String limitSizeTo1KB(String desc) {
if (desc.length() < 1024) {
return desc;
} else {
return desc.substring(0, 1024);
}
}
public static String decodeMessage(String raw) {
if (StringUtils.isEmpty(raw)) {
return "";
}
return QueryStringDecoder.decodeComponent(raw);
}
public static String encodeMessage(String raw) {
if (StringUtils.isEmpty(raw)) {
return "";
}
return encodeComponent(raw);
}
private static String encodeComponent(String raw) {
QueryStringEncoder encoder = new QueryStringEncoder("");
encoder.addParam("", raw);
// ?=
return encoder.toString().substring(2);
}
public static Code httpStatusToGrpcCode(int httpStatusCode) {
if (httpStatusCode >= 100 && httpStatusCode < 200) {
return Code.INTERNAL;
}
if (httpStatusCode == HttpResponseStatus.BAD_REQUEST.code()
|| httpStatusCode == HttpResponseStatus.REQUEST_HEADER_FIELDS_TOO_LARGE.code()) {
return Code.INTERNAL;
} else if (httpStatusCode == HttpResponseStatus.UNAUTHORIZED.code()) {
return Code.UNAUTHENTICATED;
} else if (httpStatusCode == HttpResponseStatus.FORBIDDEN.code()) {
return Code.PERMISSION_DENIED;
} else if (httpStatusCode == HttpResponseStatus.NOT_FOUND.code()) {
return Code.UNIMPLEMENTED;
} else if (httpStatusCode == HttpResponseStatus.BAD_GATEWAY.code()
|| httpStatusCode == HttpResponseStatus.TOO_MANY_REQUESTS.code()
|| httpStatusCode == HttpResponseStatus.SERVICE_UNAVAILABLE.code()
|| httpStatusCode == HttpResponseStatus.GATEWAY_TIMEOUT.code()) {
return Code.UNAVAILABLE;
} else {
return Code.UNKNOWN;
}
}
public static int grpcCodeToHttpStatus(Code code) {
switch (code) {
case OK:
return HttpResponseStatus.OK.code();
case CANCELLED:
return 499;
case UNKNOWN:
case DATA_LOSS:
case INTERNAL:
return HttpResponseStatus.INTERNAL_SERVER_ERROR.code();
case INVALID_ARGUMENT:
case FAILED_PRECONDITION:
case OUT_OF_RANGE:
return HttpResponseStatus.BAD_REQUEST.code();
case DEADLINE_EXCEEDED:
return HttpResponseStatus.GATEWAY_TIMEOUT.code();
case NOT_FOUND:
return HttpResponseStatus.NOT_FOUND.code();
case ALREADY_EXISTS:
case ABORTED:
return HttpResponseStatus.CONFLICT.code();
case PERMISSION_DENIED:
return HttpResponseStatus.FORBIDDEN.code();
case RESOURCE_EXHAUSTED:
return HttpResponseStatus.TOO_MANY_REQUESTS.code();
case UNIMPLEMENTED:
return HttpResponseStatus.NOT_IMPLEMENTED.code();
case UNAVAILABLE:
return HttpResponseStatus.SERVICE_UNAVAILABLE.code();
case UNAUTHENTICATED:
return HttpResponseStatus.UNAUTHORIZED.code();
default:
return -1;
}
}
public boolean isOk() {
return Code.isOk(code.code);
}
public TriRpcStatus withCause(Throwable cause) {
return new TriRpcStatus(this.code, cause, this.description);
}
public TriRpcStatus withDescription(String description) {
return new TriRpcStatus(code, cause, description);
}
public TriRpcStatus appendDescription(String description) {
if (this.description == null) {
return withDescription(description);
} else {
String newDescription = this.description + "\n" + description;
return withDescription(newDescription);
}
}
public StatusRpcException asException() {
return new StatusRpcException(this);
}
public String toEncodedMessage() {
String output = limitSizeTo1KB(toMessage());
return encodeComponent(output);
}
public String toMessageWithoutCause() {
if (description != null) {
return String.format("%s : %s", code, description);
} else {
return code.toString();
}
}
public String toMessage() {
String msg = "";
if (cause == null) {
msg += description;
} else {
String placeHolder = description == null ? "" : description;
msg += StringUtils.toString(placeHolder, cause);
}
return msg;
}
public enum Code {
OK(0),
CANCELLED(1),
UNKNOWN(2),
INVALID_ARGUMENT(3),
DEADLINE_EXCEEDED(4),
NOT_FOUND(5),
ALREADY_EXISTS(6),
PERMISSION_DENIED(7),
RESOURCE_EXHAUSTED(8),
FAILED_PRECONDITION(9),
ABORTED(10),
OUT_OF_RANGE(11),
UNIMPLEMENTED(12),
INTERNAL(13),
UNAVAILABLE(14),
DATA_LOSS(15),
/**
* The request does not have valid authentication credentials for the operation.
*/
UNAUTHENTICATED(16);
public final int code;
Code(int code) {
this.code = code;
}
public static boolean isOk(Integer status) {
return status == OK.code;
}
public static Code fromCode(int code) {
for (Code value : Code.values()) {
if (value.code == code) {
return value;
}
}
throw new IllegalStateException("Can not find status for code: " + code);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/stub/StubInvocationUtil.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/stub/StubInvocationUtil.java | /*
* 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.rpc.stub;
import org.apache.dubbo.common.stream.StreamObserver;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.TriRpcStatus;
import org.apache.dubbo.rpc.model.MethodDescriptor;
import org.apache.dubbo.rpc.proxy.InvocationUtil;
public class StubInvocationUtil {
public static <T, R> R unaryCall(Invoker<?> invoker, MethodDescriptor methodDescriptor, T request) {
return (R) call(invoker, methodDescriptor, new Object[] {request});
}
public static <T, R> void unaryCall(
Invoker<?> invoker, MethodDescriptor method, T request, StreamObserver<R> responseObserver) {
try {
Object res = unaryCall(invoker, method, request);
responseObserver.onNext((R) res);
} catch (Exception e) {
responseObserver.onError(e);
}
responseObserver.onCompleted();
}
public static <T, R> StreamObserver<T> biOrClientStreamCall(
Invoker<?> invoker, MethodDescriptor method, StreamObserver<R> responseObserver) {
return (StreamObserver<T>) call(invoker, method, new Object[] {responseObserver});
}
public static <T, R> void serverStreamCall(
Invoker<?> invoker, MethodDescriptor method, T request, StreamObserver<R> responseObserver) {
call(invoker, method, new Object[] {request, responseObserver});
}
private static Object call(Invoker<?> invoker, MethodDescriptor methodDescriptor, Object[] arguments) {
RpcInvocation rpcInvocation = new RpcInvocation(
invoker.getUrl().getServiceModel(),
methodDescriptor.getMethodName(),
invoker.getInterface().getName(),
invoker.getUrl().getProtocolServiceKey(),
methodDescriptor.getParameterClasses(),
arguments);
// When there are multiple MethodDescriptors with the same method name, the return type will be wrong
rpcInvocation.setReturnType(methodDescriptor.getReturnClass());
try {
return InvocationUtil.invoke(invoker, rpcInvocation);
} catch (Throwable e) {
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
} else {
throw TriRpcStatus.INTERNAL.withCause(e).asException();
}
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/RequestMetadata.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/RequestMetadata.java | /*
* 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.rpc.protocol.tri;
import org.apache.dubbo.remoting.http12.HttpHeaderNames;
import org.apache.dubbo.remoting.http12.message.MediaType;
import org.apache.dubbo.rpc.CancellationContext;
import org.apache.dubbo.rpc.model.MethodDescriptor;
import org.apache.dubbo.rpc.model.PackableMethod;
import org.apache.dubbo.rpc.protocol.tri.compressor.Compressor;
import org.apache.dubbo.rpc.protocol.tri.compressor.Identity;
import org.apache.dubbo.rpc.protocol.tri.stream.StreamUtils;
import java.util.Map;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http2.DefaultHttp2Headers;
import io.netty.util.AsciiString;
public class RequestMetadata {
public AsciiString scheme;
public String application;
public String service;
public String version;
public String group;
public String address;
public String acceptEncoding;
public String timeout;
public Compressor compressor;
public CancellationContext cancellationContext;
public MethodDescriptor method;
public PackableMethod packableMethod;
public Map<String, Object> attachments;
public boolean convertNoLowerHeader;
public boolean ignoreDefaultVersion;
public DefaultHttp2Headers toHeaders() {
DefaultHttp2Headers header = new DefaultHttp2Headers(false);
header.scheme(scheme)
.authority(address)
.method(HttpMethod.POST.asciiName())
.path(RequestPath.toFullPath(service, method.getMethodName()))
.set(HttpHeaderNames.CONTENT_TYPE.getKey(), MediaType.APPLICATION_GRPC_PROTO.getName())
.set(HttpHeaderNames.TE.getKey(), HttpHeaderValues.TRAILERS);
setIfNotNull(header, TripleHeaderEnum.TIMEOUT.getKey(), timeout);
if (!ignoreDefaultVersion || !TripleConstants.DEFAULT_VERSION.equals(version)) {
setIfNotNull(header, TripleHeaderEnum.SERVICE_VERSION.getKey(), version);
}
setIfNotNull(header, TripleHeaderEnum.SERVICE_GROUP.getKey(), group);
setIfNotNull(header, TripleHeaderEnum.CONSUMER_APP_NAME_KEY.getKey(), application);
setIfNotNull(header, TripleHeaderEnum.GRPC_ACCEPT_ENCODING.getKey(), acceptEncoding);
if (!Identity.MESSAGE_ENCODING.equals(compressor.getMessageEncoding())) {
setIfNotNull(header, TripleHeaderEnum.GRPC_ENCODING.getKey(), compressor.getMessageEncoding());
}
StreamUtils.putHeaders(header, attachments, convertNoLowerHeader);
return header;
}
private void setIfNotNull(DefaultHttp2Headers headers, CharSequence key, CharSequence value) {
if (value == null) {
return;
}
headers.set(key, value);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleInvoker.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleInvoker.java | /*
* 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.rpc.protocol.tri;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.Configuration;
import org.apache.dubbo.common.config.ConfigurationUtils;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.stream.StreamObserver;
import org.apache.dubbo.common.threadpool.ThreadlessExecutor;
import org.apache.dubbo.common.utils.ConcurrentHashMapUtils;
import org.apache.dubbo.common.utils.SystemPropertyConfigUtils;
import org.apache.dubbo.remoting.api.connection.AbstractConnectionClient;
import org.apache.dubbo.rpc.AppResponse;
import org.apache.dubbo.rpc.AsyncRpcResult;
import org.apache.dubbo.rpc.CancellationContext;
import org.apache.dubbo.rpc.FutureContext;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.InvokeMode;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.TriRpcStatus;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ConsumerModel;
import org.apache.dubbo.rpc.model.MethodDescriptor;
import org.apache.dubbo.rpc.model.PackableMethod;
import org.apache.dubbo.rpc.model.PackableMethodFactory;
import org.apache.dubbo.rpc.model.ScopeModelUtil;
import org.apache.dubbo.rpc.model.ServiceDescriptor;
import org.apache.dubbo.rpc.model.StubMethodDescriptor;
import org.apache.dubbo.rpc.protocol.AbstractInvoker;
import org.apache.dubbo.rpc.protocol.tri.call.ClientCall;
import org.apache.dubbo.rpc.protocol.tri.call.ObserverToClientCallListenerAdapter;
import org.apache.dubbo.rpc.protocol.tri.call.TripleClientCall;
import org.apache.dubbo.rpc.protocol.tri.call.UnaryClientCallListener;
import org.apache.dubbo.rpc.protocol.tri.compressor.Compressor;
import org.apache.dubbo.rpc.protocol.tri.compressor.Identity;
import org.apache.dubbo.rpc.protocol.tri.h12.grpc.GrpcUtils;
import org.apache.dubbo.rpc.protocol.tri.observer.ClientCallToObserverAdapter;
import org.apache.dubbo.rpc.protocol.tri.transport.TripleWriteQueue;
import org.apache.dubbo.rpc.service.ServiceDescriptorInternalCache;
import org.apache.dubbo.rpc.support.RpcUtils;
import java.util.Arrays;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
import io.netty.util.AsciiString;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_PACKABLE_METHOD_FACTORY;
import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_DESTROY_INVOKER;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_REQUEST;
import static org.apache.dubbo.remoting.http12.message.MediaType.APPLICATION_GRPC_PROTO;
import static org.apache.dubbo.rpc.Constants.COMPRESSOR_KEY;
import static org.apache.dubbo.rpc.Constants.TOKEN_KEY;
import static org.apache.dubbo.rpc.model.MethodDescriptor.RpcType.UNARY;
/**
* TripleInvoker
*/
public class TripleInvoker<T> extends AbstractInvoker<T> {
private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(TripleInvoker.class);
private final AbstractConnectionClient connectionClient;
private final ReentrantLock destroyLock = new ReentrantLock();
private final Set<Invoker<?>> invokers;
private final ExecutorService streamExecutor;
private final String acceptEncodings;
private final TripleWriteQueue writeQueue = new TripleWriteQueue(256);
private static final boolean setFutureWhenSync = Boolean.parseBoolean(SystemPropertyConfigUtils.getSystemProperty(
CommonConstants.ThirdPartyProperty.SET_FUTURE_IN_SYNC_MODE, "true"));
private final PackableMethodFactory packableMethodFactory;
private final ConcurrentHashMap<MethodDescriptor, PackableMethod> packableMethodCache = new ConcurrentHashMap<>();
private static Compressor compressor;
public TripleInvoker(
Class<T> serviceType,
URL url,
String acceptEncodings,
AbstractConnectionClient connectionClient,
Set<Invoker<?>> invokers,
ExecutorService streamExecutor) {
super(serviceType, url, new String[] {INTERFACE_KEY, GROUP_KEY, TOKEN_KEY});
this.invokers = invokers;
this.connectionClient = connectionClient;
this.acceptEncodings = acceptEncodings;
this.streamExecutor = streamExecutor;
this.packableMethodFactory = url.getOrDefaultFrameworkModel()
.getExtensionLoader(PackableMethodFactory.class)
.getExtension(ConfigurationUtils.getGlobalConfiguration(url.getApplicationModel())
.getString(DUBBO_PACKABLE_METHOD_FACTORY, DEFAULT_KEY));
}
private static AsciiString getSchemeFromUrl(URL url) {
boolean ssl = url.getParameter(CommonConstants.SSL_ENABLED_KEY, false);
return ssl ? TripleConstants.HTTPS_SCHEME : TripleConstants.HTTP_SCHEME;
}
private static Compressor getCompressorFromEnv() {
Compressor compressor = TripleInvoker.compressor;
if (compressor == null) {
ApplicationModel model = ApplicationModel.defaultModel();
Configuration configuration = ConfigurationUtils.getEnvConfiguration(model);
String compressorKey = configuration.getString(COMPRESSOR_KEY, Identity.MESSAGE_ENCODING);
compressor = Compressor.getCompressor(ScopeModelUtil.getFrameworkModel(model), compressorKey);
TripleInvoker.compressor = compressor;
}
return compressor;
}
@Override
protected Result doInvoke(final Invocation invocation) {
if (!connectionClient.isConnected()) {
CompletableFuture<AppResponse> future = new CompletableFuture<>();
RpcException exception = TriRpcStatus.UNAVAILABLE
.withDescription(String.format("upstream %s is unavailable", getUrl().getAddress()))
.asException();
future.completeExceptionally(exception);
return new AsyncRpcResult(future, invocation);
}
ConsumerModel consumerModel = (ConsumerModel)
(invocation.getServiceModel() != null ? invocation.getServiceModel() : getUrl().getServiceModel());
ServiceDescriptor serviceDescriptor = consumerModel.getServiceModel();
MethodDescriptor methodDescriptor =
serviceDescriptor.getMethod(invocation.getMethodName(), invocation.getParameterTypes());
if (methodDescriptor == null) {
if (RpcUtils.isGenericCall(
((RpcInvocation) invocation).getParameterTypesDesc(), invocation.getMethodName())) {
// Only reach when server generic
methodDescriptor = ServiceDescriptorInternalCache.genericService()
.getMethod(invocation.getMethodName(), invocation.getParameterTypes());
} else if (RpcUtils.isEcho(
((RpcInvocation) invocation).getParameterTypesDesc(), invocation.getMethodName())) {
methodDescriptor = ServiceDescriptorInternalCache.echoService()
.getMethod(invocation.getMethodName(), invocation.getParameterTypes());
}
}
ExecutorService callbackExecutor =
isSync(methodDescriptor, invocation) ? new ThreadlessExecutor() : streamExecutor;
ClientCall call = new TripleClientCall(
connectionClient, callbackExecutor, getUrl().getOrDefaultFrameworkModel(), writeQueue);
RpcContext.getServiceContext().setLocalAddress(connectionClient.getLocalAddress());
AsyncRpcResult result;
try {
switch (methodDescriptor.getRpcType()) {
case UNARY:
result = invokeUnary(methodDescriptor, invocation, call, callbackExecutor);
break;
case SERVER_STREAM:
result = invokeServerStream(methodDescriptor, invocation, call);
break;
case CLIENT_STREAM:
case BI_STREAM:
result = invokeBiOrClientStream(methodDescriptor, invocation, call);
break;
default:
throw new IllegalStateException("Can not reach here");
}
return result;
} catch (Throwable t) {
final TriRpcStatus status =
TriRpcStatus.INTERNAL.withCause(t).withDescription("Call aborted cause client exception");
RpcException e = status.asException();
try {
call.cancelByLocal(e);
} catch (Throwable t1) {
LOGGER.error(PROTOCOL_FAILED_REQUEST, "", "", "Cancel triple request failed", t1);
}
CompletableFuture<AppResponse> future = new CompletableFuture<>();
future.completeExceptionally(e);
return new AsyncRpcResult(future, invocation);
}
}
private static boolean isSync(MethodDescriptor methodDescriptor, Invocation invocation) {
if (!(invocation instanceof RpcInvocation)) {
return false;
}
RpcInvocation rpcInvocation = (RpcInvocation) invocation;
MethodDescriptor.RpcType rpcType = methodDescriptor.getRpcType();
return UNARY.equals(rpcType) && InvokeMode.SYNC.equals(rpcInvocation.getInvokeMode());
}
AsyncRpcResult invokeServerStream(MethodDescriptor methodDescriptor, Invocation invocation, ClientCall call) {
RequestMetadata request = createRequest(methodDescriptor, invocation, null);
Object[] arguments = invocation.getArguments();
final StreamObserver<Object> requestObserver;
if (arguments.length == 2) {
StreamObserver<Object> responseObserver = (StreamObserver<Object>) arguments[1];
requestObserver = streamCall(call, request, responseObserver);
requestObserver.onNext(invocation.getArguments()[0]);
} else if (arguments.length == 1) {
StreamObserver<Object> responseObserver = (StreamObserver<Object>) arguments[0];
requestObserver = streamCall(call, request, responseObserver);
requestObserver.onNext(null);
} else {
throw new IllegalStateException(
"The first parameter must be a StreamObserver when there are no parameters, or the second parameter must be a StreamObserver when there are parameters");
}
requestObserver.onCompleted();
return new AsyncRpcResult(CompletableFuture.completedFuture(new AppResponse()), invocation);
}
AsyncRpcResult invokeBiOrClientStream(MethodDescriptor methodDescriptor, Invocation invocation, ClientCall call) {
final AsyncRpcResult result;
RequestMetadata request = createRequest(methodDescriptor, invocation, null);
StreamObserver<Object> responseObserver =
(StreamObserver<Object>) invocation.getArguments()[0];
final StreamObserver<Object> requestObserver = streamCall(call, request, responseObserver);
result = new AsyncRpcResult(CompletableFuture.completedFuture(new AppResponse(requestObserver)), invocation);
return result;
}
StreamObserver<Object> streamCall(
ClientCall call, RequestMetadata metadata, StreamObserver<Object> responseObserver) {
ObserverToClientCallListenerAdapter listener = new ObserverToClientCallListenerAdapter(responseObserver);
StreamObserver<Object> streamObserver = call.start(metadata, listener);
if (responseObserver instanceof CancelableStreamObserver) {
final CancellationContext context = new CancellationContext();
CancelableStreamObserver<Object> cancelableStreamObserver =
(CancelableStreamObserver<Object>) responseObserver;
cancelableStreamObserver.setCancellationContext(context);
context.addListener(context1 -> call.cancelByLocal(new IllegalStateException("Canceled by app")));
listener.setOnStartConsumer(dummy -> cancelableStreamObserver.startRequest());
cancelableStreamObserver.beforeStart((ClientCallToObserverAdapter<Object>) streamObserver);
}
return streamObserver;
}
AsyncRpcResult invokeUnary(
MethodDescriptor methodDescriptor,
Invocation invocation,
ClientCall call,
ExecutorService callbackExecutor) {
int timeout = RpcUtils.calculateTimeout(getUrl(), invocation, RpcUtils.getMethodName(invocation), 3000);
if (timeout <= 0) {
return AsyncRpcResult.newDefaultAsyncResult(
new RpcException(
RpcException.TIMEOUT_TERMINATE,
"No time left for making the following call: " + invocation.getServiceName() + "."
+ RpcUtils.getMethodName(invocation) + ", terminate directly."),
invocation);
}
invocation.setAttachment(TIMEOUT_KEY, String.valueOf(timeout));
final AsyncRpcResult result;
DeadlineFuture future = DeadlineFuture.newFuture(
getUrl().getPath(), methodDescriptor.getMethodName(), getUrl().getAddress(), timeout, callbackExecutor);
RequestMetadata request = createRequest(methodDescriptor, invocation, timeout);
final Object pureArgument;
if (methodDescriptor instanceof StubMethodDescriptor) {
pureArgument = invocation.getArguments()[0];
} else {
pureArgument = invocation.getArguments();
}
result = new AsyncRpcResult(future, invocation);
if (setFutureWhenSync || ((RpcInvocation) invocation).getInvokeMode() != InvokeMode.SYNC) {
FutureContext.getContext().setCompatibleFuture(future);
}
result.setExecutor(callbackExecutor);
ClientCall.Listener callListener = new UnaryClientCallListener(future);
final StreamObserver<Object> requestObserver = call.start(request, callListener);
requestObserver.onNext(pureArgument);
requestObserver.onCompleted();
return result;
}
RequestMetadata createRequest(MethodDescriptor methodDescriptor, Invocation invocation, Integer timeout) {
final String methodName = RpcUtils.getMethodName(invocation);
Objects.requireNonNull(
methodDescriptor,
"MethodDescriptor not found for" + methodName + " params:"
+ Arrays.toString(invocation.getCompatibleParamSignatures()));
final RequestMetadata meta = new RequestMetadata();
final URL url = getUrl();
if (methodDescriptor instanceof PackableMethod) {
meta.packableMethod = (PackableMethod) methodDescriptor;
} else {
meta.packableMethod = ConcurrentHashMapUtils.computeIfAbsent(
packableMethodCache,
methodDescriptor,
(md) -> packableMethodFactory.create(md, url, APPLICATION_GRPC_PROTO.getName()));
}
meta.convertNoLowerHeader = TripleProtocol.CONVERT_NO_LOWER_HEADER;
meta.ignoreDefaultVersion = TripleProtocol.IGNORE_1_0_0_VERSION;
meta.method = methodDescriptor;
meta.scheme = getSchemeFromUrl(url);
meta.compressor = getCompressorFromEnv();
meta.cancellationContext = RpcContext.getCancellationContext();
meta.address = url.getAddress();
meta.service = url.getPath();
meta.group = url.getGroup();
meta.version = url.getVersion();
meta.acceptEncoding = acceptEncodings;
if (timeout != null) {
meta.timeout = GrpcUtils.getTimeoutHeaderValue(Long.valueOf(timeout), TimeUnit.MILLISECONDS);
}
String application = (String) invocation.getObjectAttachmentWithoutConvert(CommonConstants.APPLICATION_KEY);
if (application == null) {
application = (String) invocation.getObjectAttachmentWithoutConvert(CommonConstants.REMOTE_APPLICATION_KEY);
}
meta.application = application;
meta.attachments = invocation.getObjectAttachments();
return meta;
}
@Override
public boolean isAvailable() {
if (!super.isAvailable()) {
return false;
}
return connectionClient.isConnected();
}
@Override
public void destroy() {
// in order to avoid closing a client multiple times, a counter is used in case of connection per jvm, every
// time when client.close() is called, counter counts down once, and when counter reaches zero, client will be
// closed.
if (!super.isDestroyed()) {
// double check to avoid dup close
destroyLock.lock();
try {
if (super.isDestroyed()) {
return;
}
super.destroy();
if (invokers != null) {
invokers.remove(this);
}
try {
connectionClient.release();
} catch (Throwable t) {
logger.warn(PROTOCOL_FAILED_DESTROY_INVOKER, "", "", t.getMessage(), t);
}
} finally {
destroyLock.unlock();
}
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ServerStreamObserver.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ServerStreamObserver.java | /*
* 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.rpc.protocol.tri;
import org.apache.dubbo.rpc.protocol.tri.observer.CallStreamObserver;
public interface ServerStreamObserver<T> extends CallStreamObserver<T> {}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleHeaderEnum.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleHeaderEnum.java | /*
* 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.rpc.protocol.tri;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.rpc.protocol.tri.rest.RestConstants;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import io.netty.handler.codec.http2.Http2Headers.PseudoHeaderName;
import io.netty.util.AsciiString;
public enum TripleHeaderEnum {
HTTP_STATUS_KEY("http-status"),
STATUS_KEY("grpc-status"),
MESSAGE_KEY("grpc-message"),
STATUS_DETAIL_KEY("grpc-status-details-bin"),
TIMEOUT("grpc-timeout"),
GRPC_ENCODING("grpc-encoding"),
GRPC_ACCEPT_ENCODING("grpc-accept-encoding"),
CONSUMER_APP_NAME_KEY("tri-consumer-appname"),
SERVICE_VERSION("tri-service-version"),
SERVICE_GROUP("tri-service-group"),
SERVICE_TIMEOUT("tri-service-timeout"),
TRI_HEADER_CONVERT("tri-header-convert"),
TRI_EXCEPTION_CODE("tri-exception-code");
static final Map<String, TripleHeaderEnum> enumMap = new HashMap<>();
static final Set<String> excludeAttachmentsSet = new HashSet<>();
static {
for (TripleHeaderEnum item : values()) {
enumMap.put(item.getName(), item);
}
for (PseudoHeaderName value : PseudoHeaderName.values()) {
excludeAttachmentsSet.add(value.value().toString());
}
String[] internalHttpHeaders = new String[] {
CommonConstants.GROUP_KEY,
CommonConstants.INTERFACE_KEY,
CommonConstants.PATH_KEY,
CommonConstants.REMOTE_APPLICATION_KEY,
CommonConstants.APPLICATION_KEY,
TripleConstants.SERIALIZATION_KEY,
RestConstants.HEADER_SERVICE_VERSION,
RestConstants.HEADER_SERVICE_GROUP
};
Collections.addAll(excludeAttachmentsSet, internalHttpHeaders);
}
private final String name;
private final CharSequence key;
TripleHeaderEnum(String name) {
this.name = name;
this.key = AsciiString.cached(name);
}
public static boolean containsExcludeAttachments(String key) {
return excludeAttachmentsSet.contains(key) || enumMap.containsKey(key);
}
public String getName() {
return name;
}
public CharSequence getKey() {
return key;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/CancelableStreamObserver.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/CancelableStreamObserver.java | /*
* 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.rpc.protocol.tri;
import org.apache.dubbo.common.stream.StreamObserver;
import org.apache.dubbo.rpc.CancellationContext;
import org.apache.dubbo.rpc.protocol.tri.observer.ClientCallToObserverAdapter;
public abstract class CancelableStreamObserver<T> implements StreamObserver<T> {
private CancellationContext cancellationContext;
public void setCancellationContext(CancellationContext cancellationContext) {
this.cancellationContext = cancellationContext;
}
public CancellationContext getCancellationContext() {
return cancellationContext;
}
public void cancel(Throwable throwable) {
cancellationContext.cancel(throwable);
}
public void beforeStart(ClientCallToObserverAdapter<T> clientCallToObserverAdapter) {
// do nothing
}
public void startRequest() {
// do nothing
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/RpcInvocationBuildContext.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/RpcInvocationBuildContext.java | /*
* 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.rpc.protocol.tri;
import org.apache.dubbo.remoting.http12.message.HttpMessageDecoder;
import org.apache.dubbo.remoting.http12.message.HttpMessageEncoder;
import org.apache.dubbo.remoting.http12.message.MethodMetadata;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.model.MethodDescriptor;
import org.apache.dubbo.rpc.model.ServiceDescriptor;
import java.util.Map;
public interface RpcInvocationBuildContext {
Invoker<?> getInvoker();
boolean isHasStub();
String getMethodName();
MethodMetadata getMethodMetadata();
void setMethodMetadata(MethodMetadata methodMetadata);
MethodDescriptor getMethodDescriptor();
void setMethodDescriptor(MethodDescriptor methodDescriptor);
ServiceDescriptor getServiceDescriptor();
HttpMessageDecoder getHttpMessageDecoder();
HttpMessageEncoder getHttpMessageEncoder();
Map<String, Object> getAttributes();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/RestProtocol.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/RestProtocol.java | /*
* 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.rpc.protocol.tri;
import org.apache.dubbo.rpc.model.FrameworkModel;
public class RestProtocol extends TripleProtocol {
public RestProtocol(FrameworkModel frameworkModel) {
super(frameworkModel);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/PbArrayPacker.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/PbArrayPacker.java | /*
* 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.rpc.protocol.tri;
import org.apache.dubbo.rpc.model.Pack;
import com.google.protobuf.Message;
public class PbArrayPacker implements Pack {
private static final Pack PB_PACK = o -> ((Message) o).toByteArray();
private final boolean singleArgument;
public PbArrayPacker(boolean singleArgument) {
this.singleArgument = singleArgument;
}
@Override
public byte[] pack(Object obj) throws Exception {
if (!singleArgument) {
obj = ((Object[]) obj)[0];
}
return PB_PACK.pack(obj);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleConstants.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleConstants.java | /*
* 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.rpc.protocol.tri;
import io.netty.util.AsciiString;
public final class TripleConstants {
public static final String DEFAULT_VERSION = "1.0.0";
public static final String SERIALIZATION_KEY = "serialization";
public static final String HESSIAN4 = "hessian4";
public static final String HESSIAN2 = "hessian2";
public static final String HEADER_BIN_SUFFIX = "-bin";
public static final AsciiString HTTPS_SCHEME = AsciiString.of("https");
public static final AsciiString HTTP_SCHEME = AsciiString.of("http");
public static final String REMOTE_ADDRESS_KEY = "tri.remote.address";
public static final String HANDLER_TYPE_KEY = "tri.handler.type";
public static final String HTTP_REQUEST_KEY = "tri.http.request";
public static final String HTTP_RESPONSE_KEY = "tri.http.response";
public static final String TRIPLE_HANDLER_TYPE_REST = "rest";
public static final String TRIPLE_HANDLER_TYPE_GRPC = "grpc";
public static final String UPGRADE_HEADER_KEY = "Upgrade";
private TripleConstants() {}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/PbUnpack.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/PbUnpack.java | /*
* 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.rpc.protocol.tri;
import org.apache.dubbo.rpc.model.UnPack;
import java.io.ByteArrayInputStream;
import java.io.IOException;
public class PbUnpack<T> implements UnPack {
private final Class<T> clz;
public PbUnpack(Class<T> clz) {
this.clz = clz;
}
@Override
public Object unpack(byte[] data) throws IOException {
final ByteArrayInputStream bais = new ByteArrayInputStream(data);
return SingleProtobufUtils.deserialize(bais, clz);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleProtocol.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleProtocol.java | /*
* 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.rpc.protocol.tri;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.Configuration;
import org.apache.dubbo.common.config.ConfigurationUtils;
import org.apache.dubbo.common.threadpool.manager.ExecutorRepository;
import org.apache.dubbo.common.utils.ExecutorUtil;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.remoting.Constants;
import org.apache.dubbo.remoting.api.connection.AbstractConnectionClient;
import org.apache.dubbo.remoting.api.pu.DefaultPuHandler;
import org.apache.dubbo.remoting.exchange.PortUnificationExchanger;
import org.apache.dubbo.rpc.Exporter;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.PathResolver;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.protocol.AbstractExporter;
import org.apache.dubbo.rpc.protocol.AbstractProtocol;
import org.apache.dubbo.rpc.protocol.tri.compressor.DeCompressor;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.DefaultRequestMappingRegistry;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.RequestMappingRegistry;
import org.apache.dubbo.rpc.protocol.tri.service.TriBuiltinService;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import io.grpc.health.v1.HealthCheckResponse.ServingStatus;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_CLIENT_THREADPOOL;
import static org.apache.dubbo.common.constants.CommonConstants.THREADPOOL_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY;
import static org.apache.dubbo.config.Constants.CLIENT_THREAD_POOL_NAME;
import static org.apache.dubbo.config.Constants.SERVER_THREAD_POOL_NAME;
import static org.apache.dubbo.rpc.Constants.H2_SETTINGS_IGNORE_1_0_0_KEY;
import static org.apache.dubbo.rpc.Constants.H2_SETTINGS_OPENAPI_ENABLED;
import static org.apache.dubbo.rpc.Constants.H2_SETTINGS_RESOLVE_FALLBACK_TO_DEFAULT_KEY;
import static org.apache.dubbo.rpc.Constants.H2_SETTINGS_REST_ENABLED;
import static org.apache.dubbo.rpc.Constants.H2_SETTINGS_SUPPORT_NO_LOWER_HEADER_KEY;
import static org.apache.dubbo.rpc.Constants.H2_SETTINGS_VERBOSE_ENABLED;
public class TripleProtocol extends AbstractProtocol {
private final PathResolver pathResolver;
private final RequestMappingRegistry mappingRegistry;
private final TriBuiltinService triBuiltinService;
private final String acceptEncodings;
public static boolean CONVERT_NO_LOWER_HEADER = true;
public static boolean IGNORE_1_0_0_VERSION = false;
public static boolean RESOLVE_FALLBACK_TO_DEFAULT = true;
public static boolean VERBOSE_ENABLED = false;
public static boolean REST_ENABLED = true;
public static boolean OPENAPI_ENABLED = false;
public TripleProtocol(FrameworkModel frameworkModel) {
this.frameworkModel = frameworkModel;
triBuiltinService = new TriBuiltinService(frameworkModel);
pathResolver = frameworkModel.getDefaultExtension(PathResolver.class);
mappingRegistry = frameworkModel.getOrRegisterBean(DefaultRequestMappingRegistry.class);
acceptEncodings = String.join(",", frameworkModel.getSupportedExtensions(DeCompressor.class));
// init env settings
Configuration conf = ConfigurationUtils.getEnvConfiguration(ApplicationModel.defaultModel());
CONVERT_NO_LOWER_HEADER = conf.getBoolean(H2_SETTINGS_SUPPORT_NO_LOWER_HEADER_KEY, true);
IGNORE_1_0_0_VERSION = conf.getBoolean(H2_SETTINGS_IGNORE_1_0_0_KEY, false);
RESOLVE_FALLBACK_TO_DEFAULT = conf.getBoolean(H2_SETTINGS_RESOLVE_FALLBACK_TO_DEFAULT_KEY, true);
// init global settings
Configuration globalConf = ConfigurationUtils.getGlobalConfiguration(frameworkModel.defaultApplication());
VERBOSE_ENABLED = globalConf.getBoolean(H2_SETTINGS_VERBOSE_ENABLED, false);
REST_ENABLED = globalConf.getBoolean(H2_SETTINGS_REST_ENABLED, true);
OPENAPI_ENABLED = globalConf.getBoolean(H2_SETTINGS_OPENAPI_ENABLED, false);
ServletExchanger.init(globalConf);
Http3Exchanger.init(globalConf);
}
@Override
public int getDefaultPort() {
return 50051;
}
@Override
public <T> Exporter<T> export(Invoker<T> invoker) throws RpcException {
URL url = invoker.getUrl();
String key = serviceKey(url);
// create exporter
AbstractExporter<T> exporter = new AbstractExporter<T>(invoker) {
@Override
public void afterUnExport() {
// unregister grpc request mapping
pathResolver.unregister(invoker);
// unregister rest request mapping
if (REST_ENABLED) {
mappingRegistry.unregister(invoker);
}
// set service status to NOT_SERVING
setServiceStatus(url, false);
exporterMap.remove(key);
}
};
exporterMap.put(key, exporter);
// add invoker
invokers.add(invoker);
// register grpc path mapping
pathResolver.register(invoker);
// register rest request mapping
if (REST_ENABLED) {
mappingRegistry.register(invoker);
}
// set service status to SERVING
setServiceStatus(url, true);
// init server executor
ExecutorRepository.getInstance(url.getOrDefaultApplicationModel())
.createExecutorIfAbsent(ExecutorUtil.setThreadName(url, SERVER_THREAD_POOL_NAME));
// bind server port
bindServerPort(url);
// optimize serialization
optimizeSerialization(url);
return exporter;
}
private void setServiceStatus(URL url, boolean serving) {
if (triBuiltinService.enable()) {
ServingStatus status = serving ? ServingStatus.SERVING : ServingStatus.NOT_SERVING;
triBuiltinService.getHealthStatusManager().setStatus(url.getServiceKey(), status);
triBuiltinService.getHealthStatusManager().setStatus(url.getServiceInterface(), status);
}
}
private void bindServerPort(URL url) {
boolean bindPort = true;
if (ServletExchanger.isEnabled()) {
int port = url.getParameter(Constants.BIND_PORT_KEY, url.getPort());
Integer serverPort = ServletExchanger.getServerPort();
if (serverPort == null) {
if (NetUtils.isPortInUsed(port)) {
bindPort = false;
}
} else if (serverPort == port) {
bindPort = false;
}
ServletExchanger.bind(url);
}
if (bindPort) {
PortUnificationExchanger.bind(url, new DefaultPuHandler());
}
Http3Exchanger.bind(url);
}
@Override
public <T> Invoker<T> refer(Class<T> type, URL url) throws RpcException {
optimizeSerialization(url);
ExecutorService streamExecutor = getOrCreateStreamExecutor(url.getOrDefaultApplicationModel(), url);
AbstractConnectionClient connectionClient = Http3Exchanger.isEnabled(url)
? Http3Exchanger.connect(url)
: PortUnificationExchanger.connect(url, new DefaultPuHandler());
TripleInvoker<T> invoker =
new TripleInvoker<>(type, url, acceptEncodings, connectionClient, invokers, streamExecutor);
invokers.add(invoker);
return invoker;
}
private ExecutorService getOrCreateStreamExecutor(ApplicationModel applicationModel, URL url) {
url = url.addParameter(THREAD_NAME_KEY, CLIENT_THREAD_POOL_NAME)
.addParameterIfAbsent(THREADPOOL_KEY, DEFAULT_CLIENT_THREADPOOL);
ExecutorService executor =
ExecutorRepository.getInstance(applicationModel).createExecutorIfAbsent(url);
Objects.requireNonNull(executor, String.format("No available executor found in %s", url));
return executor;
}
@Override
protected <T> Invoker<T> protocolBindingRefer(Class<T> type, URL url) throws RpcException {
return null;
}
@Override
public void destroy() {
if (logger.isInfoEnabled()) {
logger.info("Destroying protocol [{}] ...", getClass().getSimpleName());
}
PortUnificationExchanger.close();
Http3Exchanger.close();
pathResolver.destroy();
if (REST_ENABLED) {
mappingRegistry.destroy();
}
super.destroy();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ReflectionPackableMethod.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ReflectionPackableMethod.java | /*
* 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.rpc.protocol.tri;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.serialize.MultipleSerialization;
import org.apache.dubbo.common.stream.StreamObserver;
import org.apache.dubbo.config.Constants;
import org.apache.dubbo.remoting.transport.CodecSupport;
import org.apache.dubbo.remoting.utils.UrlUtils;
import org.apache.dubbo.rpc.model.MethodDescriptor;
import org.apache.dubbo.rpc.model.Pack;
import org.apache.dubbo.rpc.model.PackableMethod;
import org.apache.dubbo.rpc.model.UnPack;
import org.apache.dubbo.rpc.model.WrapperUnPack;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.Iterator;
import java.util.stream.Stream;
import com.google.protobuf.Message;
import static org.apache.dubbo.common.constants.CommonConstants.$ECHO;
import static org.apache.dubbo.common.utils.ProtobufUtils.isProtobufClass;
public class ReflectionPackableMethod implements PackableMethod {
private static final String GRPC_ASYNC_RETURN_CLASS = "com.google.common.util.concurrent.ListenableFuture";
private static final String TRI_ASYNC_RETURN_CLASS = "java.util.concurrent.CompletableFuture";
private static final String REACTOR_RETURN_CLASS = "reactor.core.publisher.Mono";
private static final String RX_RETURN_CLASS = "io.reactivex.Single";
private static final String GRPC_STREAM_CLASS = "io.grpc.stub.StreamObserver";
private static final Pack PB_PACK = o -> ((Message) o).toByteArray();
private final Pack requestPack;
private final Pack responsePack;
private final UnPack requestUnpack;
private final UnPack responseUnpack;
private final boolean needWrapper;
private final Collection<String> allSerialize;
@Override
public boolean needWrapper() {
return this.needWrapper;
}
public ReflectionPackableMethod(
MethodDescriptor method, URL url, String serializeName, Collection<String> allSerialize) {
Class<?>[] actualRequestTypes;
Class<?> actualResponseType;
switch (method.getRpcType()) {
case CLIENT_STREAM:
case BI_STREAM:
case SERVER_STREAM:
actualRequestTypes = method.getActualRequestTypes();
actualResponseType = method.getActualResponseType();
break;
case UNARY:
actualRequestTypes = method.getParameterClasses();
actualResponseType = (Class<?>) method.getReturnTypes()[0];
break;
default:
throw new IllegalStateException("Can not reach here");
}
boolean singleArgument = method.getRpcType() != MethodDescriptor.RpcType.UNARY;
this.needWrapper = needWrap(method, actualRequestTypes, actualResponseType);
if (!needWrapper) {
requestPack = new PbArrayPacker(singleArgument);
responsePack = PB_PACK;
requestUnpack = new PbUnpack<>(actualRequestTypes[0]);
responseUnpack = new PbUnpack<>(actualResponseType);
} else {
final MultipleSerialization serialization = url.getOrDefaultFrameworkModel()
.getExtensionLoader(MultipleSerialization.class)
.getExtension(url.getParameter(Constants.MULTI_SERIALIZATION_KEY, CommonConstants.DEFAULT_KEY));
// client
this.requestPack =
new WrapRequestPack(serialization, url, serializeName, actualRequestTypes, singleArgument);
this.responseUnpack = new WrapResponseUnpack(serialization, url, allSerialize, actualResponseType);
// server
this.responsePack = new WrapResponsePack(serialization, url, serializeName, actualResponseType);
this.requestUnpack = new WrapRequestUnpack(serialization, url, allSerialize, actualRequestTypes);
}
this.allSerialize = allSerialize;
}
public static ReflectionPackableMethod init(MethodDescriptor methodDescriptor, URL url) {
String serializeName = UrlUtils.serializationOrDefault(url);
Collection<String> allSerialize = UrlUtils.allSerializations(url);
return new ReflectionPackableMethod(methodDescriptor, url, serializeName, allSerialize);
}
public static boolean isStreamType(Class<?> type) {
return StreamObserver.class.isAssignableFrom(type) || GRPC_STREAM_CLASS.equalsIgnoreCase(type.getName());
}
/**
* Determine if the request and response instance should be wrapped in Protobuf wrapper object
*
* @return true if the request and response object is not generated by protobuf
*/
public static boolean needWrap(
MethodDescriptor methodDescriptor, Class<?>[] parameterClasses, Class<?> returnClass) {
String methodName = methodDescriptor.getMethodName();
// generic call must be wrapped
if (CommonConstants.$INVOKE.equals(methodName) || CommonConstants.$INVOKE_ASYNC.equals(methodName)) {
return true;
}
// echo must be wrapped
if ($ECHO.equals(methodName)) {
return true;
}
boolean returnClassProtobuf = isProtobufClass(returnClass);
// Response foo()
if (parameterClasses.length == 0) {
return !returnClassProtobuf;
}
int protobufParameterCount = 0;
int javaParameterCount = 0;
int streamParameterCount = 0;
boolean secondParameterStream = false;
// count normal and protobuf param
for (int i = 0; i < parameterClasses.length; i++) {
Class<?> parameterClass = parameterClasses[i];
if (isProtobufClass(parameterClass)) {
protobufParameterCount++;
} else {
if (isStreamType(parameterClass)) {
if (i == 1) {
secondParameterStream = true;
}
streamParameterCount++;
} else {
javaParameterCount++;
}
}
}
// more than one stream param
if (streamParameterCount > 1) {
throw new IllegalStateException("method params error: more than one Stream params. method=" + methodName);
}
// protobuf only support one param
if (protobufParameterCount >= 2) {
throw new IllegalStateException("method params error: more than one protobuf params. method=" + methodName);
}
// server stream support one normal param and one stream param
if (streamParameterCount == 1) {
if (javaParameterCount + protobufParameterCount > 1) {
throw new IllegalStateException(
"method params error: server stream does not support more than one normal param." + " method="
+ methodName);
}
// server stream: void foo(Request, StreamObserver<Response>)
if (!secondParameterStream) {
throw new IllegalStateException(
"method params error: server stream's second param must be StreamObserver." + " method="
+ methodName);
}
}
if (methodDescriptor.getRpcType() != MethodDescriptor.RpcType.UNARY) {
if (MethodDescriptor.RpcType.SERVER_STREAM == methodDescriptor.getRpcType()) {
if (!secondParameterStream) {
throw new IllegalStateException(
"method params error:server stream's second param must be StreamObserver." + " method="
+ methodName);
}
}
// param type must be consistent
if (returnClassProtobuf) {
if (javaParameterCount > 0) {
throw new IllegalStateException(
"method params error: both normal and protobuf param found. method=" + methodName);
}
} else {
if (protobufParameterCount > 0) {
throw new IllegalStateException("method params error method=" + methodName);
}
}
} else {
if (streamParameterCount > 0) {
throw new IllegalStateException(
"method params error: unary method should not contain any StreamObserver." + " method="
+ methodName);
}
if (protobufParameterCount > 0 && returnClassProtobuf) {
return false;
}
// handler reactor or rxjava only consider gen by proto
if (isMono(returnClass) || isRx(returnClass)) {
return false;
}
if (protobufParameterCount <= 0 && !returnClassProtobuf) {
return true;
}
// handle grpc stub only consider gen by proto
if (GRPC_ASYNC_RETURN_CLASS.equalsIgnoreCase(returnClass.getName()) && protobufParameterCount == 1) {
return false;
}
// handle dubbo generated method
if (TRI_ASYNC_RETURN_CLASS.equalsIgnoreCase(returnClass.getName())) {
Class<?> actualReturnClass = (Class<?>)
((ParameterizedType) methodDescriptor.getMethod().getGenericReturnType())
.getActualTypeArguments()[0];
boolean actualReturnClassProtobuf = isProtobufClass(actualReturnClass);
if (actualReturnClassProtobuf && protobufParameterCount == 1) {
return false;
}
if (!actualReturnClassProtobuf && protobufParameterCount == 0) {
return true;
}
}
// todo remove this in future
boolean ignore = checkNeedIgnore(returnClass);
if (ignore) {
return protobufParameterCount != 1;
}
throw new IllegalStateException("method params error method=" + methodName);
}
// java param should be wrapped
return javaParameterCount > 0;
}
/**
* fixme will produce error on grpc. but is harmless so ignore now
*/
static boolean checkNeedIgnore(Class<?> returnClass) {
return Iterator.class.isAssignableFrom(returnClass);
}
static boolean isMono(Class<?> clz) {
return REACTOR_RETURN_CLASS.equalsIgnoreCase(clz.getName());
}
static boolean isRx(Class<?> clz) {
return RX_RETURN_CLASS.equalsIgnoreCase(clz.getName());
}
private static String convertHessianFromWrapper(String serializeType) {
if (TripleConstants.HESSIAN4.equals(serializeType)) {
return TripleConstants.HESSIAN2;
}
return serializeType;
}
static Class<?> obtainActualTypeInStreamObserver(Type typeInStreamObserver) {
return (Class<?>)
(typeInStreamObserver instanceof ParameterizedType
? ((ParameterizedType) typeInStreamObserver).getRawType()
: typeInStreamObserver);
}
@Override
public Pack getRequestPack() {
return requestPack;
}
@Override
public Pack getResponsePack() {
return responsePack;
}
@Override
public UnPack getResponseUnpack() {
return responseUnpack;
}
@Override
public UnPack getRequestUnpack() {
return requestUnpack;
}
private static class WrapResponsePack implements Pack {
private final MultipleSerialization multipleSerialization;
private final URL url;
private final Class<?> actualResponseType;
// wrapper request set serialize type
String requestSerialize;
private WrapResponsePack(
MultipleSerialization multipleSerialization,
URL url,
String defaultSerialize,
Class<?> actualResponseType) {
this.multipleSerialization = multipleSerialization;
this.url = url;
this.actualResponseType = actualResponseType;
this.requestSerialize = defaultSerialize;
}
@Override
public byte[] pack(Object obj) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
multipleSerialization.serialize(url, requestSerialize, actualResponseType, obj, bos);
return TripleCustomerProtocolWrapper.TripleResponseWrapper.Builder.newBuilder()
.setSerializeType(requestSerialize)
.setType(actualResponseType.getName())
.setData(bos.toByteArray())
.build()
.toByteArray();
}
}
private static class WrapResponseUnpack implements WrapperUnPack {
private final MultipleSerialization serialization;
private final URL url;
private final Class<?> returnClass;
private final Collection<String> allSerialize;
private WrapResponseUnpack(
MultipleSerialization serialization, URL url, Collection<String> allSerialize, Class<?> returnClass) {
this.serialization = serialization;
this.url = url;
this.returnClass = returnClass;
this.allSerialize = allSerialize;
}
@Override
public Object unpack(byte[] data) throws IOException, ClassNotFoundException {
return unpack(data, false);
}
public Object unpack(byte[] data, boolean isReturnTriException) throws IOException, ClassNotFoundException {
TripleCustomerProtocolWrapper.TripleResponseWrapper wrapper =
TripleCustomerProtocolWrapper.TripleResponseWrapper.parseFrom(data);
final String serializeType = convertHessianFromWrapper(wrapper.getSerializeType());
CodecSupport.checkSerialization(serializeType, allSerialize);
ByteArrayInputStream bais = new ByteArrayInputStream(wrapper.getData());
if (isReturnTriException) {
return serialization.deserialize(url, serializeType, Exception.class, bais);
}
return serialization.deserialize(url, serializeType, returnClass, bais);
}
}
private static class WrapRequestPack implements Pack {
private final String serialize;
private final MultipleSerialization multipleSerialization;
private final String[] argumentsType;
private final Class<?>[] actualRequestTypes;
private final URL url;
private final boolean singleArgument;
private WrapRequestPack(
MultipleSerialization multipleSerialization,
URL url,
String serialize,
Class<?>[] actualRequestTypes,
boolean singleArgument) {
this.url = url;
this.serialize = convertHessianToWrapper(serialize);
this.multipleSerialization = multipleSerialization;
this.actualRequestTypes = actualRequestTypes;
this.argumentsType =
Stream.of(actualRequestTypes).map(Class::getName).toArray(String[]::new);
this.singleArgument = singleArgument;
}
@Override
public byte[] pack(Object obj) throws IOException {
Object[] arguments;
if (singleArgument) {
arguments = new Object[] {obj};
} else {
arguments = (Object[]) obj;
}
TripleCustomerProtocolWrapper.TripleRequestWrapper.Builder builder =
TripleCustomerProtocolWrapper.TripleRequestWrapper.Builder.newBuilder();
builder.setSerializeType(serialize);
for (String type : argumentsType) {
builder.addArgTypes(type);
}
if (actualRequestTypes == null || actualRequestTypes.length == 0) {
return builder.build().toByteArray();
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
for (int i = 0; i < arguments.length; i++) {
Object argument = arguments[i];
multipleSerialization.serialize(url, serialize, actualRequestTypes[i], argument, bos);
builder.addArgs(bos.toByteArray());
bos.reset();
}
return builder.build().toByteArray();
}
/**
* Convert hessian version from Dubbo's SPI version(hessian2) to wrapper API version
* (hessian4)
*
* @param serializeType literal type
* @return hessian4 if the param is hessian2, otherwise return the param
*/
private String convertHessianToWrapper(String serializeType) {
if (TripleConstants.HESSIAN2.equals(serializeType)) {
return TripleConstants.HESSIAN4;
}
return serializeType;
}
}
private class WrapRequestUnpack implements WrapperUnPack {
private final MultipleSerialization serialization;
private final URL url;
private final Class<?>[] actualRequestTypes;
private final Collection<String> allSerialize;
private WrapRequestUnpack(
MultipleSerialization serialization,
URL url,
Collection<String> allSerialize,
Class<?>[] actualRequestTypes) {
this.serialization = serialization;
this.url = url;
this.actualRequestTypes = actualRequestTypes;
this.allSerialize = allSerialize;
}
public Object unpack(byte[] data, boolean isReturnTriException) throws IOException, ClassNotFoundException {
TripleCustomerProtocolWrapper.TripleRequestWrapper wrapper =
TripleCustomerProtocolWrapper.TripleRequestWrapper.parseFrom(data);
String wrapperSerializeType = convertHessianFromWrapper(wrapper.getSerializeType());
CodecSupport.checkSerialization(wrapperSerializeType, allSerialize);
Object[] ret = new Object[wrapper.getArgs().size()];
((WrapResponsePack) responsePack).requestSerialize = wrapper.getSerializeType();
for (int i = 0; i < wrapper.getArgs().size(); i++) {
ByteArrayInputStream bais =
new ByteArrayInputStream(wrapper.getArgs().get(i));
ret[i] = serialization.deserialize(url, wrapper.getSerializeType(), actualRequestTypes[i], bais);
}
return ret;
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/Http2ProtocolDetector.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/Http2ProtocolDetector.java | /*
* 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.rpc.protocol.tri;
import org.apache.dubbo.remoting.api.ProtocolDetector;
import org.apache.dubbo.remoting.buffer.ByteBufferBackedChannelBuffer;
import org.apache.dubbo.remoting.buffer.ChannelBuffer;
import org.apache.dubbo.remoting.buffer.ChannelBuffers;
import io.netty.handler.codec.http2.Http2CodecUtil;
import static java.lang.Math.min;
public class Http2ProtocolDetector implements ProtocolDetector {
private final ChannelBuffer clientPrefaceString = new ByteBufferBackedChannelBuffer(
Http2CodecUtil.connectionPrefaceBuf().nioBuffer());
@Override
public Result detect(ChannelBuffer in) {
int prefaceLen = clientPrefaceString.readableBytes();
int bytesRead = min(in.readableBytes(), prefaceLen);
// If the input so far doesn't match the preface, break the connection.
if (bytesRead == 0 || !ChannelBuffers.prefixEquals(in, clientPrefaceString, bytesRead)) {
return Result.unrecognized();
}
if (bytesRead == prefaceLen) {
return Result.recognized();
}
return Result.needMoreData();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleHttp2FrameCodecBuilder.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleHttp2FrameCodecBuilder.java | /*
* 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.rpc.protocol.tri;
import org.apache.dubbo.common.utils.Assert;
import java.util.function.Consumer;
import io.netty.handler.codec.http2.DefaultHttp2Connection;
import io.netty.handler.codec.http2.Http2CodecUtil;
import io.netty.handler.codec.http2.Http2Connection;
import io.netty.handler.codec.http2.Http2FrameCodecBuilder;
import io.netty.handler.codec.http2.Http2LocalFlowController;
import io.netty.handler.codec.http2.Http2RemoteFlowController;
public class TripleHttp2FrameCodecBuilder extends Http2FrameCodecBuilder {
TripleHttp2FrameCodecBuilder(Http2Connection connection) {
connection(connection);
}
public static TripleHttp2FrameCodecBuilder fromConnection(Http2Connection connection) {
return new TripleHttp2FrameCodecBuilder(connection);
}
public static TripleHttp2FrameCodecBuilder forClient() {
return forClient(Http2CodecUtil.SMALLEST_MAX_CONCURRENT_STREAMS);
}
public static TripleHttp2FrameCodecBuilder forClient(int maxReservedStreams) {
return fromConnection(new DefaultHttp2Connection(false, maxReservedStreams));
}
public static TripleHttp2FrameCodecBuilder forServer() {
return forServer(Http2CodecUtil.SMALLEST_MAX_CONCURRENT_STREAMS);
}
public static TripleHttp2FrameCodecBuilder forServer(int maxReservedStreams) {
return fromConnection(new DefaultHttp2Connection(true, maxReservedStreams));
}
public TripleHttp2FrameCodecBuilder customizeConnection(Consumer<Http2Connection> connectionCustomizer) {
Http2Connection connection = this.connection();
Assert.notNull(connection, "connection cannot be null.");
connectionCustomizer.accept(connection);
return this;
}
public TripleHttp2FrameCodecBuilder remoteFlowController(Http2RemoteFlowController remoteFlowController) {
return this.customizeConnection((connection) -> connection.remote().flowController(remoteFlowController));
}
public TripleHttp2FrameCodecBuilder localFlowController(Http2LocalFlowController localFlowController) {
return this.customizeConnection((connection) -> connection.local().flowController(localFlowController));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TriplePingPongHandler.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TriplePingPongHandler.java | /*
* 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.rpc.protocol.tri;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http2.DefaultHttp2PingFrame;
import io.netty.handler.codec.http2.Http2PingFrame;
import io.netty.handler.timeout.IdleStateEvent;
public class TriplePingPongHandler extends ChannelDuplexHandler {
private final long pingAckTimeout;
private ScheduledFuture<?> pingAckTimeoutFuture;
public TriplePingPongHandler(long pingAckTimeout) {
this.pingAckTimeout = pingAckTimeout;
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (!(msg instanceof Http2PingFrame) || pingAckTimeoutFuture == null) {
super.channelRead(ctx, msg);
return;
}
// cancel task when read anything, include http2 ping ack
pingAckTimeoutFuture.cancel(true);
pingAckTimeoutFuture = null;
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (!(evt instanceof IdleStateEvent)) {
ctx.fireUserEventTriggered(evt);
return;
}
ctx.writeAndFlush(new DefaultHttp2PingFrame(0));
if (pingAckTimeoutFuture == null) {
pingAckTimeoutFuture =
ctx.executor().schedule(new CloseChannelTask(ctx), pingAckTimeout, TimeUnit.MILLISECONDS);
}
// not null means last ping ack not received
}
private static class CloseChannelTask implements Runnable {
private final ChannelHandlerContext ctx;
public CloseChannelTask(ChannelHandlerContext ctx) {
this.ctx = ctx;
}
@Override
public void run() {
if (ctx.channel().isActive()) {
ctx.close();
}
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/GrpcHttp2Protocol.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/GrpcHttp2Protocol.java | /*
* 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.rpc.protocol.tri;
import org.apache.dubbo.common.extension.Activate;
@Activate
public class GrpcHttp2Protocol extends TripleHttp2Protocol {}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/SingleProtobufUtils.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/SingleProtobufUtils.java | /*
* 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.rpc.protocol.tri;
import org.apache.dubbo.common.utils.ConcurrentHashMapUtils;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import com.google.protobuf.BoolValue;
import com.google.protobuf.BytesValue;
import com.google.protobuf.DoubleValue;
import com.google.protobuf.Empty;
import com.google.protobuf.EnumValue;
import com.google.protobuf.ExtensionRegistryLite;
import com.google.protobuf.FloatValue;
import com.google.protobuf.Int32Value;
import com.google.protobuf.Int64Value;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.ListValue;
import com.google.protobuf.Message;
import com.google.protobuf.MessageLite;
import com.google.protobuf.Parser;
import com.google.protobuf.StringValue;
public class SingleProtobufUtils {
private static final ConcurrentHashMap<Class<?>, Message> INST_CACHE = new ConcurrentHashMap<>();
private static final ExtensionRegistryLite GLOBAL_REGISTRY = ExtensionRegistryLite.getEmptyRegistry();
private static final ConcurrentMap<Class<?>, SingleMessageMarshaller<?>> MARSHALLER_CACHE =
new ConcurrentHashMap<>();
static {
// Built-in types need to be registered in advance
marshaller(Empty.getDefaultInstance());
marshaller(BoolValue.getDefaultInstance());
marshaller(Int32Value.getDefaultInstance());
marshaller(Int64Value.getDefaultInstance());
marshaller(FloatValue.getDefaultInstance());
marshaller(DoubleValue.getDefaultInstance());
marshaller(BytesValue.getDefaultInstance());
marshaller(StringValue.getDefaultInstance());
marshaller(EnumValue.getDefaultInstance());
marshaller(ListValue.getDefaultInstance());
}
static boolean isSupported(Class<?> clazz) {
if (clazz == null) {
return false;
}
return MessageLite.class.isAssignableFrom(clazz);
}
public static <T extends MessageLite> void marshaller(T defaultInstance) {
MARSHALLER_CACHE.put(defaultInstance.getClass(), new SingleMessageMarshaller<>(defaultInstance));
}
@SuppressWarnings("all")
public static Message defaultInst(Class<?> clz) {
Message defaultInst = INST_CACHE.get(clz);
if (defaultInst != null) {
return defaultInst;
}
try {
defaultInst = (Message) clz.getMethod("getDefaultInstance").invoke(null);
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
throw new RuntimeException("Create default protobuf instance failed ", e);
}
INST_CACHE.put(clz, defaultInst);
return defaultInst;
}
@SuppressWarnings("all")
public static <T> Parser<T> getParser(Class<T> clz) {
Message defaultInst = defaultInst(clz);
return (Parser<T>) defaultInst.getParserForType();
}
public static <T> T deserialize(InputStream in, Class<T> clz) throws IOException {
if (!isSupported(clz)) {
throw new IllegalArgumentException("This serialization only support google protobuf messages, but the "
+ "actual input type is :" + clz.getName());
}
try {
return (T) getMarshaller(clz).parse(in);
} catch (InvalidProtocolBufferException e) {
throw new IOException(e);
}
}
public static void serialize(Object obj, OutputStream os) throws IOException {
final MessageLite msg = (MessageLite) obj;
msg.writeTo(os);
}
private static SingleMessageMarshaller<?> getMarshaller(Class<?> clz) {
return ConcurrentHashMapUtils.computeIfAbsent(MARSHALLER_CACHE, clz, k -> new SingleMessageMarshaller(k));
}
public static final class SingleMessageMarshaller<T extends MessageLite> {
private final Parser<T> parser;
private final T defaultInstance;
SingleMessageMarshaller(Class<T> clz) {
this.defaultInstance = (T) defaultInst(clz);
this.parser = (Parser<T>) defaultInstance.getParserForType();
}
SingleMessageMarshaller(T defaultInstance) {
this.defaultInstance = defaultInstance;
this.parser = (Parser<T>) defaultInstance.getParserForType();
}
public T parse(InputStream stream) throws InvalidProtocolBufferException {
return parser.parseFrom(stream, GLOBAL_REGISTRY);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/DefaultPackableMethodFactory.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/DefaultPackableMethodFactory.java | /*
* 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.rpc.protocol.tri;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.model.MethodDescriptor;
import org.apache.dubbo.rpc.model.PackableMethod;
import org.apache.dubbo.rpc.model.PackableMethodFactory;
public class DefaultPackableMethodFactory implements PackableMethodFactory {
@Override
public PackableMethod create(MethodDescriptor methodDescriptor, URL url, String contentType) {
return ReflectionPackableMethod.init(methodDescriptor, url);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ServletExchanger.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ServletExchanger.java | /*
* 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.rpc.protocol.tri;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.Configuration;
import org.apache.dubbo.rpc.Constants;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;
public final class ServletExchanger {
private static final AtomicReference<URL> url = new AtomicReference<>();
private static final AtomicReference<Integer> serverPort = new AtomicReference<>();
private static boolean ENABLED = false;
public static void init(Configuration configuration) {
ENABLED = configuration.getBoolean(Constants.H2_SETTINGS_SERVLET_ENABLED, false);
}
private ServletExchanger() {}
public static boolean isEnabled() {
return ENABLED;
}
public static void bind(URL url) {
ServletExchanger.url.compareAndSet(null, url);
}
public static void bindServerPort(int serverPort) {
ServletExchanger.serverPort.compareAndSet(null, serverPort);
}
public static URL getUrl() {
return Objects.requireNonNull(url.get(), "ServletExchanger not bound to triple protocol");
}
public static Integer getServerPort() {
return serverPort.get();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/RequestPath.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/RequestPath.java | /*
* 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.rpc.protocol.tri;
public final class RequestPath {
private final String path;
private final String stubPath;
private final String serviceInterface;
private final String methodName;
private RequestPath(String path, String stubPath, String serviceInterface, String methodName) {
this.path = path;
this.stubPath = stubPath;
this.serviceInterface = serviceInterface;
this.methodName = methodName;
}
// Request path pattern:
// '{interfaceName}/{methodName}' or '{contextPath}/{interfaceName}/{methodName}'
// └─── path ────┘ └─ method ─┘ └────────── path ───────────┘ └─ method ─┘
public static RequestPath parse(String fullPath) {
int i = fullPath.lastIndexOf('/');
if (i < 1) {
return null;
}
String path = fullPath.substring(1, i);
int j = path.lastIndexOf('/');
if (j == -1) {
return new RequestPath(path, fullPath, path, fullPath.substring(i + 1));
} else {
return new RequestPath(path, fullPath.substring(j), path.substring(j + 1), fullPath.substring(i + 1));
}
}
public static String toFullPath(String path, String methodName) {
return '/' + path + '/' + methodName;
}
public String getPath() {
return path;
}
public String getStubPath() {
return stubPath;
}
public String getServiceInterface() {
return serviceInterface;
}
public String getMethodName() {
return methodName;
}
@Override
public String toString() {
return path + '/' + methodName;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/GrpcProtocol.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/GrpcProtocol.java | /*
* 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.rpc.protocol.tri;
import org.apache.dubbo.rpc.model.FrameworkModel;
public class GrpcProtocol extends TripleProtocol {
public GrpcProtocol(FrameworkModel frameworkModel) {
super(frameworkModel);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ClientStreamObserver.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ClientStreamObserver.java | /*
* 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.rpc.protocol.tri;
import org.apache.dubbo.common.stream.StreamObserver;
import org.apache.dubbo.rpc.protocol.tri.observer.CallStreamObserver;
public interface ClientStreamObserver<T> extends CallStreamObserver<T> {
/**
* Swaps to manual flow control where no message will be delivered to {@link
* StreamObserver#onNext(Object)} unless it is {@link #request request()}ed. Since {@code
* request()} may not be called before the call is started, a number of initial requests may be
* specified.
*/
default void disableAutoRequest() {
disableAutoFlowControl();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ExceptionUtils.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ExceptionUtils.java | /*
* 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.rpc.protocol.tri;
import org.apache.dubbo.common.logger.Level;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.remoting.http12.HttpStatus;
import org.apache.dubbo.remoting.http12.exception.HttpStatusException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.UndeclaredThrowableException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ExecutionException;
public class ExceptionUtils {
public static String getStackTrace(final Throwable throwable) {
final StringWriter sw = new StringWriter();
final PrintWriter pw = new PrintWriter(sw, true);
throwable.printStackTrace(pw);
return sw.getBuffer().toString();
}
public static String getStackFrameString(List<String> stackFrameList) {
if (CollectionUtils.isEmpty(stackFrameList)) {
return "";
}
StringBuilder stringBuilder = new StringBuilder();
for (String s : stackFrameList) {
stringBuilder.append(s).append("\n");
}
return stringBuilder.toString();
}
public static String[] getStackFrames(final Throwable throwable) {
if (throwable == null) {
return new String[0];
}
return getStackFrames(getStackTrace(throwable));
}
static String[] getStackFrames(final String stackTrace) {
final String linebreak = System.lineSeparator();
final StringTokenizer frames = new StringTokenizer(stackTrace, linebreak);
final List<String> list = new ArrayList<>();
while (frames.hasMoreTokens()) {
list.add(frames.nextToken());
}
return list.toArray(new String[0]);
}
public static List<String> getStackFrameList(final Throwable t, int maxDepth) {
final String stackTrace = getStackTrace(t);
final String linebreak = System.lineSeparator();
final StringTokenizer frames = new StringTokenizer(stackTrace, linebreak);
final List<String> list = new ArrayList<>();
for (int i = 0; i < maxDepth && frames.hasMoreTokens(); i++) {
list.add(frames.nextToken());
}
return list;
}
public static List<String> getStackFrameList(final Throwable t) {
return getStackFrameList(t, Integer.MAX_VALUE);
}
public static Level resolveLogLevel(final Throwable t) {
if (t instanceof HttpStatusException) {
int httpStatusCode = ((HttpStatusException) t).getStatusCode();
if (httpStatusCode < HttpStatus.BAD_REQUEST.getCode()) {
return TripleProtocol.VERBOSE_ENABLED ? Level.INFO : Level.DEBUG;
}
if (httpStatusCode < HttpStatus.INTERNAL_SERVER_ERROR.getCode()) {
return Level.INFO;
}
}
return Level.ERROR;
}
/**
* Wrap as runtime exception
*/
public static RuntimeException wrap(Throwable t) {
while (true) {
if (t instanceof UndeclaredThrowableException) {
t = ((UndeclaredThrowableException) t).getUndeclaredThrowable();
} else if (t instanceof InvocationTargetException) {
t = ((InvocationTargetException) t).getTargetException();
} else if (t instanceof CompletionException || t instanceof ExecutionException) {
Throwable cause = t.getCause();
if (cause == t) {
break;
}
t = cause;
} else {
break;
}
}
return t instanceof RuntimeException ? (RuntimeException) t : new ThrowableWrapper(t);
}
/**
* Unwrap the wrapped exception
*/
public static Throwable unwrap(Throwable t) {
while (true) {
if (t instanceof ThrowableWrapper) {
t = ((ThrowableWrapper) t).getOriginal();
} else if (t instanceof UndeclaredThrowableException) {
t = ((UndeclaredThrowableException) t).getUndeclaredThrowable();
} else if (t instanceof InvocationTargetException) {
t = ((InvocationTargetException) t).getTargetException();
} else if (t instanceof CompletionException || t instanceof ExecutionException) {
Throwable cause = t.getCause();
if (cause == t) {
break;
}
t = cause;
} else {
break;
}
}
return t;
}
public static String buildVerboseMessage(Throwable t) {
StringBuilder sb = new StringBuilder(256);
t = unwrap(t);
Throwable parent;
String before = null;
do {
String msg = t.getMessage();
String className = t.getClass().getName();
if (before != null) {
if (!before.startsWith(className) && !before.equals(msg)) {
sb.append(": ").append(before);
}
sb.append(" -> ");
}
sb.append(className);
before = msg;
parent = t;
t = t.getCause();
} while (t != null && t != parent);
if (before != null) {
sb.append(": ").append(before);
}
sb.append("\n -> Stack traces:");
StackTraceElement[] elements = parent.getStackTrace();
for (int i = 0, len = elements.length; i < 10 && i < len; i++) {
sb.append("\n at ").append(elements[i]);
}
return sb.toString();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/DescriptorUtils.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/DescriptorUtils.java | /*
* 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.rpc.protocol.tri;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.io.StreamUtils;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.remoting.http12.exception.UnimplementedException;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.model.MethodDescriptor;
import org.apache.dubbo.rpc.model.ProviderModel;
import org.apache.dubbo.rpc.model.ServiceDescriptor;
import org.apache.dubbo.rpc.protocol.tri.TripleCustomerProtocolWrapper.TripleRequestWrapper;
import org.apache.dubbo.rpc.service.ServiceDescriptorInternalCache;
import org.apache.dubbo.rpc.stub.StubSuppliers;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
/**
* The MetaUtils provides utility methods for working with service descriptors and method descriptors.
*/
public final class DescriptorUtils {
private DescriptorUtils() {}
public static ServiceDescriptor findServiceDescriptor(Invoker<?> invoker, String serviceName, boolean hasStub)
throws UnimplementedException {
ServiceDescriptor result;
if (hasStub) {
result = getStubServiceDescriptor(invoker.getUrl(), serviceName);
} else {
result = getReflectionServiceDescriptor(invoker.getUrl());
}
if (result == null) {
throw new UnimplementedException("service:" + serviceName);
}
return result;
}
public static ServiceDescriptor getStubServiceDescriptor(URL url, String serviceName) {
ServiceDescriptor serviceDescriptor;
if (url.getServiceModel() != null) {
serviceDescriptor = url.getServiceModel().getServiceModel();
} else {
serviceDescriptor = StubSuppliers.getServiceDescriptor(serviceName);
}
return serviceDescriptor;
}
public static ServiceDescriptor getReflectionServiceDescriptor(URL url) {
ProviderModel providerModel = (ProviderModel) url.getServiceModel();
if (providerModel == null || providerModel.getServiceModel() == null) {
return null;
}
return providerModel.getServiceModel();
}
public static MethodDescriptor findMethodDescriptor(
ServiceDescriptor serviceDescriptor, String originalMethodName, boolean hasStub)
throws UnimplementedException {
MethodDescriptor result;
if (hasStub) {
result = serviceDescriptor.getMethods(originalMethodName).get(0);
} else {
result = findReflectionMethodDescriptor(serviceDescriptor, originalMethodName);
}
return result;
}
public static MethodDescriptor findReflectionMethodDescriptor(
ServiceDescriptor serviceDescriptor, String methodName) {
MethodDescriptor methodDescriptor = null;
if (isGeneric(methodName)) {
// There should be one and only one
methodDescriptor = ServiceDescriptorInternalCache.genericService()
.getMethods(methodName)
.get(0);
} else if (isEcho(methodName)) {
// There should be one and only one
return ServiceDescriptorInternalCache.echoService()
.getMethods(methodName)
.get(0);
} else {
List<MethodDescriptor> methodDescriptors = serviceDescriptor.getMethods(methodName);
if (CollectionUtils.isEmpty(methodDescriptors)) {
return null;
}
// In most cases there is only one method
if (methodDescriptors.size() == 1) {
methodDescriptor = methodDescriptors.get(0);
}
// generated unary method ,use unary type
// Response foo(Request)
// void foo(Request,StreamObserver<Response>)
if (methodDescriptors.size() == 2) {
if (methodDescriptors.get(1).getRpcType() == MethodDescriptor.RpcType.SERVER_STREAM) {
methodDescriptor = methodDescriptors.get(0);
} else if (methodDescriptors.get(0).getRpcType() == MethodDescriptor.RpcType.SERVER_STREAM) {
methodDescriptor = methodDescriptors.get(1);
}
}
}
return methodDescriptor;
}
public static MethodDescriptor findTripleMethodDescriptor(
ServiceDescriptor serviceDescriptor, String methodName, InputStream rawMessage) throws IOException {
MethodDescriptor methodDescriptor = findReflectionMethodDescriptor(serviceDescriptor, methodName);
if (methodDescriptor == null) {
byte[] data = StreamUtils.readBytes(rawMessage);
List<MethodDescriptor> methodDescriptors = serviceDescriptor.getMethods(methodName);
TripleRequestWrapper request = TripleRequestWrapper.parseFrom(data);
String[] paramTypes = request.getArgTypes().toArray(new String[0]);
// wrapper mode the method can overload so maybe list
for (MethodDescriptor descriptor : methodDescriptors) {
// params type is array
if (Arrays.equals(descriptor.getCompatibleParamSignatures(), paramTypes)) {
methodDescriptor = descriptor;
break;
}
}
if (methodDescriptor == null) {
throw new UnimplementedException("method:" + methodName);
}
rawMessage.reset();
}
return methodDescriptor;
}
private static boolean isGeneric(String methodName) {
return CommonConstants.$INVOKE.equals(methodName) || CommonConstants.$INVOKE_ASYNC.equals(methodName);
}
private static boolean isEcho(String methodName) {
return CommonConstants.$ECHO.equals(methodName);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleCustomerProtocolWrapper.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleCustomerProtocolWrapper.java | /*
* 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.rpc.protocol.tri;
import org.apache.dubbo.common.utils.Assert;
import org.apache.dubbo.common.utils.CollectionUtils;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class TripleCustomerProtocolWrapper {
static int makeTag(int fieldNumber, int wireType) {
return fieldNumber << 3 | wireType;
}
public static byte[] varIntEncode(int val) {
byte[] data = new byte[varIntComputeLength(val)];
for (int i = 0; i < data.length - 1; i++) {
data[i] = (byte) ((val & 0x7F) | 0x80);
val = val >>> 7;
}
data[data.length - 1] = (byte) (val);
return data;
}
public static int varIntComputeLength(int val) {
if (val == 0) {
return 1;
}
int length = 0;
while (val != 0) {
val = val >>> 7;
length++;
}
return length;
}
public static int readRawVarint32(ByteBuffer byteBuffer) {
int val = 0;
int currentPosition = byteBuffer.position();
int varIntLength = 1;
byte currentByte = byteBuffer.get();
while ((currentByte & 0XF0) >> 7 == 1) {
varIntLength++;
currentByte = byteBuffer.get();
}
for (int index = currentPosition + varIntLength - 1; index >= currentPosition; index--) {
val = val << 7;
val = val | (byteBuffer.get(index) & 0x7F);
}
byteBuffer.position(currentPosition + varIntLength);
return val;
}
public static int extractFieldNumFromTag(int tag) {
return tag >> 3;
}
public static int extractWireTypeFromTag(int tag) {
return tag & 0X07;
}
public static final class TripleResponseWrapper {
private String serializeType;
private byte[] data;
private String type;
public String getSerializeType() {
return serializeType;
}
public byte[] getData() {
return data;
}
public String getType() {
return type;
}
public static TripleResponseWrapper parseFrom(byte[] data) {
TripleResponseWrapper tripleResponseWrapper = new TripleResponseWrapper();
ByteBuffer byteBuffer = ByteBuffer.wrap(data);
while (byteBuffer.position() < byteBuffer.limit()) {
int tag = readRawVarint32(byteBuffer);
int fieldNum = extractFieldNumFromTag(tag);
int wireType = extractWireTypeFromTag(tag);
if (wireType != 2) {
throw new RuntimeException(
String.format("unexpected wireType, expect %d realType %d", 2, wireType));
}
if (fieldNum == 1) {
int serializeTypeLength = readRawVarint32(byteBuffer);
byte[] serializeTypeBytes = new byte[serializeTypeLength];
byteBuffer.get(serializeTypeBytes, 0, serializeTypeLength);
tripleResponseWrapper.serializeType = new String(serializeTypeBytes);
} else if (fieldNum == 2) {
int dataLength = readRawVarint32(byteBuffer);
byte[] dataBytes = new byte[dataLength];
byteBuffer.get(dataBytes, 0, dataLength);
tripleResponseWrapper.data = dataBytes;
} else if (fieldNum == 3) {
int typeLength = readRawVarint32(byteBuffer);
byte[] typeBytes = new byte[typeLength];
byteBuffer.get(typeBytes, 0, typeLength);
tripleResponseWrapper.type = new String(typeBytes);
} else {
throw new RuntimeException("fieldNum should in (1,2,3)");
}
}
return tripleResponseWrapper;
}
public byte[] toByteArray() {
int totalSize = 0;
int serializeTypeTag = makeTag(1, 2);
byte[] serializeTypeTagBytes = varIntEncode(serializeTypeTag);
byte[] serializeTypeBytes = serializeType.getBytes(StandardCharsets.UTF_8);
byte[] serializeTypeLengthVarIntEncodeBytes = varIntEncode(serializeTypeBytes.length);
totalSize += serializeTypeTagBytes.length
+ serializeTypeLengthVarIntEncodeBytes.length
+ serializeTypeBytes.length;
int dataTag = makeTag(2, 2);
if (data != null) {
totalSize += varIntComputeLength(dataTag) + varIntComputeLength(data.length) + data.length;
}
int typeTag = makeTag(3, 2);
byte[] typeTagBytes = varIntEncode(typeTag);
byte[] typeBytes = type.getBytes(StandardCharsets.UTF_8);
byte[] typeLengthVarIntEncodeBytes = varIntEncode(typeBytes.length);
totalSize += typeTagBytes.length + typeLengthVarIntEncodeBytes.length + typeBytes.length;
ByteBuffer byteBuffer = ByteBuffer.allocate(totalSize);
byteBuffer
.put(serializeTypeTagBytes)
.put(serializeTypeLengthVarIntEncodeBytes)
.put(serializeTypeBytes);
if (data != null) {
byteBuffer
.put(varIntEncode(dataTag))
.put(varIntEncode(data.length))
.put(data);
}
byteBuffer.put(typeTagBytes).put(typeLengthVarIntEncodeBytes).put(typeBytes);
return byteBuffer.array();
}
public static final class Builder {
private String serializeType;
private byte[] data;
private String type;
public Builder setSerializeType(String serializeType) {
this.serializeType = serializeType;
return this;
}
public Builder setData(byte[] data) {
this.data = data;
return this;
}
public Builder setType(String type) {
this.type = type;
return this;
}
public static Builder newBuilder() {
return new Builder();
}
public TripleResponseWrapper build() {
Assert.notNull(serializeType, "serializeType can not be null");
Assert.notNull(type, "type can not be null");
TripleResponseWrapper tripleResponseWrapper = new TripleResponseWrapper();
tripleResponseWrapper.data = this.data;
tripleResponseWrapper.serializeType = this.serializeType;
tripleResponseWrapper.type = this.type;
return tripleResponseWrapper;
}
}
}
public static final class TripleRequestWrapper {
private String serializeType;
private List<byte[]> args;
private List<String> argTypes;
public String getSerializeType() {
return serializeType;
}
public List<byte[]> getArgs() {
return args;
}
public List<String> getArgTypes() {
return argTypes;
}
public TripleRequestWrapper() {}
public static TripleRequestWrapper parseFrom(byte[] data) {
TripleRequestWrapper tripleRequestWrapper = new TripleRequestWrapper();
ByteBuffer byteBuffer = ByteBuffer.wrap(data);
tripleRequestWrapper.args = new ArrayList<>();
tripleRequestWrapper.argTypes = new ArrayList<>();
while (byteBuffer.position() < byteBuffer.limit()) {
int tag = readRawVarint32(byteBuffer);
int fieldNum = extractFieldNumFromTag(tag);
int wireType = extractWireTypeFromTag(tag);
if (wireType != 2) {
throw new RuntimeException(
String.format("unexpected wireType, expect %d realType %d", 2, wireType));
}
if (fieldNum == 1) {
int serializeTypeLength = readRawVarint32(byteBuffer);
byte[] serializeTypeBytes = new byte[serializeTypeLength];
byteBuffer.get(serializeTypeBytes, 0, serializeTypeLength);
tripleRequestWrapper.serializeType = new String(serializeTypeBytes);
} else if (fieldNum == 2) {
int argLength = readRawVarint32(byteBuffer);
byte[] argBytes = new byte[argLength];
byteBuffer.get(argBytes, 0, argLength);
tripleRequestWrapper.args.add(argBytes);
} else if (fieldNum == 3) {
int argTypeLength = readRawVarint32(byteBuffer);
byte[] argTypeBytes = new byte[argTypeLength];
byteBuffer.get(argTypeBytes, 0, argTypeLength);
tripleRequestWrapper.argTypes.add(new String(argTypeBytes));
} else {
throw new RuntimeException("fieldNum should in (1,2,3)");
}
}
return tripleRequestWrapper;
}
public byte[] toByteArray() {
int totalSize = 0;
int serializeTypeTag = makeTag(1, 2);
byte[] serializeTypeTagBytes = varIntEncode(serializeTypeTag);
byte[] serializeTypeBytes = serializeType.getBytes(StandardCharsets.UTF_8);
byte[] serializeTypeLengthVarIntEncodeBytes = varIntEncode(serializeTypeBytes.length);
totalSize += serializeTypeTagBytes.length
+ serializeTypeLengthVarIntEncodeBytes.length
+ serializeTypeBytes.length;
int argTypeTag = makeTag(3, 2);
if (CollectionUtils.isNotEmpty(argTypes)) {
totalSize += varIntComputeLength(argTypeTag) * argTypes.size();
for (String argType : argTypes) {
byte[] argTypeBytes = argType.getBytes(StandardCharsets.UTF_8);
totalSize += argTypeBytes.length + varIntComputeLength(argTypeBytes.length);
}
}
int argTag = makeTag(2, 2);
if (CollectionUtils.isNotEmpty(args)) {
totalSize += varIntComputeLength(argTag) * args.size();
for (byte[] arg : args) {
totalSize += arg.length + varIntComputeLength(arg.length);
}
}
ByteBuffer byteBuffer = ByteBuffer.allocate(totalSize);
byteBuffer
.put(serializeTypeTagBytes)
.put(serializeTypeLengthVarIntEncodeBytes)
.put(serializeTypeBytes);
if (CollectionUtils.isNotEmpty(args)) {
byte[] argTagBytes = varIntEncode(argTag);
for (byte[] arg : args) {
byteBuffer.put(argTagBytes).put(varIntEncode(arg.length)).put(arg);
}
}
if (CollectionUtils.isNotEmpty(argTypes)) {
byte[] argTypeTagBytes = varIntEncode(argTypeTag);
for (String argType : argTypes) {
byte[] argTypeBytes = argType.getBytes(StandardCharsets.UTF_8);
byteBuffer
.put(argTypeTagBytes)
.put(varIntEncode(argTypeBytes.length))
.put(argTypeBytes);
}
}
return byteBuffer.array();
}
public static final class Builder {
private String serializeType;
private final List<byte[]> args = new ArrayList<>();
private final List<String> argTypes = new ArrayList<>();
public Builder setSerializeType(String serializeType) {
this.serializeType = serializeType;
return this;
}
public Builder addArgTypes(String argsType) {
Assert.notEmptyString(argsType, "argsType cannot be empty.");
argTypes.add(argsType);
return this;
}
public Builder addArgs(byte[] arg) {
args.add(arg);
return this;
}
public static Builder newBuilder() {
return new Builder();
}
public TripleRequestWrapper build() {
Assert.notNull(serializeType, "serializeType can not be null");
TripleRequestWrapper tripleRequestWrapper = new TripleRequestWrapper();
tripleRequestWrapper.args = this.args;
tripleRequestWrapper.argTypes = this.argTypes;
tripleRequestWrapper.serializeType = this.serializeType;
return tripleRequestWrapper;
}
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof TripleRequestWrapper)) {
return false;
}
TripleRequestWrapper that = (TripleRequestWrapper) o;
return Objects.equals(serializeType, that.serializeType)
&& Objects.equals(args, that.args)
&& Objects.equals(argTypes, that.argTypes);
}
@Override
public int hashCode() {
return Objects.hash(serializeType, args, argTypes);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TriHttp2RemoteFlowController.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TriHttp2RemoteFlowController.java | /*
* Copyright 2014 The Netty Project
*
* The Netty Project 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.rpc.protocol.tri;
import org.apache.dubbo.config.nested.TripleConfig;
import java.util.ArrayDeque;
import java.util.Deque;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http2.Http2Connection;
import io.netty.handler.codec.http2.Http2ConnectionAdapter;
import io.netty.handler.codec.http2.Http2Error;
import io.netty.handler.codec.http2.Http2Exception;
import io.netty.handler.codec.http2.Http2RemoteFlowController;
import io.netty.handler.codec.http2.Http2Stream;
import io.netty.handler.codec.http2.Http2StreamVisitor;
import io.netty.handler.codec.http2.StreamByteDistributor;
import io.netty.handler.codec.http2.WeightedFairQueueByteDistributor;
import io.netty.util.internal.UnstableApi;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import static io.netty.handler.codec.http2.Http2CodecUtil.MAX_WEIGHT;
import static io.netty.handler.codec.http2.Http2CodecUtil.MIN_WEIGHT;
import static io.netty.handler.codec.http2.Http2Error.FLOW_CONTROL_ERROR;
import static io.netty.handler.codec.http2.Http2Error.INTERNAL_ERROR;
import static io.netty.handler.codec.http2.Http2Error.STREAM_CLOSED;
import static io.netty.handler.codec.http2.Http2Exception.streamError;
import static io.netty.handler.codec.http2.Http2Stream.State.HALF_CLOSED_LOCAL;
import static io.netty.util.internal.ObjectUtil.checkNotNull;
import static io.netty.util.internal.ObjectUtil.checkPositiveOrZero;
import static java.lang.Math.max;
import static java.lang.Math.min;
/**
* This design is learning from {@see io.netty.handler.codec.http2.DefaultHttp2RemoteFlowController} which is in Netty.
*/
@UnstableApi
public class TriHttp2RemoteFlowController implements Http2RemoteFlowController {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(TriHttp2RemoteFlowController.class);
private static final int MIN_WRITABLE_CHUNK = 32 * 1024;
private final Http2Connection connection;
private final Http2Connection.PropertyKey stateKey;
private final StreamByteDistributor streamByteDistributor;
private final FlowState connectionState;
private int initialWindowSize;
private WritabilityMonitor monitor;
private ChannelHandlerContext ctx;
public TriHttp2RemoteFlowController(Http2Connection connection, TripleConfig config) {
this(connection, (Listener) null, config);
}
public TriHttp2RemoteFlowController(
Http2Connection connection, StreamByteDistributor streamByteDistributor, TripleConfig config) {
this(connection, streamByteDistributor, null, config);
}
public TriHttp2RemoteFlowController(Http2Connection connection, final Listener listener, TripleConfig config) {
this(connection, new WeightedFairQueueByteDistributor(connection), listener, config);
}
public TriHttp2RemoteFlowController(
Http2Connection connection,
StreamByteDistributor streamByteDistributor,
final Listener listener,
TripleConfig config) {
this.connection = checkNotNull(connection, "connection");
this.streamByteDistributor = checkNotNull(streamByteDistributor, "streamWriteDistributor");
this.initialWindowSize = config.getConnectionInitialWindowSizeOrDefault();
// Add a flow state for the connection.
stateKey = connection.newKey();
connectionState = new FlowState(connection.connectionStream());
connection.connectionStream().setProperty(stateKey, connectionState);
// Monitor may depend upon connectionState, and so initialize after connectionState
listener(listener);
monitor.windowSize(connectionState, initialWindowSize);
// Register for notification of new streams.
connection.addListener(new Http2ConnectionAdapter() {
@Override
public void onStreamAdded(Http2Stream stream) {
// If the stream state is not open then the stream is not yet eligible for flow controlled frames and
// only requires the ReducedFlowState. Otherwise the full amount of memory is required.
stream.setProperty(stateKey, new FlowState(stream));
}
@Override
public void onStreamActive(Http2Stream stream) {
// If the object was previously created, but later activated then we have to ensure the proper
// initialWindowSize is used.
monitor.windowSize(state(stream), initialWindowSize);
}
@Override
public void onStreamClosed(Http2Stream stream) {
// Any pending frames can never be written, cancel and
// write errors for any pending frames.
state(stream).cancel(STREAM_CLOSED, null);
}
@Override
public void onStreamHalfClosed(Http2Stream stream) {
if (HALF_CLOSED_LOCAL == stream.state()) {
/*
* When this method is called there should not be any
* pending frames left if the API is used correctly. However,
* it is possible that a erroneous application can sneak
* in a frame even after having already written a frame with the
* END_STREAM flag set, as the stream state might not transition
* immediately to HALF_CLOSED_LOCAL / CLOSED due to flow control
* delaying the write.
*
* This is to cancel any such illegal writes.
*/
state(stream).cancel(STREAM_CLOSED, null);
}
}
});
}
/**
* {@inheritDoc}
* <p>
* Any queued {@link FlowControlled} objects will be sent.
*/
@Override
public void channelHandlerContext(ChannelHandlerContext ctx) throws Http2Exception {
this.ctx = checkNotNull(ctx, "ctx");
// Writing the pending bytes will not check writability change and instead a writability change notification
// to be provided by an explicit call.
channelWritabilityChanged();
// Don't worry about cleaning up queued frames here if ctx is null. It is expected that all streams will be
// closed and the queue cleanup will occur when the stream state transitions occur.
// If any frames have been queued up, we should send them now that we have a channel context.
if (isChannelWritable()) {
writePendingBytes();
}
}
@Override
public ChannelHandlerContext channelHandlerContext() {
return ctx;
}
@Override
public void initialWindowSize(int newWindowSize) throws Http2Exception {
assert ctx == null || ctx.executor().inEventLoop();
monitor.initialWindowSize(newWindowSize);
}
@Override
public int initialWindowSize() {
return initialWindowSize;
}
@Override
public int windowSize(Http2Stream stream) {
return state(stream).windowSize();
}
@Override
public boolean isWritable(Http2Stream stream) {
return monitor.isWritable(state(stream));
}
@Override
public void channelWritabilityChanged() throws Http2Exception {
monitor.channelWritabilityChange();
}
@Override
public void updateDependencyTree(int childStreamId, int parentStreamId, short weight, boolean exclusive) {
// It is assumed there are all validated at a higher level. For example in the Http2FrameReader.
assert weight >= MIN_WEIGHT && weight <= MAX_WEIGHT : "Invalid weight";
assert childStreamId != parentStreamId : "A stream cannot depend on itself";
assert childStreamId > 0 && parentStreamId >= 0 : "childStreamId must be > 0. parentStreamId must be >= 0.";
streamByteDistributor.updateDependencyTree(childStreamId, parentStreamId, weight, exclusive);
}
private boolean isChannelWritable() {
return ctx != null && isChannelWritable0();
}
private boolean isChannelWritable0() {
return ctx.channel().isWritable();
}
@Override
public void listener(Listener listener) {
monitor = listener == null ? new WritabilityMonitor() : new ListenerWritabilityMonitor(listener);
}
@Override
public void incrementWindowSize(Http2Stream stream, int delta) throws Http2Exception {
assert ctx == null || ctx.executor().inEventLoop();
monitor.incrementWindowSize(state(stream), delta);
}
@Override
public void addFlowControlled(Http2Stream stream, FlowControlled frame) {
// The context can be null assuming the frame will be queued and send later when the context is set.
assert ctx == null || ctx.executor().inEventLoop();
checkNotNull(frame, "frame");
try {
monitor.enqueueFrame(state(stream), frame);
} catch (Throwable t) {
frame.error(ctx, t);
}
}
@Override
public boolean hasFlowControlled(Http2Stream stream) {
return state(stream).hasFrame();
}
private FlowState state(Http2Stream stream) {
return (FlowState) stream.getProperty(stateKey);
}
/**
* Returns the flow control window for the entire connection.
*/
private int connectionWindowSize() {
return connectionState.windowSize();
}
private int minUsableChannelBytes() {
// The current allocation algorithm values "fairness" and doesn't give any consideration to "goodput". It
// is possible that 1 byte will be allocated to many streams. In an effort to try to make "goodput"
// reasonable with the current allocation algorithm we have this "cheap" check up front to ensure there is
// an "adequate" amount of connection window before allocation is attempted. This is not foolproof as if the
// number of streams is >= this minimal number then we may still have the issue, but the idea is to narrow the
// circumstances in which this can happen without rewriting the allocation algorithm.
return max(ctx.channel().config().getWriteBufferLowWaterMark(), MIN_WRITABLE_CHUNK);
}
private int maxUsableChannelBytes() {
// If the channel isWritable, allow at least minUsableChannelBytes.
int channelWritableBytes = (int) min(Integer.MAX_VALUE, ctx.channel().bytesBeforeUnwritable());
int usableBytes = channelWritableBytes > 0 ? max(channelWritableBytes, minUsableChannelBytes()) : 0;
// Clip the usable bytes by the connection window.
return min(connectionState.windowSize(), usableBytes);
}
/**
* The amount of bytes that can be supported by underlying {@link io.netty.channel.Channel} without
* queuing "too-much".
*/
private int writableBytes() {
return min(connectionWindowSize(), maxUsableChannelBytes());
}
@Override
public void writePendingBytes() throws Http2Exception {
monitor.writePendingBytes();
}
/**
* The remote flow control state for a single stream.
*/
private final class FlowState implements StreamByteDistributor.StreamState {
private final Http2Stream stream;
private final Deque<FlowControlled> pendingWriteQueue;
private int window;
private long pendingBytes;
private boolean markedWritable;
/**
* Set to true while a frame is being written, false otherwise.
*/
private boolean writing;
/**
* Set to true if cancel() was called.
*/
private boolean cancelled;
FlowState(Http2Stream stream) {
this.stream = stream;
pendingWriteQueue = new ArrayDeque<>(2);
}
/**
* Determine if the stream associated with this object is writable.
* @return {@code true} if the stream associated with this object is writable.
*/
boolean isWritable() {
return windowSize() > pendingBytes() && !cancelled;
}
/**
* The stream this state is associated with.
*/
@Override
public Http2Stream stream() {
return stream;
}
/**
* Returns the parameter from the last call to {@link #markedWritability(boolean)}.
*/
boolean markedWritability() {
return markedWritable;
}
/**
* Save the state of writability.
*/
void markedWritability(boolean isWritable) {
this.markedWritable = isWritable;
}
@Override
public int windowSize() {
return window;
}
/**
* Reset the window size for this stream.
*/
void windowSize(int initialWindowSize) {
window = initialWindowSize;
}
/**
* Write the allocated bytes for this stream.
* @return the number of bytes written for a stream or {@code -1} if no write occurred.
*/
int writeAllocatedBytes(int allocated) {
final int initialAllocated = allocated;
int writtenBytes;
// In case an exception is thrown we want to remember it and pass it to cancel(Throwable).
Throwable cause = null;
FlowControlled frame;
try {
assert !writing;
writing = true;
// Write the remainder of frames that we are allowed to
boolean writeOccurred = false;
while (!cancelled && (frame = peek()) != null) {
int maxBytes = min(allocated, writableWindow());
if (maxBytes <= 0 && frame.size() > 0) {
// The frame still has data, but the amount of allocated bytes has been exhausted.
// Don't write needless empty frames.
break;
}
writeOccurred = true;
int initialFrameSize = frame.size();
try {
frame.write(ctx, max(0, maxBytes));
if (frame.size() == 0) {
// This frame has been fully written, remove this frame and notify it.
// Since we remove this frame first, we're guaranteed that its error
// method will not be called when we call cancel.
pendingWriteQueue.remove();
frame.writeComplete();
}
} finally {
// Decrement allocated by how much was actually written.
allocated -= initialFrameSize - frame.size();
}
}
if (!writeOccurred) {
// Either there was no frame, or the amount of allocated bytes has been exhausted.
return -1;
}
} catch (Throwable t) {
// Mark the state as cancelled, we'll clear the pending queue via cancel() below.
cancelled = true;
cause = t;
} finally {
writing = false;
// Make sure we always decrement the flow control windows
// by the bytes written.
writtenBytes = initialAllocated - allocated;
decrementPendingBytes(writtenBytes, false);
decrementFlowControlWindow(writtenBytes);
// If a cancellation occurred while writing, call cancel again to
// clear and error all of the pending writes.
if (cancelled) {
cancel(INTERNAL_ERROR, cause);
}
// does not check overflow anymore: Let receiver continue receiving the pending bytes.
}
return writtenBytes;
}
/**
* Increments the flow control window for this stream by the given delta and returns the new value.
*/
int incrementStreamWindow(int delta) throws Http2Exception {
if (delta > 0 && Integer.MAX_VALUE - delta < window) {
throw streamError(stream.id(), FLOW_CONTROL_ERROR, "Window size overflow for stream: %d", stream.id());
}
window += delta;
streamByteDistributor.updateStreamableBytes(this);
return window;
}
/**
* Returns the maximum writable window (minimum of the stream and connection windows).
*/
private int writableWindow() {
return min(window, connectionWindowSize());
}
@Override
public long pendingBytes() {
return pendingBytes;
}
/**
* Adds the {@code frame} to the pending queue and increments the pending byte count.
*/
void enqueueFrame(FlowControlled frame) {
FlowControlled last = pendingWriteQueue.peekLast();
if (last == null) {
enqueueFrameWithoutMerge(frame);
return;
}
int lastSize = last.size();
if (last.merge(ctx, frame)) {
incrementPendingBytes(last.size() - lastSize, true);
return;
}
enqueueFrameWithoutMerge(frame);
}
private void enqueueFrameWithoutMerge(FlowControlled frame) {
pendingWriteQueue.offer(frame);
// This must be called after adding to the queue in order so that hasFrame() is
// updated before updating the stream state.
incrementPendingBytes(frame.size(), true);
}
@Override
public boolean hasFrame() {
return !pendingWriteQueue.isEmpty();
}
/**
* Returns the head of the pending queue, or {@code null} if empty.
*/
private FlowControlled peek() {
return pendingWriteQueue.peek();
}
/**
* Clears the pending queue and writes errors for each remaining frame.
* @param error the {@link Http2Error} to use.
* @param cause the {@link Throwable} that caused this method to be invoked.
*/
void cancel(Http2Error error, Throwable cause) {
cancelled = true;
// Ensure that the queue can't be modified while we are writing.
if (writing) {
return;
}
FlowControlled frame = pendingWriteQueue.poll();
if (frame != null) {
// Only create exception once and reuse to reduce overhead of filling in the stacktrace.
final Http2Exception exception =
streamError(stream.id(), error, cause, "Stream closed before write could take place");
do {
writeError(frame, exception);
frame = pendingWriteQueue.poll();
} while (frame != null);
}
streamByteDistributor.updateStreamableBytes(this);
monitor.stateCancelled(this);
}
/**
* Increments the number of pending bytes for this node and optionally updates the
* {@link StreamByteDistributor}.
*/
private void incrementPendingBytes(int numBytes, boolean updateStreamableBytes) {
pendingBytes += numBytes;
monitor.incrementPendingBytes(numBytes);
if (updateStreamableBytes) {
streamByteDistributor.updateStreamableBytes(this);
}
}
/**
* If this frame is in the pending queue, decrements the number of pending bytes for the stream.
*/
private void decrementPendingBytes(int bytes, boolean updateStreamableBytes) {
incrementPendingBytes(-bytes, updateStreamableBytes);
}
/**
* Decrement the per stream and connection flow control window by {@code bytes}.
*/
private void decrementFlowControlWindow(int bytes) {
try {
int negativeBytes = -bytes;
connectionState.incrementStreamWindow(negativeBytes);
incrementStreamWindow(negativeBytes);
} catch (Http2Exception e) {
// Should never get here since we're decrementing.
throw new IllegalStateException("Invalid window state when writing frame: " + e.getMessage(), e);
}
}
/**
* Discards this {@link FlowControlled}, writing an error. If this frame is in the pending queue,
* the unwritten bytes are removed from this branch of the priority tree.
*/
private void writeError(FlowControlled frame, Http2Exception cause) {
assert ctx != null;
decrementPendingBytes(frame.size(), true);
frame.error(ctx, cause);
}
}
/**
* Abstract class which provides common functionality for writability monitor implementations.
*/
private class WritabilityMonitor implements StreamByteDistributor.Writer {
private boolean inWritePendingBytes;
private long totalPendingBytes;
@Override
public final void write(Http2Stream stream, int numBytes) {
state(stream).writeAllocatedBytes(numBytes);
}
/**
* Called when the writability of the underlying channel changes.
* @throws Http2Exception If a write occurs and an exception happens in the write operation.
*/
void channelWritabilityChange() throws Http2Exception {}
/**
* Called when the state is cancelled.
* @param state the state that was cancelled.
*/
void stateCancelled(FlowState state) {}
/**
* Set the initial window size for {@code state}.
* @param state the state to change the initial window size for.
* @param initialWindowSize the size of the window in bytes.
*/
void windowSize(FlowState state, int initialWindowSize) {
state.windowSize(initialWindowSize);
}
/**
* Increment the window size for a particular stream.
* @param state the state associated with the stream whose window is being incremented.
* @param delta The amount to increment by.
* @throws Http2Exception If this operation overflows the window for {@code state}.
*/
void incrementWindowSize(FlowState state, int delta) throws Http2Exception {
state.incrementStreamWindow(delta);
}
/**
* Add a frame to be sent via flow control.
* @param state The state associated with the stream which the {@code frame} is associated with.
* @param frame the frame to enqueue.
* @throws Http2Exception If a writability error occurs.
*/
void enqueueFrame(FlowState state, FlowControlled frame) throws Http2Exception {
state.enqueueFrame(frame);
}
/**
* Increment the total amount of pending bytes for all streams. When any stream's pending bytes changes
* method should be called.
* @param delta The amount to increment by.
*/
final void incrementPendingBytes(int delta) {
totalPendingBytes += delta;
// Notification of writibilty change should be delayed until the end of the top level event.
// This is to ensure the flow controller is more consistent state before calling external listener methods.
}
/**
* Determine if the stream associated with {@code state} is writable.
* @param state The state which is associated with the stream to test writability for.
* @return {@code true} if {@link FlowState#stream()} is writable. {@code false} otherwise.
*/
final boolean isWritable(FlowState state) {
return isWritableConnection() && state.isWritable();
}
final void writePendingBytes() throws Http2Exception {
// Reentry is not permitted during the byte distribution process. It may lead to undesirable distribution of
// bytes and even infinite loops. We protect against reentry and make sure each call has an opportunity to
// cause a distribution to occur. This may be useful for example if the channel's writability changes from
// Writable -> Not Writable (because we are writing) -> Writable (because the user flushed to make more room
// in the channel outbound buffer).
if (inWritePendingBytes) {
return;
}
inWritePendingBytes = true;
try {
int bytesToWrite = writableBytes();
// Make sure we always write at least once, regardless if we have bytesToWrite or not.
// This ensures that zero-length frames will always be written.
for (; ; ) {
if (!streamByteDistributor.distribute(bytesToWrite, this)
|| (bytesToWrite = writableBytes()) <= 0
|| !isChannelWritable0()) {
break;
}
}
} finally {
inWritePendingBytes = false;
}
}
void initialWindowSize(int newWindowSize) throws Http2Exception {
checkPositiveOrZero(newWindowSize, "newWindowSize");
final int delta = newWindowSize - initialWindowSize;
initialWindowSize = newWindowSize;
connection.forEachActiveStream(new Http2StreamVisitor() {
@Override
public boolean visit(Http2Stream stream) throws Http2Exception {
state(stream).incrementStreamWindow(delta);
return true;
}
});
if (delta > 0 && isChannelWritable()) {
// The window size increased, send any pending frames for all streams.
writePendingBytes();
}
}
final boolean isWritableConnection() {
return connectionState.windowSize() - totalPendingBytes > 0 && isChannelWritable();
}
}
/**
* Writability of a {@code stream} is calculated using the following:
* <pre>
* Connection Window - Total Queued Bytes > 0 &&
* Stream Window - Bytes Queued for Stream > 0 &&
* isChannelWritable()
* </pre>
*/
private final class ListenerWritabilityMonitor extends WritabilityMonitor implements Http2StreamVisitor {
private final Listener listener;
ListenerWritabilityMonitor(Listener listener) {
this.listener = listener;
}
@Override
public boolean visit(Http2Stream stream) throws Http2Exception {
FlowState state = state(stream);
if (isWritable(state) != state.markedWritability()) {
notifyWritabilityChanged(state);
}
return true;
}
@Override
void windowSize(FlowState state, int initialWindowSize) {
super.windowSize(state, initialWindowSize);
try {
checkStateWritability(state);
} catch (Http2Exception e) {
throw new RuntimeException("Caught unexpected exception from window", e);
}
}
@Override
void incrementWindowSize(FlowState state, int delta) throws Http2Exception {
super.incrementWindowSize(state, delta);
checkStateWritability(state);
}
@Override
void initialWindowSize(int newWindowSize) throws Http2Exception {
super.initialWindowSize(newWindowSize);
if (isWritableConnection()) {
// If the write operation does not occur we still need to check all streams because they
// may have transitioned from writable to not writable.
checkAllWritabilityChanged();
}
}
@Override
void enqueueFrame(FlowState state, FlowControlled frame) throws Http2Exception {
super.enqueueFrame(state, frame);
checkConnectionThenStreamWritabilityChanged(state);
}
@Override
void stateCancelled(FlowState state) {
try {
checkConnectionThenStreamWritabilityChanged(state);
} catch (Http2Exception e) {
throw new RuntimeException("Caught unexpected exception from checkAllWritabilityChanged", e);
}
}
@Override
void channelWritabilityChange() throws Http2Exception {
if (connectionState.markedWritability() != isChannelWritable()) {
checkAllWritabilityChanged();
}
}
private void checkStateWritability(FlowState state) throws Http2Exception {
if (isWritable(state) != state.markedWritability()) {
if (state == connectionState) {
checkAllWritabilityChanged();
} else {
notifyWritabilityChanged(state);
}
}
}
private void notifyWritabilityChanged(FlowState state) {
state.markedWritability(!state.markedWritability());
try {
listener.writabilityChanged(state.stream);
} catch (Throwable cause) {
logger.error("Caught Throwable from listener.writabilityChanged", cause);
}
}
private void checkConnectionThenStreamWritabilityChanged(FlowState state) throws Http2Exception {
// It is possible that the connection window and/or the individual stream writability could change.
if (isWritableConnection() != connectionState.markedWritability()) {
checkAllWritabilityChanged();
} else if (isWritable(state) != state.markedWritability()) {
notifyWritabilityChanged(state);
}
// does not check overflow anymore: Let receiver continue receiving the pending bytes.
}
private void checkAllWritabilityChanged() throws Http2Exception {
// Make sure we mark that we have notified as a result of this change.
connectionState.markedWritability(isWritableConnection());
connection.forEachActiveStream(this);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TriplePathResolver.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TriplePathResolver.java | /*
* 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.rpc.protocol.tri;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.ClassUtils;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.PathResolver;
import java.util.Map;
public class TriplePathResolver implements PathResolver {
private static final Logger LOGGER = LoggerFactory.getLogger(TriplePathResolver.class);
private final Map<String, Invoker<?>> mapping = CollectionUtils.newConcurrentHashMap();
private final Map<String, Boolean> nativeStubs = CollectionUtils.newConcurrentHashMap();
@Override
public void register(Invoker<?> invoker) {
URL url = invoker.getUrl();
String serviceKey = url.getServiceKey();
String serviceInterface = url.getServiceModel().getServiceModel().getInterfaceName();
register0(serviceKey, serviceInterface, invoker, url);
// Path pattern: '{interfaceName}' or '{contextPath}/{interfaceName}'
String path = url.getPath();
int index = path.lastIndexOf('/');
if (index == -1) {
return;
}
String fallbackPath = path.substring(0, index + 1) + serviceInterface;
register0(URL.buildKey(path, url.getGroup(), url.getVersion()), fallbackPath, invoker, url);
}
private void register0(String path, String fallbackPath, Invoker<?> invoker, URL url) {
// register default mapping
Invoker<?> previous = mapping.put(path, invoker);
if (previous != null) {
if (path.equals(fallbackPath)) {
LOGGER.info(
"Already exists an invoker[{}] on path[{}], dubbo will override with invoker[{}]",
previous.getUrl(),
path,
url);
} else {
throw new IllegalStateException(String.format(
"Already exists an invoker[%s] on path[%s], failed to add invoker[%s], please use a unique path.",
previous.getUrl(), path, url));
}
} else {
LOGGER.debug(
"Register triple grpc mapping: '{}' -> invoker[{}], service=[{}]",
path,
url,
ClassUtils.toShortString(url.getServiceModel().getProxyObject()));
}
// register fallback mapping
if (TripleProtocol.RESOLVE_FALLBACK_TO_DEFAULT && !path.equals(fallbackPath)) {
previous = mapping.putIfAbsent(fallbackPath, invoker);
if (previous != null) {
LOGGER.info(
"Already exists an invoker[{}] on path[{}], dubbo will skip override with invoker[{}]",
previous.getUrl(),
fallbackPath,
url);
} else {
LOGGER.info(
"Register fallback triple grpc mapping: '{}' -> invoker[{}], service=[{}]",
fallbackPath,
url,
ClassUtils.toShortString(url.getServiceModel().getProxyObject()));
}
}
}
@Override
public void unregister(Invoker<?> invoker) {
URL url = invoker.getUrl();
mapping.remove(url.getServiceKey());
if (TripleProtocol.RESOLVE_FALLBACK_TO_DEFAULT) {
mapping.remove(url.getServiceModel().getServiceModel().getInterfaceName());
}
}
@Override
public Invoker<?> add(String path, Invoker<?> invoker) {
return mapping.put(path, invoker);
}
@Override
public Invoker<?> addIfAbsent(String path, Invoker<?> invoker) {
return mapping.putIfAbsent(path, invoker);
}
@Override
public Invoker<?> resolve(String path, String group, String version) {
Invoker<?> invoker = mapping.get(URL.buildKey(path, group, version));
if (invoker == null && TripleProtocol.RESOLVE_FALLBACK_TO_DEFAULT) {
invoker = mapping.get(URL.buildKey(path, group, TripleConstants.DEFAULT_VERSION));
if (invoker == null) {
invoker = mapping.get(path);
}
}
return invoker;
}
public boolean hasNativeStub(String path) {
return nativeStubs.containsKey(path);
}
@Override
public void addNativeStub(String path) {
nativeStubs.put(path, Boolean.TRUE);
}
@Override
public void remove(String path) {
mapping.remove(path);
}
@Override
public void destroy() {
mapping.clear();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ClassLoadUtil.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ClassLoadUtil.java | /*
* 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.rpc.protocol.tri;
public class ClassLoadUtil {
public static void switchContextLoader(ClassLoader loader) {
try {
if (loader != null && loader != Thread.currentThread().getContextClassLoader()) {
Thread.currentThread().setContextClassLoader(loader);
}
} catch (SecurityException e) {
// ignore , ForkJoinPool & jdk8 & securityManager will cause this
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleHttp2Protocol.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleHttp2Protocol.java | /*
* 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.rpc.protocol.tri;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.config.context.ConfigManager;
import org.apache.dubbo.config.nested.TripleConfig;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.api.AbstractWireProtocol;
import org.apache.dubbo.remoting.api.pu.ChannelHandlerPretender;
import org.apache.dubbo.remoting.api.pu.ChannelOperator;
import org.apache.dubbo.remoting.api.ssl.ContextOperator;
import org.apache.dubbo.remoting.http12.HttpVersion;
import org.apache.dubbo.remoting.http12.netty4.HttpWriteQueueHandler;
import org.apache.dubbo.remoting.http12.netty4.h1.NettyHttp1Codec;
import org.apache.dubbo.remoting.http12.netty4.h1.NettyHttp1ConnectionHandler;
import org.apache.dubbo.remoting.http12.netty4.h2.NettyHttp2FrameCodec;
import org.apache.dubbo.remoting.http12.netty4.h2.NettyHttp2ProtocolSelectorHandler;
import org.apache.dubbo.remoting.http12.netty4.h2.NettyHttp2SettingsHandler;
import org.apache.dubbo.remoting.utils.UrlUtils;
import org.apache.dubbo.remoting.websocket.netty4.WebSocketFrameCodec;
import org.apache.dubbo.remoting.websocket.netty4.WebSocketProtocolSelectorHandler;
import org.apache.dubbo.remoting.websocket.netty4.WebSocketServerUpgradeCodec;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ScopeModelAware;
import org.apache.dubbo.rpc.protocol.tri.h12.TripleProtocolDetector;
import org.apache.dubbo.rpc.protocol.tri.h12.http1.DefaultHttp11ServerTransportListenerFactory;
import org.apache.dubbo.rpc.protocol.tri.h12.http2.GenericHttp2ServerTransportListenerFactory;
import org.apache.dubbo.rpc.protocol.tri.transport.TripleGoAwayHandler;
import org.apache.dubbo.rpc.protocol.tri.transport.TripleServerConnectionHandler;
import org.apache.dubbo.rpc.protocol.tri.transport.TripleTailHandler;
import org.apache.dubbo.rpc.protocol.tri.websocket.DefaultWebSocketServerTransportListenerFactory;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.HttpServerUpgradeHandler;
import io.netty.handler.codec.http.websocketx.WebSocketDecoderConfig;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolConfig;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketServerCompressionHandler;
import io.netty.handler.codec.http2.Http2CodecUtil;
import io.netty.handler.codec.http2.Http2FrameCodec;
import io.netty.handler.codec.http2.Http2FrameCodecBuilder;
import io.netty.handler.codec.http2.Http2FrameLogger;
import io.netty.handler.codec.http2.Http2MultiplexHandler;
import io.netty.handler.codec.http2.Http2ServerUpgradeCodec;
import io.netty.handler.codec.http2.Http2Settings;
import io.netty.handler.codec.http2.Http2StreamChannel;
import io.netty.handler.flush.FlushConsolidationHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.util.AsciiString;
@Activate
public class TripleHttp2Protocol extends AbstractWireProtocol implements ScopeModelAware {
public static final Http2FrameLogger CLIENT_LOGGER = new Http2FrameLogger(LogLevel.DEBUG, "H2_CLIENT");
public static final Http2FrameLogger SERVER_LOGGER = new Http2FrameLogger(LogLevel.DEBUG, "H2_SERVER");
private FrameworkModel frameworkModel;
public TripleHttp2Protocol() {
super(new TripleProtocolDetector());
}
@Override
public void setFrameworkModel(FrameworkModel frameworkModel) {
this.frameworkModel = frameworkModel;
}
@Override
public void close() {
super.close();
}
@Override
public void configClientPipeline(URL url, ChannelOperator operator, ContextOperator contextOperator) {
TripleConfig tripleConfig = ConfigManager.getProtocolOrDefault(url).getTripleOrDefault();
Http2FrameCodec codec = Http2FrameCodecBuilder.forClient()
.gracefulShutdownTimeoutMillis(10000)
.initialSettings(new Http2Settings()
.headerTableSize(tripleConfig.getHeaderTableSizeOrDefault())
.pushEnabled(tripleConfig.getEnablePushOrDefault())
.maxConcurrentStreams(tripleConfig.getMaxConcurrentStreamsOrDefault())
.initialWindowSize(tripleConfig.getInitialWindowSizeOrDefault())
.maxFrameSize(tripleConfig.getMaxFrameSizeOrDefault())
.maxHeaderListSize(tripleConfig.getMaxHeaderListSizeOrDefault()))
.frameLogger(CLIENT_LOGGER)
.validateHeaders(false)
.build();
// codec.connection().local().flowController().frameWriter(codec.encoder().frameWriter());
List<ChannelHandler> handlers = new ArrayList<>();
handlers.add(new ChannelHandlerPretender(codec));
handlers.add(new ChannelHandlerPretender(new Http2MultiplexHandler(new ChannelDuplexHandler())));
handlers.add(new ChannelHandlerPretender(new TriplePingPongHandler(UrlUtils.getCloseTimeout(url))));
handlers.add(new ChannelHandlerPretender(new TripleGoAwayHandler()));
handlers.add(new ChannelHandlerPretender(new TripleTailHandler()));
operator.configChannelHandler(handlers);
}
@Override
public void configServerProtocolHandler(URL url, ChannelOperator operator) {
String httpVersion = operator.detectResult().getAttribute(TripleProtocolDetector.HTTP_VERSION);
List<ChannelHandler> channelHandlerPretenders = new ArrayList<>();
try {
// h1
if (HttpVersion.HTTP1.getVersion().equals(httpVersion)) {
configurerHttp1Handlers(url, channelHandlerPretenders);
return;
}
// h2
if (HttpVersion.HTTP2.getVersion().equals(httpVersion)) {
configurerHttp2Handlers(url, channelHandlerPretenders);
}
} finally {
operator.configChannelHandler(channelHandlerPretenders);
}
}
@SuppressWarnings("deprecation")
private void configurerHttp1Handlers(URL url, List<ChannelHandler> handlers) {
TripleConfig tripleConfig = ConfigManager.getProtocolOrDefault(url).getTripleOrDefault();
HttpServerCodec sourceCodec = new HttpServerCodec(
tripleConfig.getMaxInitialLineLengthOrDefault(),
tripleConfig.getMaxHeaderSizeOrDefault(),
tripleConfig.getMaxChunkSizeOrDefault(),
false,
tripleConfig.getInitialBufferSizeOrDefault());
handlers.add(new ChannelHandlerPretender(sourceCodec));
// Triple protocol http1 upgrade support
handlers.add(new ChannelHandlerPretender(new HttpServerUpgradeHandler(
sourceCodec,
protocol -> {
if (AsciiString.contentEquals(Http2CodecUtil.HTTP_UPGRADE_PROTOCOL_NAME, protocol)) {
NettyHttp2SettingsHandler nettyHttp2SettingsHandler = new NettyHttp2SettingsHandler();
return new Http2ServerUpgradeCodec(
buildHttp2FrameCodec(tripleConfig),
nettyHttp2SettingsHandler,
new HttpWriteQueueHandler(),
new FlushConsolidationHandler(64, true),
new TripleServerConnectionHandler(),
buildHttp2MultiplexHandler(nettyHttp2SettingsHandler, url, tripleConfig),
new TripleTailHandler());
} else if (AsciiString.contentEquals(HttpHeaderValues.WEBSOCKET, protocol)) {
return new WebSocketServerUpgradeCodec(
Arrays.asList(
HttpObjectAggregator.class,
NettyHttp1Codec.class,
NettyHttp1ConnectionHandler.class),
new WebSocketServerCompressionHandler(),
new HttpWriteQueueHandler(),
new WebSocketProtocolSelectorHandler(
url,
frameworkModel,
tripleConfig,
DefaultWebSocketServerTransportListenerFactory.INSTANCE),
buildWebSocketServerProtocolHandler(tripleConfig),
new WebSocketFrameCodec());
}
// Not upgrade request
return null;
},
Integer.MAX_VALUE)));
// If the upgrade was successful, remove the message from the output list
// so that it's not propagated to the next handler. This request will
// be propagated as a user event instead.
handlers.add(new ChannelHandlerPretender(new HttpObjectAggregator(tripleConfig.getMaxBodySizeOrDefault())));
handlers.add(new ChannelHandlerPretender(new NettyHttp1Codec()));
handlers.add(new ChannelHandlerPretender(new NettyHttp1ConnectionHandler(
url, frameworkModel, tripleConfig, DefaultHttp11ServerTransportListenerFactory.INSTANCE)));
}
private Http2MultiplexHandler buildHttp2MultiplexHandler(
NettyHttp2SettingsHandler nettyHttp2SettingsHandler, URL url, TripleConfig tripleConfig) {
return new Http2MultiplexHandler(new ChannelInitializer<Http2StreamChannel>() {
@Override
protected void initChannel(Http2StreamChannel ch) {
ChannelPipeline p = ch.pipeline();
p.addLast(new NettyHttp2FrameCodec(nettyHttp2SettingsHandler));
p.addLast(new NettyHttp2ProtocolSelectorHandler(
url, frameworkModel, tripleConfig, GenericHttp2ServerTransportListenerFactory.INSTANCE));
}
});
}
private void configurerHttp2Handlers(URL url, List<ChannelHandler> handlers) {
NettyHttp2SettingsHandler nettyHttp2SettingsHandler = new NettyHttp2SettingsHandler();
TripleConfig tripleConfig = ConfigManager.getProtocolOrDefault(url).getTripleOrDefault();
Http2FrameCodec codec = buildHttp2FrameCodec(tripleConfig);
Http2MultiplexHandler handler = buildHttp2MultiplexHandler(nettyHttp2SettingsHandler, url, tripleConfig);
handlers.add(new ChannelHandlerPretender(new HttpWriteQueueHandler()));
handlers.add(new ChannelHandlerPretender(codec));
handlers.add(new ChannelHandlerPretender(nettyHttp2SettingsHandler));
handlers.add(new ChannelHandlerPretender(new FlushConsolidationHandler(64, true)));
handlers.add(new ChannelHandlerPretender(new TripleServerConnectionHandler()));
handlers.add(new ChannelHandlerPretender(handler));
handlers.add(new ChannelHandlerPretender(new TripleTailHandler()));
}
private Http2FrameCodec buildHttp2FrameCodec(TripleConfig tripleConfig) {
return TripleHttp2FrameCodecBuilder.forServer()
.customizeConnection((connection) ->
connection.remote().flowController(new TriHttp2RemoteFlowController(connection, tripleConfig)))
.gracefulShutdownTimeoutMillis(10000)
.initialSettings(new Http2Settings()
.headerTableSize(tripleConfig.getHeaderTableSizeOrDefault())
.maxConcurrentStreams(tripleConfig.getMaxConcurrentStreamsOrDefault())
.initialWindowSize(tripleConfig.getInitialWindowSizeOrDefault())
.maxFrameSize(tripleConfig.getMaxFrameSizeOrDefault())
.maxHeaderListSize(tripleConfig.getMaxHeaderListSizeOrDefault()))
.frameLogger(SERVER_LOGGER)
.validateHeaders(false)
.build();
}
private WebSocketServerProtocolHandler buildWebSocketServerProtocolHandler(TripleConfig tripleConfig) {
return new WebSocketServerProtocolHandler(WebSocketServerProtocolConfig.newBuilder()
.checkStartsWith(true)
.handleCloseFrames(false)
.decoderConfig(WebSocketDecoderConfig.newBuilder()
.maxFramePayloadLength(tripleConfig.getMaxBodySizeOrDefault())
.build())
.build());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ThrowableWrapper.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ThrowableWrapper.java | /*
* 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.rpc.protocol.tri;
public final class ThrowableWrapper extends RuntimeException {
private static final long serialVersionUID = 1L;
private final Throwable original;
public ThrowableWrapper(Throwable original) {
super(original.getMessage(), null);
this.original = original;
setStackTrace(original.getStackTrace());
}
public Throwable getOriginal() {
return original;
}
@Override
public Throwable fillInStackTrace() {
return null;
}
@Override
public Throwable getCause() {
return original;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/Http3Exchanger.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/Http3Exchanger.java | /*
* 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.rpc.protocol.tri;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.Configuration;
import org.apache.dubbo.common.constants.LoggerCodeConstants;
import org.apache.dubbo.common.logger.FluentLogger;
import org.apache.dubbo.common.utils.ClassUtils;
import org.apache.dubbo.common.utils.ConcurrentHashMapUtils;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.RemotingServer;
import org.apache.dubbo.remoting.api.connection.AbstractConnectionClient;
import org.apache.dubbo.remoting.http12.netty4.HttpWriteQueueHandler;
import org.apache.dubbo.remoting.http3.netty4.NettyHttp3FrameCodec;
import org.apache.dubbo.remoting.http3.netty4.NettyHttp3ProtocolSelectorHandler;
import org.apache.dubbo.remoting.transport.ChannelHandlerAdapter;
import org.apache.dubbo.remoting.transport.netty4.NettyHttp3Server;
import org.apache.dubbo.remoting.utils.UrlUtils;
import org.apache.dubbo.rpc.Constants;
import org.apache.dubbo.rpc.model.ScopeModelUtil;
import org.apache.dubbo.rpc.protocol.tri.h3.Http3ClientFrameCodec;
import org.apache.dubbo.rpc.protocol.tri.h3.Http3TripleServerConnectionHandler;
import org.apache.dubbo.rpc.protocol.tri.h3.negotiation.Helper;
import java.util.ArrayList;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.http3.Http3ServerConnectionHandler;
import io.netty.handler.codec.quic.QuicStreamChannel;
import io.netty.handler.flush.FlushConsolidationHandler;
import io.netty.handler.timeout.IdleStateHandler;
import static org.apache.dubbo.remoting.http3.netty4.Constants.PIPELINE_CONFIGURATOR_KEY;
public final class Http3Exchanger {
private static final FluentLogger LOGGER = FluentLogger.of(Http3Exchanger.class);
private static final boolean HAS_NETTY_HTTP3 = ClassUtils.isPresent("io.netty.handler.codec.http3.Http3");
private static final ConcurrentHashMap<String, RemotingServer> SERVERS = new ConcurrentHashMap<>();
private static final Map<String, AbstractConnectionClient> CLIENTS = new ConcurrentHashMap<>(16);
private static final ChannelHandler HANDLER = new ChannelHandlerAdapter();
private static boolean ENABLED = false;
private static boolean NEGOTIATION_ENABLED = true;
private Http3Exchanger() {}
public static void init(Configuration configuration) {
ENABLED = configuration.getBoolean(Constants.H3_SETTINGS_HTTP3_ENABLED, false);
NEGOTIATION_ENABLED = configuration.getBoolean(Constants.H3_SETTINGS_HTTP3_NEGOTIATION, true);
if (ENABLED && !HAS_NETTY_HTTP3) {
throw new IllegalStateException("Class for netty http3 support not found");
}
}
public static boolean isEnabled(URL url) {
return ENABLED || HAS_NETTY_HTTP3 && url.getParameter(Constants.HTTP3_KEY, false);
}
public static RemotingServer bind(URL url) {
if (isEnabled(url)) {
return ConcurrentHashMapUtils.computeIfAbsent(SERVERS, url.getAddress(), addr -> {
try {
URL serverUrl = url.putAttribute(PIPELINE_CONFIGURATOR_KEY, configServerPipeline(url));
return new NettyHttp3Server(serverUrl, HANDLER);
} catch (RemotingException e) {
throw new RuntimeException(e);
}
});
}
return null;
}
private static Consumer<ChannelPipeline> configServerPipeline(URL url) {
NettyHttp3ProtocolSelectorHandler selectorHandler =
new NettyHttp3ProtocolSelectorHandler(url, ScopeModelUtil.getFrameworkModel(url.getScopeModel()));
return pipeline -> {
pipeline.addLast(new Http3ServerConnectionHandler(new ChannelInitializer<QuicStreamChannel>() {
@Override
protected void initChannel(QuicStreamChannel ch) {
ch.pipeline()
.addLast(new HttpWriteQueueHandler())
.addLast(new FlushConsolidationHandler(64, true))
.addLast(NettyHttp3FrameCodec.INSTANCE)
.addLast(selectorHandler);
}
}));
pipeline.addLast(new Http3TripleServerConnectionHandler());
};
}
public static AbstractConnectionClient connect(URL url) {
return CLIENTS.compute(url.getAddress(), (address, client) -> {
if (client == null) {
URL clientUrl = url.putAttribute(PIPELINE_CONFIGURATOR_KEY, configClientPipeline(url));
AbstractConnectionClient connectionClient = NEGOTIATION_ENABLED
? Helper.createAutoSwitchClient(clientUrl, HANDLER)
: Helper.createHttp3Client(clientUrl, HANDLER);
connectionClient.addCloseListener(() -> CLIENTS.remove(address, connectionClient));
client = connectionClient;
} else {
client.retain();
}
return client;
});
}
private static Consumer<ChannelPipeline> configClientPipeline(URL url) {
int heartbeat = UrlUtils.getHeartbeat(url);
int closeTimeout = UrlUtils.getCloseTimeout(url);
return pipeline -> {
pipeline.addLast(Http3ClientFrameCodec.INSTANCE);
pipeline.addLast(new IdleStateHandler(heartbeat, 0, 0, TimeUnit.MILLISECONDS));
pipeline.addLast(new TriplePingPongHandler(closeTimeout));
};
}
public static void close() {
if (SERVERS.isEmpty()) {
return;
}
ArrayList<RemotingServer> toClose = new ArrayList<>(SERVERS.values());
SERVERS.clear();
for (RemotingServer server : toClose) {
try {
server.close();
} catch (Throwable t) {
LOGGER.error(LoggerCodeConstants.PROTOCOL_ERROR_CLOSE_SERVER, "Close http3 server failed", t);
}
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/DeadlineFuture.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/DeadlineFuture.java | /*
* 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.rpc.protocol.tri;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.resource.GlobalResourceInitializer;
import org.apache.dubbo.common.timer.HashedWheelTimer;
import org.apache.dubbo.common.timer.Timeout;
import org.apache.dubbo.common.timer.Timer;
import org.apache.dubbo.common.timer.TimerTask;
import org.apache.dubbo.common.utils.NamedThreadFactory;
import org.apache.dubbo.rpc.AppResponse;
import org.apache.dubbo.rpc.TriRpcStatus;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
public class DeadlineFuture extends CompletableFuture<AppResponse> {
private static final Logger LOGGER = LoggerFactory.getLogger(DeadlineFuture.class);
private final String serviceName;
private final String methodName;
private final String address;
private final int timeout;
private final long start = System.currentTimeMillis();
private final List<Runnable> timeoutListeners = new ArrayList<>();
private final Timeout timeoutTask;
private ExecutorService executor;
private static final GlobalResourceInitializer<Timer> TIME_OUT_TIMER = new GlobalResourceInitializer<>(
() -> new HashedWheelTimer(new NamedThreadFactory("dubbo-future-timeout", true), 30, TimeUnit.MILLISECONDS),
DeadlineFuture::destroy);
private DeadlineFuture(String serviceName, String methodName, String address, int timeout) {
this.serviceName = serviceName;
this.methodName = methodName;
this.address = address;
this.timeout = timeout;
TimeoutCheckTask timeoutCheckTask = new TimeoutCheckTask();
this.timeoutTask = TIME_OUT_TIMER.get().newTimeout(timeoutCheckTask, timeout, TimeUnit.MILLISECONDS);
}
public static void destroy() {
TIME_OUT_TIMER.remove(Timer::stop);
}
/**
* init a DeadlineFuture 1.init a DeadlineFuture 2.timeout check
*
* @param timeout timeout in Mills
* @return a new DeadlineFuture
*/
public static DeadlineFuture newFuture(
String serviceName, String methodName, String address, int timeout, ExecutorService executor) {
final DeadlineFuture future = new DeadlineFuture(serviceName, methodName, address, timeout);
future.setExecutor(executor);
return future;
}
public void received(TriRpcStatus status, AppResponse appResponse) {
if (status.code != TriRpcStatus.Code.DEADLINE_EXCEEDED && !timeoutTask.isCancelled()) {
timeoutTask.cancel();
}
if (getExecutor() != null) {
getExecutor().execute(() -> doReceived(status, appResponse));
} else {
doReceived(status, appResponse);
}
}
public void addTimeoutListener(Runnable runnable) {
timeoutListeners.add(runnable);
}
public List<Runnable> getTimeoutListeners() {
return timeoutListeners;
}
public ExecutorService getExecutor() {
return executor;
}
public void setExecutor(ExecutorService executor) {
this.executor = executor;
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
timeoutTask.cancel();
doReceived(TriRpcStatus.CANCELLED, new AppResponse(TriRpcStatus.CANCELLED.asException()));
return true;
}
public void cancel() {
this.cancel(true);
}
private void doReceived(TriRpcStatus status, AppResponse appResponse) {
if (isDone() || isCancelled() || isCompletedExceptionally()) {
return;
}
// Still needs to be discussed here, but for now, that's it
// Remove the judgment of status is ok,
// because the completelyExceptionally method will lead to the onError method in the filter,
// but there are also exceptions in the onResponse in the filter,which is a bit confusing.
// We recommend only handling onResponse in which onError is called for handling
this.complete(appResponse);
}
private String getTimeoutMessage() {
long nowTimestamp = System.currentTimeMillis();
return "Waiting server-side response timeout by scan timer. start time: "
+ (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date(start)))
+ ", end time: " + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date(nowTimestamp)))
+ ", timeout: " + timeout + " ms, service: " + serviceName
+ ", method: " + methodName;
}
private class TimeoutCheckTask implements TimerTask {
@Override
public void run(Timeout timeout) {
if (DeadlineFuture.this.isDone()) {
return;
}
ExecutorService executor = getExecutor();
if (executor != null && !executor.isShutdown()) {
executor.execute(() -> {
notifyTimeout();
for (Runnable timeoutListener : getTimeoutListeners()) {
timeoutListener.run();
}
});
} else {
notifyTimeout();
}
}
private void notifyTimeout() {
final TriRpcStatus status = TriRpcStatus.DEADLINE_EXCEEDED.withDescription(getTimeoutMessage());
AppResponse timeoutResponse = new AppResponse();
timeoutResponse.setException(status.asException());
DeadlineFuture.this.doReceived(status, timeoutResponse);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/service/ReflectionV1AlphaService.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/service/ReflectionV1AlphaService.java | /*
* 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.rpc.protocol.tri.service;
import org.apache.dubbo.common.stream.StreamObserver;
import org.apache.dubbo.rpc.TriRpcStatus;
import java.util.ArrayDeque;
import java.util.HashSet;
import java.util.Queue;
import java.util.Set;
import com.google.protobuf.Descriptors.FileDescriptor;
import io.grpc.reflection.v1alpha.DubboServerReflectionTriple;
import io.grpc.reflection.v1alpha.ErrorResponse;
import io.grpc.reflection.v1alpha.ExtensionNumberResponse;
import io.grpc.reflection.v1alpha.ExtensionRequest;
import io.grpc.reflection.v1alpha.FileDescriptorResponse;
import io.grpc.reflection.v1alpha.ListServiceResponse;
import io.grpc.reflection.v1alpha.ServerReflectionRequest;
import io.grpc.reflection.v1alpha.ServerReflectionResponse;
import io.grpc.reflection.v1alpha.ServiceResponse;
/**
* Provides a reflection service for Protobuf service for service test and dynamic gateway.
*
* @link https://github.com/grpc/grpc/blob/master/doc/server-reflection.md
*/
public class ReflectionV1AlphaService extends DubboServerReflectionTriple.ServerReflectionImplBase {
@Override
public StreamObserver<ServerReflectionRequest> serverReflectionInfo(
StreamObserver<ServerReflectionResponse> responseObserver) {
return new StreamObserver<ServerReflectionRequest>() {
@Override
public void onNext(ServerReflectionRequest request) {
switch (request.getMessageRequestCase()) {
case FILE_BY_FILENAME:
getFileByName(request, responseObserver);
break;
case FILE_CONTAINING_SYMBOL:
getFileContainingSymbol(request, responseObserver);
break;
case FILE_CONTAINING_EXTENSION:
getFileByExtension(request, responseObserver);
break;
case ALL_EXTENSION_NUMBERS_OF_TYPE:
getAllExtensions(request, responseObserver);
break;
case LIST_SERVICES:
listServices(request, responseObserver);
break;
default:
sendErrorResponse(
request,
TriRpcStatus.Code.UNIMPLEMENTED,
"not implemented " + request.getMessageRequestCase(),
responseObserver);
}
}
@Override
public void onError(Throwable throwable) {
responseObserver.onError(throwable);
}
@Override
public void onCompleted() {
responseObserver.onCompleted();
}
};
}
private void getFileByName(
ServerReflectionRequest request, StreamObserver<ServerReflectionResponse> responseObserver) {
String name = request.getFileByFilename();
FileDescriptor fd = SchemaDescriptorRegistry.getSchemaDescriptor(name);
if (fd != null) {
responseObserver.onNext(createServerReflectionResponse(request, fd));
} else {
sendErrorResponse(request, TriRpcStatus.Code.NOT_FOUND, "File not found.", responseObserver);
}
}
private void getFileContainingSymbol(
ServerReflectionRequest request, StreamObserver<ServerReflectionResponse> responseObserver) {
String symbol = request.getFileContainingSymbol();
FileDescriptor fd = SchemaDescriptorRegistry.getSchemaDescriptor(symbol);
if (fd != null) {
responseObserver.onNext(createServerReflectionResponse(request, fd));
} else {
sendErrorResponse(request, TriRpcStatus.Code.NOT_FOUND, "Symbol not found.", responseObserver);
}
}
private void getFileByExtension(
ServerReflectionRequest request, StreamObserver<ServerReflectionResponse> responseObserver) {
ExtensionRequest extensionRequest = request.getFileContainingExtension();
String type = extensionRequest.getContainingType();
int extension = extensionRequest.getExtensionNumber();
FileDescriptor fd = SchemaDescriptorRegistry.getFileDescriptorByExtensionAndNumber(type, extension);
if (fd != null) {
responseObserver.onNext(createServerReflectionResponse(request, fd));
} else {
sendErrorResponse(request, TriRpcStatus.Code.NOT_FOUND, "Extension not found.", responseObserver);
}
}
private void getAllExtensions(
ServerReflectionRequest request, StreamObserver<ServerReflectionResponse> responseObserver) {
String type = request.getAllExtensionNumbersOfType();
Set<Integer> extensions = SchemaDescriptorRegistry.getExtensionNumbers(type);
if (extensions != null) {
ExtensionNumberResponse.Builder builder =
ExtensionNumberResponse.newBuilder().setBaseTypeName(type).addAllExtensionNumber(extensions);
responseObserver.onNext(ServerReflectionResponse.newBuilder()
.setValidHost(request.getHost())
.setOriginalRequest(request)
.setAllExtensionNumbersResponse(builder)
.build());
} else {
sendErrorResponse(request, TriRpcStatus.Code.NOT_FOUND, "Type not found.", responseObserver);
}
}
private void listServices(
ServerReflectionRequest request, StreamObserver<ServerReflectionResponse> responseObserver) {
ListServiceResponse.Builder builder = ListServiceResponse.newBuilder();
for (String serviceName : SchemaDescriptorRegistry.listServiceNames()) {
builder.addService(ServiceResponse.newBuilder().setName(serviceName));
}
responseObserver.onNext(ServerReflectionResponse.newBuilder()
.setValidHost(request.getHost())
.setOriginalRequest(request)
.setListServicesResponse(builder)
.build());
}
private void sendErrorResponse(
ServerReflectionRequest request,
TriRpcStatus.Code code,
String message,
StreamObserver<ServerReflectionResponse> responseObserver) {
ServerReflectionResponse response = ServerReflectionResponse.newBuilder()
.setValidHost(request.getHost())
.setOriginalRequest(request)
.setErrorResponse(
ErrorResponse.newBuilder().setErrorCode(code.code).setErrorMessage(message))
.build();
responseObserver.onNext(response);
}
private ServerReflectionResponse createServerReflectionResponse(
ServerReflectionRequest request, FileDescriptor fd) {
FileDescriptorResponse.Builder fdRBuilder = FileDescriptorResponse.newBuilder();
Set<String> seenFiles = new HashSet<>();
Queue<FileDescriptor> frontier = new ArrayDeque<>();
seenFiles.add(fd.getName());
frontier.add(fd);
while (!frontier.isEmpty()) {
FileDescriptor nextFd = frontier.remove();
fdRBuilder.addFileDescriptorProto(nextFd.toProto().toByteString());
for (FileDescriptor dependencyFd : nextFd.getDependencies()) {
if (!seenFiles.contains(dependencyFd.getName())) {
seenFiles.add(dependencyFd.getName());
frontier.add(dependencyFd);
}
}
}
return ServerReflectionResponse.newBuilder()
.setValidHost(request.getHost())
.setOriginalRequest(request)
.setFileDescriptorResponse(fdRBuilder)
.build();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/service/HealthStatusManager.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/service/HealthStatusManager.java | /*
* 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.rpc.protocol.tri.service;
import io.grpc.health.v1.Health;
import io.grpc.health.v1.HealthCheckResponse;
public class HealthStatusManager {
/**
* The special "service name" that represent all services on a GRPC server. It is an empty
* string.
*/
public static final String SERVICE_NAME_ALL_SERVICES = "";
private final TriHealthImpl healthService;
public HealthStatusManager(TriHealthImpl healthService) {
this.healthService = healthService;
}
public Health getHealthService() {
return healthService;
}
/**
* Updates the status of the server.
*
* @param service the name of some aspect of the server that is associated with a health status.
* This name can have no relation with the gRPC services that the server is
* running with. It can also be an empty String {@code ""} per the gRPC
* specification.
* @param status is one of the values {@link HealthCheckResponse.ServingStatus#SERVING}, {@link
* HealthCheckResponse.ServingStatus#NOT_SERVING} and {@link
* HealthCheckResponse.ServingStatus#UNKNOWN}.
*/
public void setStatus(String service, HealthCheckResponse.ServingStatus status) {
healthService.setStatus(service, status);
}
/**
* Clears the health status record of a service. The health service will respond with NOT_FOUND
* error on checking the status of a cleared service.
*
* @param service the name of some aspect of the server that is associated with a health status.
* This name can have no relation with the gRPC services that the server is
* running with. It can also be an empty String {@code ""} per the gRPC
* specification.
*/
public void clearStatus(String service) {
healthService.clearStatus(service);
}
/**
* enterTerminalState causes the health status manager to mark all services as not serving, and
* prevents future updates to services. This method is meant to be called prior to server
* shutdown as a way to indicate that clients should redirect their traffic elsewhere.
*/
public void enterTerminalState() {
healthService.enterTerminalState();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/service/TriBuiltinService.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/service/TriBuiltinService.java | /*
* 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.rpc.protocol.tri.service;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.Configuration;
import org.apache.dubbo.common.config.ConfigurationUtils;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.url.component.ServiceConfigURL;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.PathResolver;
import org.apache.dubbo.rpc.ProxyFactory;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.concurrent.atomic.AtomicBoolean;
import io.grpc.health.v1.DubboHealthTriple;
import io.grpc.health.v1.Health;
import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE;
import static org.apache.dubbo.rpc.Constants.H2_SETTINGS_BUILTIN_SERVICE_INIT;
import static org.apache.dubbo.rpc.Constants.PROXY_KEY;
/**
* tri internal service like grpc internal service
**/
public class TriBuiltinService {
private ProxyFactory proxyFactory;
private PathResolver pathResolver;
private Health healthService;
private FrameworkModel frameworkModel;
private ReflectionV1AlphaService reflectionServiceV1Alpha;
private HealthStatusManager healthStatusManager;
private Configuration config = ConfigurationUtils.getGlobalConfiguration(ApplicationModel.defaultModel());
private final AtomicBoolean init = new AtomicBoolean();
public TriBuiltinService(FrameworkModel frameworkModel) {
this.frameworkModel = frameworkModel;
if (enable()) {
init();
}
}
public void init() {
if (init.compareAndSet(false, true)) {
healthStatusManager = new HealthStatusManager(new TriHealthImpl());
healthService = healthStatusManager.getHealthService();
reflectionServiceV1Alpha = new ReflectionV1AlphaService();
proxyFactory = frameworkModel.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension();
pathResolver = frameworkModel.getExtensionLoader(PathResolver.class).getDefaultExtension();
addSingleBuiltinService(DubboHealthTriple.SERVICE_NAME, healthService, Health.class);
addSingleBuiltinService(
ReflectionV1AlphaService.SERVICE_NAME, reflectionServiceV1Alpha, ReflectionV1AlphaService.class);
}
}
public boolean enable() {
return config.getBoolean(H2_SETTINGS_BUILTIN_SERVICE_INIT, false);
}
private <T> void addSingleBuiltinService(String serviceName, T impl, Class<T> interfaceClass) {
ModuleModel internalModule = ApplicationModel.defaultModel().getInternalModule();
URL url = new ServiceConfigURL(CommonConstants.TRIPLE, null, null, ANYHOST_VALUE, 0, serviceName)
.addParameter(PROXY_KEY, CommonConstants.NATIVE_STUB)
.setScopeModel(internalModule);
Invoker<?> invoker = proxyFactory.getInvoker(impl, interfaceClass, url);
pathResolver.add(serviceName, invoker);
internalModule.addDestroyListener(scopeModel -> pathResolver.remove(serviceName));
}
public HealthStatusManager getHealthStatusManager() {
return healthStatusManager;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/service/SchemaDescriptorRegistry.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/service/SchemaDescriptorRegistry.java | /*
* 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.rpc.protocol.tri.service;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import com.google.protobuf.Descriptors.Descriptor;
import com.google.protobuf.Descriptors.FieldDescriptor;
import com.google.protobuf.Descriptors.FileDescriptor;
public class SchemaDescriptorRegistry {
private static final Map<String, FileDescriptor> DESCRIPTORS_BY_SYMBOL = new ConcurrentHashMap<>();
private static final Map<String, Map<Integer, FileDescriptor>> EXTENSIONS = new ConcurrentHashMap<>();
private static final Set<String> SERVICES = new HashSet<>();
public static void addSchemaDescriptor(String serviceName, FileDescriptor fd) {
SERVICES.add(serviceName);
DESCRIPTORS_BY_SYMBOL.put(serviceName, fd);
for (Descriptor messageType : fd.getMessageTypes()) {
addType(messageType);
}
for (FieldDescriptor extension : fd.getExtensions()) {
addExtension(extension, fd);
}
}
private static void addType(Descriptor descriptor) {
DESCRIPTORS_BY_SYMBOL.put(descriptor.getFullName(), descriptor.getFile());
for (Descriptor nestedType : descriptor.getNestedTypes()) {
addType(nestedType);
}
}
private static void addExtension(FieldDescriptor extension, FileDescriptor fd) {
String name = extension.getContainingType().getFullName();
int number = extension.getNumber();
if (!EXTENSIONS.containsKey(name)) {
EXTENSIONS.put(name, new HashMap<>());
}
Map<Integer, FileDescriptor> fdMap = EXTENSIONS.get(name);
fdMap.put(number, fd);
}
public static FileDescriptor getFileDescriptorByExtensionAndNumber(String extension, int number) {
return EXTENSIONS.getOrDefault(extension, Collections.emptyMap()).get(number);
}
public static Set<Integer> getExtensionNumbers(String extension) {
Map<Integer, FileDescriptor> ret = EXTENSIONS.get(extension);
if (ret == null) {
return null;
} else {
return ret.keySet();
}
}
public static FileDescriptor getSchemaDescriptor(String serviceName) {
return DESCRIPTORS_BY_SYMBOL.get(serviceName);
}
public static List<String> listServiceNames() {
return new ArrayList<>(SERVICES);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/service/TriHealthImpl.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/service/TriHealthImpl.java | /*
* 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.rpc.protocol.tri.service;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.stream.StreamObserver;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.TriRpcStatus;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import io.grpc.health.v1.DubboHealthTriple;
import io.grpc.health.v1.HealthCheckRequest;
import io.grpc.health.v1.HealthCheckResponse;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_CLOSED_SERVER;
public class TriHealthImpl extends DubboHealthTriple.HealthImplBase {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(TriHealthImpl.class);
// Due to the latency of rpc calls, synchronization of the map does not help with consistency.
// However, need use ConcurrentHashMap to allow concurrent reading by check().
private final Map<String, HealthCheckResponse.ServingStatus> statusMap = new ConcurrentHashMap<>();
private final Object watchLock = new Object();
// Technically a Multimap<String, StreamObserver<HealthCheckResponse>>. The Boolean value is not
// used. The StreamObservers need to be kept in an identity-equality set, to make sure
// user-defined equals() doesn't confuse our book-keeping of the StreamObservers. Constructing
// such Multimap would require extra lines and the end result is not significantly simpler, thus I
// would rather not have the Guava collections dependency.
private final HashMap<String, IdentityHashMap<StreamObserver<HealthCheckResponse>, Boolean>> watchers =
new HashMap<>();
// Indicates if future status changes should be ignored.
private boolean terminal;
public TriHealthImpl() {
// Copy of what Go and C++ do.
statusMap.put(HealthStatusManager.SERVICE_NAME_ALL_SERVICES, HealthCheckResponse.ServingStatus.SERVING);
}
private static HealthCheckResponse getResponseForWatch(HealthCheckResponse.ServingStatus recordedStatus) {
return HealthCheckResponse.newBuilder()
.setStatus(recordedStatus == null ? HealthCheckResponse.ServingStatus.SERVICE_UNKNOWN : recordedStatus)
.build();
}
@Override
public HealthCheckResponse check(HealthCheckRequest request) {
HealthCheckResponse.ServingStatus status = statusMap.get(request.getService());
if (status != null) {
return HealthCheckResponse.newBuilder().setStatus(status).build();
}
throw TriRpcStatus.NOT_FOUND
.withDescription("unknown service " + request.getService())
.asException();
}
@Override
public void watch(HealthCheckRequest request, StreamObserver<HealthCheckResponse> responseObserver) {
final String service = request.getService();
synchronized (watchLock) {
HealthCheckResponse.ServingStatus status = statusMap.get(service);
responseObserver.onNext(getResponseForWatch(status));
IdentityHashMap<StreamObserver<HealthCheckResponse>, Boolean> serviceWatchers = watchers.get(service);
if (serviceWatchers == null) {
serviceWatchers = new IdentityHashMap<>();
watchers.put(service, serviceWatchers);
}
serviceWatchers.put(responseObserver, Boolean.TRUE);
}
RpcContext.getCancellationContext().addListener(context -> {
synchronized (watchLock) {
IdentityHashMap<StreamObserver<HealthCheckResponse>, Boolean> serviceWatchers = watchers.get(service);
if (serviceWatchers != null) {
serviceWatchers.remove(responseObserver);
if (serviceWatchers.isEmpty()) {
watchers.remove(service);
}
}
}
});
}
void setStatus(String service, HealthCheckResponse.ServingStatus status) {
synchronized (watchLock) {
if (terminal) {
logger.info("Ignoring status " + status + " for " + service);
return;
}
setStatusInternal(service, status);
}
}
private void setStatusInternal(String service, HealthCheckResponse.ServingStatus status) {
HealthCheckResponse.ServingStatus prevStatus = statusMap.put(service, status);
if (prevStatus != status) {
notifyWatchers(service, status);
}
}
void clearStatus(String service) {
synchronized (watchLock) {
if (terminal) {
logger.info("Ignoring status clearing for " + service);
return;
}
HealthCheckResponse.ServingStatus prevStatus = statusMap.remove(service);
if (prevStatus != null) {
notifyWatchers(service, null);
}
}
}
void enterTerminalState() {
synchronized (watchLock) {
if (terminal) {
logger.warn(PROTOCOL_CLOSED_SERVER, "", "", "Already terminating", new RuntimeException());
return;
}
terminal = true;
for (String service : statusMap.keySet()) {
setStatusInternal(service, HealthCheckResponse.ServingStatus.NOT_SERVING);
}
}
}
private void notifyWatchers(String service, HealthCheckResponse.ServingStatus status) {
HealthCheckResponse response = getResponseForWatch(status);
IdentityHashMap<StreamObserver<HealthCheckResponse>, Boolean> serviceWatchers = watchers.get(service);
if (serviceWatchers != null) {
for (StreamObserver<HealthCheckResponse> responseObserver : serviceWatchers.keySet()) {
responseObserver.onNext(response);
}
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/Stream.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/Stream.java | /*
* 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.rpc.protocol.tri.stream;
import org.apache.dubbo.rpc.TriRpcStatus;
import javax.net.ssl.SSLSession;
import java.net.SocketAddress;
import io.netty.handler.codec.http2.Http2Headers;
import io.netty.util.concurrent.Future;
/**
* Stream is a bi-directional channel that manipulates the data flow between peers. Inbound data
* from remote peer is acquired by {@link Listener}. Outbound data to remote peer is sent directly
* by {@link Stream}. Backpressure is supported by {@link #request(int)}.
*/
public interface Stream {
/**
* Register a {@link Listener} to receive inbound data from remote peer.
*/
interface Listener {
/**
* Callback when receive message. Note this method may be called many times if is a
* streaming .
*
* @param message message received from remote peer
*/
void onMessage(byte[] message, boolean isReturnTriException);
/**
* Callback when receive cancel signal.
*
* @param status the cancel status
*/
void onCancelByRemote(TriRpcStatus status);
}
/**
* Send headers to remote peer.
*
* @param headers headers to send to remote peer
* @return future to callback when send headers is done
*/
Future<?> sendHeader(Http2Headers headers);
/**
* Cancel by this peer.
*
* @param status cancel status to send to remote peer
* @return future to callback when cancel is done
*/
Future<?> cancelByLocal(TriRpcStatus status);
/**
* Get remote peer address.
*
* @return socket address of remote peer
*/
SocketAddress remoteAddress();
/**
* Get ssl session.
*
* @return ssl session
*/
SSLSession getSslSession();
/**
* Request n message from remote peer.
*
* @param n number of message
*/
void request(int n);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/ClientStreamFactory.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/ClientStreamFactory.java | /*
* 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.rpc.protocol.tri.stream;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.remoting.api.connection.AbstractConnectionClient;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.protocol.tri.call.TripleClientCall;
import org.apache.dubbo.rpc.protocol.tri.transport.TripleWriteQueue;
import java.util.concurrent.Executor;
@SPI(scope = ExtensionScope.FRAMEWORK)
public interface ClientStreamFactory {
ClientStream createClientStream(
AbstractConnectionClient client,
FrameworkModel frameworkModel,
Executor executor,
TripleClientCall clientCall,
TripleWriteQueue writeQueue);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/AbstractStream.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/AbstractStream.java | /*
* 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.rpc.protocol.tri.stream;
import org.apache.dubbo.common.threadpool.serial.SerializingExecutor;
import org.apache.dubbo.common.utils.ClassUtils;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.concurrent.Executor;
/**
* An abstract stream implementation.
*/
public abstract class AbstractStream implements Stream {
protected Executor executor;
protected final FrameworkModel frameworkModel;
private static final boolean HAS_PROTOBUF = ClassUtils.hasProtobuf();
public AbstractStream(Executor executor, FrameworkModel frameworkModel) {
this.executor = new SerializingExecutor(executor);
this.frameworkModel = frameworkModel;
}
public void setExecutor(Executor executor) {
this.executor = new SerializingExecutor(executor);
}
public static boolean getGrpcStatusDetailEnabled() {
return HAS_PROTOBUF;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/TripleStreamChannelFuture.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/TripleStreamChannelFuture.java | /*
* 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.rpc.protocol.tri.stream;
import org.apache.dubbo.common.utils.Assert;
import java.util.concurrent.CompletableFuture;
import io.netty.channel.Channel;
import io.netty.handler.codec.http2.Http2StreamChannel;
public class TripleStreamChannelFuture extends CompletableFuture<Channel> {
private final Channel parentChannel;
private Throwable cause;
public TripleStreamChannelFuture(Channel parentChannel) {
Assert.notNull(parentChannel, "parentChannel cannot be null.");
this.parentChannel = parentChannel;
}
public TripleStreamChannelFuture(Http2StreamChannel channel) {
this.complete(channel);
this.parentChannel = channel.parent();
}
public Channel getParentChannel() {
return parentChannel;
}
@Override
public boolean completeExceptionally(Throwable cause) {
boolean result = super.completeExceptionally(cause);
if (result) {
this.cause = cause;
}
return result;
}
public Throwable cause() {
return cause;
}
public boolean isSuccess() {
return isDone() && cause() == null;
}
public Channel getNow() {
return getNow(null);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/ClientStream.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/ClientStream.java | /*
* 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.rpc.protocol.tri.stream;
import org.apache.dubbo.rpc.TriRpcStatus;
import java.util.Map;
import io.netty.util.concurrent.Future;
/**
* ClientStream is used to send request to server and receive response from server. Response is
* received by {@link ClientStream.Listener} Requests are sent by {@link ClientStream} directly.
*/
public interface ClientStream extends Stream {
interface Listener extends Stream.Listener {
/**
* Callback when stream started.
*/
void onStart();
/**
* Callback when stream completed.
*
* @param attachments received from remote peer
*/
default void onComplete(TriRpcStatus status, Map<String, Object> attachments) {}
/**
* Callback when request completed.
*
* @param status response status
* @param attachments attachments received from remote peer
* @param reserved triple protocol reserved data
*/
default void onComplete(
TriRpcStatus status,
Map<String, Object> attachments,
Map<CharSequence, String> reserved,
boolean isReturnTriException) {
onComplete(status, attachments);
}
void onClose();
}
/**
* Send message to remote peer.
*
* @param message message to send to remote peer
* @return future to callback when send message is done
*/
Future<?> sendMessage(byte[] message, int compressFlag);
/**
* No more data will be sent, half close this stream to wait server response.
*
* @return a future of send result
*/
Future<?> halfClose();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/AbstractTripleClientStream.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/AbstractTripleClientStream.java | /*
* 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.rpc.protocol.tri.stream;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.remoting.Constants;
import org.apache.dubbo.remoting.http12.HttpHeaderNames;
import org.apache.dubbo.rpc.TriRpcStatus;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.protocol.tri.ClassLoadUtil;
import org.apache.dubbo.rpc.protocol.tri.ExceptionUtils;
import org.apache.dubbo.rpc.protocol.tri.TripleHeaderEnum;
import org.apache.dubbo.rpc.protocol.tri.command.CancelQueueCommand;
import org.apache.dubbo.rpc.protocol.tri.command.DataQueueCommand;
import org.apache.dubbo.rpc.protocol.tri.command.EndStreamQueueCommand;
import org.apache.dubbo.rpc.protocol.tri.command.HeaderQueueCommand;
import org.apache.dubbo.rpc.protocol.tri.compressor.DeCompressor;
import org.apache.dubbo.rpc.protocol.tri.compressor.Identity;
import org.apache.dubbo.rpc.protocol.tri.frame.Deframer;
import org.apache.dubbo.rpc.protocol.tri.frame.TriDecoder;
import org.apache.dubbo.rpc.protocol.tri.h12.grpc.GrpcUtils;
import org.apache.dubbo.rpc.protocol.tri.transport.AbstractH2TransportListener;
import org.apache.dubbo.rpc.protocol.tri.transport.H2TransportListener;
import org.apache.dubbo.rpc.protocol.tri.transport.TripleWriteQueue;
import javax.net.ssl.SSLSession;
import java.io.IOException;
import java.net.SocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;
import com.google.protobuf.Any;
import com.google.rpc.DebugInfo;
import com.google.rpc.ErrorInfo;
import com.google.rpc.Status;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.handler.codec.http2.Http2Error;
import io.netty.handler.codec.http2.Http2Headers;
import io.netty.handler.codec.http2.Http2StreamChannel;
import io.netty.util.AttributeKey;
import io.netty.util.ReferenceCountUtil;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_RESPONSE;
/**
* ClientStream is an abstraction for bidirectional messaging. It maintains a {@link TripleWriteQueue} to
* write Http2Frame to remote. A {@link H2TransportListener} receives Http2Frame from remote.
* Instead of maintaining state, this class depends on upper layer or transport layer's states.
*/
public abstract class AbstractTripleClientStream extends AbstractStream implements ClientStream {
private static final ErrorTypeAwareLogger LOGGER =
LoggerFactory.getErrorTypeAwareLogger(AbstractTripleClientStream.class);
private static final AttributeKey<SSLSession> SSL_SESSION_KEY = AttributeKey.valueOf(Constants.SSL_SESSION_KEY);
private final ClientStream.Listener listener;
protected final TripleWriteQueue writeQueue;
private Deframer deframer;
private final Channel parent;
private final TripleStreamChannelFuture streamChannelFuture;
private boolean halfClosed;
private boolean rst;
private boolean isReturnTriException = false;
protected AbstractTripleClientStream(
FrameworkModel frameworkModel,
Executor executor,
TripleWriteQueue writeQueue,
ClientStream.Listener listener,
Http2StreamChannel http2StreamChannel) {
super(executor, frameworkModel);
this.parent = http2StreamChannel.parent();
this.listener = listener;
this.writeQueue = writeQueue;
this.streamChannelFuture = initStreamChannel(http2StreamChannel);
}
protected AbstractTripleClientStream(
FrameworkModel frameworkModel,
Executor executor,
TripleWriteQueue writeQueue,
ClientStream.Listener listener,
Channel parent) {
super(executor, frameworkModel);
this.parent = parent;
this.listener = listener;
this.writeQueue = writeQueue;
this.streamChannelFuture = initStreamChannel(parent);
}
protected abstract TripleStreamChannelFuture initStreamChannel(Channel parent);
public ChannelFuture sendHeader(Http2Headers headers) {
if (this.writeQueue == null) {
// already processed at createStream()
return parent.newFailedFuture(new IllegalStateException("Stream already closed"));
}
ChannelFuture checkResult = preCheck();
if (!checkResult.isSuccess()) {
return checkResult;
}
final HeaderQueueCommand headerCmd = HeaderQueueCommand.createHeaders(streamChannelFuture, headers);
return writeQueue.enqueueFuture(headerCmd, parent.eventLoop()).addListener(future -> {
if (!future.isSuccess()) {
transportException(future.cause());
}
});
}
private void transportException(Throwable cause) {
final TriRpcStatus status =
TriRpcStatus.INTERNAL.withDescription("Http2 exception").withCause(cause);
listener.onComplete(status, null, null, false);
}
public ChannelFuture cancelByLocal(TriRpcStatus status) {
ChannelFuture checkResult = preCheck();
if (!checkResult.isSuccess()) {
return checkResult;
}
final CancelQueueCommand cmd = CancelQueueCommand.createCommand(streamChannelFuture, Http2Error.CANCEL);
rst = true;
return this.writeQueue.enqueue(cmd);
}
@Override
public SocketAddress remoteAddress() {
return parent.remoteAddress();
}
@Override
public SSLSession getSslSession() {
return parent.attr(SSL_SESSION_KEY).get();
}
@Override
public ChannelFuture sendMessage(byte[] message, int compressFlag) {
ChannelFuture checkResult = preCheck();
if (!checkResult.isSuccess()) {
return checkResult;
}
final DataQueueCommand cmd = DataQueueCommand.create(streamChannelFuture, message, false, compressFlag);
return this.writeQueue.enqueueFuture(cmd, parent.eventLoop()).addListener(future -> {
if (!future.isSuccess()) {
cancelByLocal(TriRpcStatus.INTERNAL
.withDescription("Client write message failed")
.withCause(future.cause()));
transportException(future.cause());
}
});
}
@Override
public void request(int n) {
deframer.request(n);
}
@Override
public ChannelFuture halfClose() {
ChannelFuture checkResult = preCheck();
if (!checkResult.isSuccess()) {
return checkResult;
}
final EndStreamQueueCommand cmd = EndStreamQueueCommand.create(streamChannelFuture);
return this.writeQueue.enqueueFuture(cmd, parent.eventLoop()).addListener(future -> {
if (future.isSuccess()) {
halfClosed = true;
}
});
}
private ChannelFuture preCheck() {
if (rst) {
return streamChannelFuture.getNow().newFailedFuture(new IOException("stream channel has reset"));
}
return parent.newSucceededFuture();
}
/**
* @return transport listener
*/
protected H2TransportListener createTransportListener() {
return new ClientTransportListener();
}
class ClientTransportListener extends AbstractH2TransportListener implements H2TransportListener {
private TriRpcStatus transportError;
private DeCompressor decompressor;
private boolean headerReceived;
private Http2Headers trailers;
void handleH2TransportError(TriRpcStatus status) {
writeQueue.enqueue(CancelQueueCommand.createCommand(streamChannelFuture, Http2Error.NO_ERROR));
rst = true;
finishProcess(status, null, false);
}
void finishProcess(TriRpcStatus status, Http2Headers trailers, boolean isReturnTriException) {
final Map<CharSequence, String> reserved = filterReservedHeaders(trailers);
final Map<String, Object> attachments =
headersToMap(trailers, () -> reserved.get(TripleHeaderEnum.TRI_HEADER_CONVERT.getKey()));
final TriRpcStatus detailStatus;
final TriRpcStatus statusFromTrailers = getStatusFromTrailers(reserved);
if (statusFromTrailers != null) {
detailStatus = statusFromTrailers;
} else {
detailStatus = status;
}
listener.onComplete(detailStatus, attachments, reserved, isReturnTriException);
}
private TriRpcStatus validateHeaderStatus(Http2Headers headers) {
Integer httpStatus = headers.status() == null
? null
: Integer.parseInt(headers.status().toString());
if (httpStatus == null) {
return TriRpcStatus.INTERNAL.withDescription("Missing HTTP status code");
}
final CharSequence contentType = headers.get(HttpHeaderNames.CONTENT_TYPE.getKey());
if (contentType == null || !GrpcUtils.isGrpcRequest(contentType.toString())) {
return TriRpcStatus.fromCode(TriRpcStatus.httpStatusToGrpcCode(httpStatus))
.withDescription("HTTP status: " + httpStatus + ", invalid content-type: " + contentType);
}
return null;
}
void onHeaderReceived(Http2Headers headers) {
if (transportError != null) {
transportError.appendDescription("headers:" + headers);
return;
}
if (headerReceived) {
transportError = TriRpcStatus.INTERNAL.withDescription("Received headers twice");
return;
}
Integer httpStatus = headers.status() == null
? null
: Integer.parseInt(headers.status().toString());
if (httpStatus != null && Integer.parseInt(httpStatus.toString()) > 100 && httpStatus < 200) {
// ignored
return;
}
headerReceived = true;
transportError = validateHeaderStatus(headers);
// todo support full payload compressor
CharSequence messageEncoding = headers.get(TripleHeaderEnum.GRPC_ENCODING.getKey());
CharSequence triExceptionCode = headers.get(TripleHeaderEnum.TRI_EXCEPTION_CODE.getKey());
if (triExceptionCode != null) {
Integer triExceptionCodeNum = Integer.parseInt(triExceptionCode.toString());
if (!(triExceptionCodeNum.equals(CommonConstants.TRI_EXCEPTION_CODE_NOT_EXISTS))) {
isReturnTriException = true;
}
}
if (null != messageEncoding) {
String compressorStr = messageEncoding.toString();
if (!Identity.IDENTITY.getMessageEncoding().equals(compressorStr)) {
DeCompressor compressor = DeCompressor.getCompressor(frameworkModel, compressorStr);
if (null == compressor) {
throw TriRpcStatus.UNIMPLEMENTED
.withDescription(String.format("Grpc-encoding '%s' is not supported", compressorStr))
.asException();
} else {
decompressor = compressor;
}
}
}
TriDecoder.Listener listener = new TriDecoder.Listener() {
@Override
public void onRawMessage(byte[] data) {
AbstractTripleClientStream.this.listener.onMessage(data, isReturnTriException);
}
public void close() {
finishProcess(statusFromTrailers(trailers), trailers, isReturnTriException);
}
};
deframer = new TriDecoder(decompressor, listener);
AbstractTripleClientStream.this.listener.onStart();
}
void onTrailersReceived(Http2Headers trailers) {
if (transportError == null && !headerReceived) {
transportError = validateHeaderStatus(trailers);
}
this.trailers = trailers;
TriRpcStatus status;
if (transportError == null) {
status = statusFromTrailers(trailers);
} else {
transportError = transportError.appendDescription("trailers: " + trailers);
status = transportError;
}
if (deframer == null) {
finishProcess(status, trailers, false);
} else {
deframer.close();
}
}
/**
* Extract the response status from trailers.
*/
private TriRpcStatus statusFromTrailers(Http2Headers trailers) {
final Integer intStatus = trailers.getInt(TripleHeaderEnum.STATUS_KEY.getKey());
TriRpcStatus status = intStatus == null ? null : TriRpcStatus.fromCode(intStatus);
if (status != null) {
final CharSequence message = trailers.get(TripleHeaderEnum.MESSAGE_KEY.getKey());
if (message != null) {
final String description = TriRpcStatus.decodeMessage(message.toString());
status = status.withDescription(description);
}
return status;
}
// No status; something is broken. Try to provide a rational error.
if (headerReceived) {
return TriRpcStatus.UNKNOWN.withDescription("missing GRPC status in response");
}
Integer httpStatus = trailers.status() == null
? null
: Integer.parseInt(trailers.status().toString());
if (httpStatus != null) {
status = TriRpcStatus.fromCode(TriRpcStatus.httpStatusToGrpcCode(httpStatus));
} else {
status = TriRpcStatus.INTERNAL.withDescription("missing HTTP status code");
}
return status.appendDescription("missing GRPC status, inferred error from HTTP status code");
}
private TriRpcStatus getStatusFromTrailers(Map<CharSequence, String> metadata) {
if (null == metadata) {
return null;
}
if (!getGrpcStatusDetailEnabled()) {
return null;
}
// second get status detail
if (!metadata.containsKey(TripleHeaderEnum.STATUS_DETAIL_KEY.getKey())) {
return null;
}
final String raw = (metadata.remove(TripleHeaderEnum.STATUS_DETAIL_KEY.getKey()));
byte[] statusDetailBin = StreamUtils.decodeASCIIByte(raw);
ClassLoader tccl = Thread.currentThread().getContextClassLoader();
try {
final Status statusDetail = Status.parseFrom(statusDetailBin);
List<Any> detailList = statusDetail.getDetailsList();
Map<Class<?>, Object> classObjectMap = tranFromStatusDetails(detailList);
// get common exception from DebugInfo
TriRpcStatus status = TriRpcStatus.fromCode(statusDetail.getCode())
.withDescription(TriRpcStatus.decodeMessage(statusDetail.getMessage()));
DebugInfo debugInfo = (DebugInfo) classObjectMap.get(DebugInfo.class);
if (debugInfo != null) {
String msg = ExceptionUtils.getStackFrameString(debugInfo.getStackEntriesList());
status = status.appendDescription(msg);
}
return status;
} catch (IOException ioException) {
return null;
} finally {
ClassLoadUtil.switchContextLoader(tccl);
}
}
private Map<Class<?>, Object> tranFromStatusDetails(List<Any> detailList) {
Map<Class<?>, Object> map = new HashMap<>(detailList.size());
try {
for (Any any : detailList) {
if (any.is(ErrorInfo.class)) {
ErrorInfo errorInfo = any.unpack(ErrorInfo.class);
map.putIfAbsent(ErrorInfo.class, errorInfo);
} else if (any.is(DebugInfo.class)) {
DebugInfo debugInfo = any.unpack(DebugInfo.class);
map.putIfAbsent(DebugInfo.class, debugInfo);
}
// support others type but now only support this
}
} catch (Throwable t) {
LOGGER.error(PROTOCOL_FAILED_RESPONSE, "", "", "tran from grpc-status-details error", t);
}
return map;
}
@Override
public void onHeader(Http2Headers headers, boolean endStream) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("endStream: {} HEADERS: {}", endStream, headers);
}
executor.execute(() -> {
if (endStream) {
if (!halfClosed) {
Channel channel = streamChannelFuture.getNow();
if (channel.isActive() && !rst) {
writeQueue.enqueue(
CancelQueueCommand.createCommand(streamChannelFuture, Http2Error.CANCEL));
rst = true;
}
}
onTrailersReceived(headers);
} else {
onHeaderReceived(headers);
}
});
}
@Override
public void onData(ByteBuf data, boolean endStream) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("endStream: {} DATA: {}", endStream, data.toString(StandardCharsets.UTF_8));
}
try {
executor.execute(() -> doOnData(data, endStream));
} catch (Throwable t) {
// Tasks will be rejected when the thread pool is closed or full,
// ByteBuf needs to be released to avoid out of heap memory leakage.
// For example, ThreadLessExecutor will be shutdown when request timeout {@link AsyncRpcResult}
ReferenceCountUtil.release(data);
LOGGER.error(PROTOCOL_FAILED_RESPONSE, "", "", "submit onData task failed", t);
}
}
private void doOnData(ByteBuf data, boolean endStream) {
if (transportError != null) {
transportError.appendDescription("Data:" + data.toString(StandardCharsets.UTF_8));
ReferenceCountUtil.release(data);
if (transportError.description.length() > 512 || endStream) {
handleH2TransportError(transportError);
}
return;
}
if (!headerReceived) {
handleH2TransportError(TriRpcStatus.INTERNAL.withDescription("headers not received before payload"));
return;
}
deframer.deframe(data);
}
@Override
public void cancelByRemote(long errorCode) {
executor.execute(() -> {
transportError =
TriRpcStatus.CANCELLED.withDescription("Canceled by remote peer, errorCode=" + errorCode);
finishProcess(transportError, null, false);
});
}
@Override
public void onClose() {
executor.execute(listener::onClose);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/StreamUtils.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/StreamUtils.java | /*
* 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.rpc.protocol.tri.stream;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.common.utils.LRU2Cache;
import org.apache.dubbo.remoting.http12.HttpHeaders;
import org.apache.dubbo.rpc.TriRpcStatus;
import org.apache.dubbo.rpc.protocol.tri.TripleConstants;
import org.apache.dubbo.rpc.protocol.tri.TripleHeaderEnum;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.function.BiConsumer;
import io.netty.handler.codec.DateFormatter;
import io.netty.handler.codec.http2.DefaultHttp2Headers;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_PARSE;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_UNSUPPORTED;
public final class StreamUtils {
private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(StreamUtils.class);
private static final Base64.Decoder BASE64_DECODER = Base64.getDecoder();
private static final Base64.Encoder BASE64_ENCODER = Base64.getEncoder().withoutPadding();
private static final int MAX_LRU_HEADER_MAP_SIZE = 10000;
private static final Map<String, String> lruHeaderMap = new LRU2Cache<>(MAX_LRU_HEADER_MAP_SIZE);
private StreamUtils() {}
public static String encodeBase64ASCII(byte[] in) {
return new String(encodeBase64(in), StandardCharsets.US_ASCII);
}
public static byte[] encodeBase64(byte[] in) {
return BASE64_ENCODER.encode(in);
}
public static byte[] decodeASCIIByte(String value) {
return BASE64_DECODER.decode(value.getBytes(StandardCharsets.US_ASCII));
}
/**
* Parse and put attachments into headers.
* Ignore Http2 PseudoHeaderName and internal name.
* Only strings, dates, and byte arrays are allowed.
*
* @param headers the headers
* @param attachments the attachments
* @param needConvertHeaderKey whether need to convert the header key to lower-case
*/
public static void putHeaders(
DefaultHttp2Headers headers, Map<String, Object> attachments, boolean needConvertHeaderKey) {
putHeaders(attachments, needConvertHeaderKey, headers::set);
}
/**
* Parse and put attachments into headers.
* Ignore Http2 PseudoHeaderName and internal name.
* Only strings, dates, and byte arrays are allowed.
*
* @param headers the headers
* @param attachments the attachments
* @param needConvertHeaderKey whether need to convert the header key to lower-case
*/
public static void putHeaders(HttpHeaders headers, Map<String, Object> attachments, boolean needConvertHeaderKey) {
putHeaders(attachments, needConvertHeaderKey, headers::set);
}
private static void putHeaders(
Map<String, Object> attachments, boolean needConvertHeaderKey, BiConsumer<CharSequence, String> consumer) {
if (CollectionUtils.isEmptyMap(attachments)) {
return;
}
Map<String, String> needConvertKeys = new HashMap<>();
for (Map.Entry<String, Object> entry : attachments.entrySet()) {
Object value = entry.getValue();
if (value == null) {
continue;
}
String key = entry.getKey();
String lowerCaseKey = lruHeaderMap.computeIfAbsent(key, k -> k.toLowerCase(Locale.ROOT));
if (TripleHeaderEnum.containsExcludeAttachments(lowerCaseKey)) {
continue;
}
if (needConvertHeaderKey && !lowerCaseKey.equals(key)) {
needConvertKeys.put(lowerCaseKey, key);
}
putHeader(consumer, lowerCaseKey, value);
}
if (needConvertKeys.isEmpty()) {
return;
}
consumer.accept(
TripleHeaderEnum.TRI_HEADER_CONVERT.getKey(),
TriRpcStatus.encodeMessage(JsonUtils.toJson(needConvertKeys)));
}
/**
* Put a KV pairs into headers.
*
* @param consumer outbound headers consumer
* @param key the key of the attachment
* @param value the value of the attachment (Only strings, dates, and byte arrays are allowed in the attachment value.)
*/
private static void putHeader(BiConsumer<CharSequence, String> consumer, String key, Object value) {
try {
if (value instanceof CharSequence || value instanceof Number || value instanceof Boolean) {
String str = value.toString();
consumer.accept(key, str);
} else if (value instanceof Date) {
consumer.accept(key, DateFormatter.format((Date) value));
} else if (value instanceof byte[]) {
String str = encodeBase64ASCII((byte[]) value);
consumer.accept(key + TripleConstants.HEADER_BIN_SUFFIX, str);
} else {
LOGGER.warn(
PROTOCOL_UNSUPPORTED,
"",
"",
"Unsupported attachment k: " + key + " class: "
+ value.getClass().getName());
}
} catch (Throwable t) {
LOGGER.warn(
PROTOCOL_UNSUPPORTED,
"",
"",
"Meet exception when convert single attachment key:" + key + " value=" + value,
t);
}
}
/**
* Convert the given map to attachments. Ignore Http2 PseudoHeaderName and internal name.
*
* @param map The map
* @return the attachments
*/
public static Map<String, Object> toAttachments(Map<String, Object> map) {
if (CollectionUtils.isEmptyMap(map)) {
return Collections.emptyMap();
}
Map<String, Object> res = CollectionUtils.newHashMap(map.size());
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
if (TripleHeaderEnum.containsExcludeAttachments(key)) {
continue;
}
res.put(key, entry.getValue());
}
return res;
}
/**
* Parse and convert headers to attachments. Ignore Http2 PseudoHeaderName and internal name.
*
* @param headers the headers
* @return the attachments
*/
public static Map<String, Object> toAttachments(HttpHeaders headers) {
if (headers == null) {
return Collections.emptyMap();
}
Map<String, Object> attachments = CollectionUtils.newHashMap(headers.size());
for (Map.Entry<CharSequence, String> entry : headers) {
String key = entry.getKey().toString();
String value = entry.getValue();
int len = key.length() - TripleConstants.HEADER_BIN_SUFFIX.length();
if (len > 0 && TripleConstants.HEADER_BIN_SUFFIX.equals(key.substring(len))) {
try {
putAttachment(attachments, key.substring(0, len), value == null ? null : decodeASCIIByte(value));
} catch (Exception e) {
LOGGER.error(PROTOCOL_FAILED_PARSE, "", "", "Failed to parse response attachment key=" + key, e);
}
} else {
putAttachment(attachments, key, value);
}
}
// try converting upper key
String converted = headers.getFirst(TripleHeaderEnum.TRI_HEADER_CONVERT.getKey());
if (converted == null) {
return attachments;
}
String json = TriRpcStatus.decodeMessage(converted);
Map<String, String> map = JsonUtils.toJavaObject(json, Map.class);
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
Object value = attachments.remove(key);
if (value != null) {
putAttachment(attachments, entry.getValue(), value);
}
}
return attachments;
}
/**
* Put a KV pairs into attachments.
*
* @param attachments the map to which the attachment will be added
* @param key the key of the header
* @param value the value of the header
*/
private static void putAttachment(Map<String, Object> attachments, String key, Object value) {
if (TripleHeaderEnum.containsExcludeAttachments(key)) {
return;
}
attachments.put(key, value);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/HeaderQueueCommand.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/HeaderQueueCommand.java | /*
* 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.rpc.protocol.tri.command;
import org.apache.dubbo.rpc.protocol.tri.stream.TripleStreamChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http2.DefaultHttp2HeadersFrame;
import io.netty.handler.codec.http2.Http2Headers;
public class HeaderQueueCommand extends StreamQueueCommand {
private final Http2Headers headers;
private final boolean endStream;
private HeaderQueueCommand(TripleStreamChannelFuture streamChannelFuture, Http2Headers headers, boolean endStream) {
super(streamChannelFuture);
this.headers = headers;
this.endStream = endStream;
}
public static HeaderQueueCommand createHeaders(
TripleStreamChannelFuture streamChannelFuture, Http2Headers headers) {
return new HeaderQueueCommand(streamChannelFuture, headers, false);
}
public static HeaderQueueCommand createHeaders(
TripleStreamChannelFuture streamChannelFuture, Http2Headers headers, boolean endStream) {
return new HeaderQueueCommand(streamChannelFuture, headers, endStream);
}
public Http2Headers getHeaders() {
return headers;
}
public boolean isEndStream() {
return endStream;
}
@Override
public void doSend(ChannelHandlerContext ctx, ChannelPromise promise) {
ctx.write(new DefaultHttp2HeadersFrame(headers, endStream), promise);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/EndStreamQueueCommand.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/EndStreamQueueCommand.java | /*
* 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.rpc.protocol.tri.command;
import org.apache.dubbo.rpc.protocol.tri.stream.TripleStreamChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http2.DefaultHttp2DataFrame;
public class EndStreamQueueCommand extends StreamQueueCommand {
public EndStreamQueueCommand(TripleStreamChannelFuture streamChannelFuture) {
super(streamChannelFuture);
}
public static EndStreamQueueCommand create(TripleStreamChannelFuture streamChannelFuture) {
return new EndStreamQueueCommand(streamChannelFuture);
}
@Override
public void doSend(ChannelHandlerContext ctx, ChannelPromise promise) {
ctx.write(new DefaultHttp2DataFrame(true), promise);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/Http3CreateStreamQueueCommand.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/Http3CreateStreamQueueCommand.java | /*
* 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.rpc.protocol.tri.command;
import org.apache.dubbo.rpc.protocol.tri.stream.TripleStreamChannelFuture;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http3.Http3;
import io.netty.handler.codec.quic.QuicChannel;
import io.netty.handler.codec.quic.QuicStreamChannel;
public class Http3CreateStreamQueueCommand extends QueuedCommand {
private final ChannelInitializer<QuicStreamChannel> initializer;
private final TripleStreamChannelFuture streamChannelFuture;
private Http3CreateStreamQueueCommand(
ChannelInitializer<QuicStreamChannel> initializer, TripleStreamChannelFuture future) {
this.initializer = initializer;
this.streamChannelFuture = future;
this.promise(future.getParentChannel().newPromise());
this.channel(future.getParentChannel());
}
public static Http3CreateStreamQueueCommand create(
ChannelInitializer<QuicStreamChannel> initializer, TripleStreamChannelFuture future) {
return new Http3CreateStreamQueueCommand(initializer, future);
}
@Override
public void doSend(ChannelHandlerContext ctx, ChannelPromise promise) {}
@Override
public void run(Channel channel) {
Http3.newRequestStream((QuicChannel) channel, initializer).addListener(future -> {
if (future.isSuccess()) {
streamChannelFuture.complete((Channel) future.getNow());
} else {
streamChannelFuture.completeExceptionally(future.cause());
}
});
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/StreamQueueCommand.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/StreamQueueCommand.java | /*
* 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.rpc.protocol.tri.command;
import org.apache.dubbo.common.utils.Assert;
import org.apache.dubbo.rpc.protocol.tri.stream.TripleStreamChannelFuture;
import io.netty.channel.Channel;
public abstract class StreamQueueCommand extends QueuedCommand {
protected final TripleStreamChannelFuture streamChannelFuture;
protected StreamQueueCommand(TripleStreamChannelFuture streamChannelFuture) {
Assert.notNull(streamChannelFuture, "streamChannelFuture cannot be null.");
this.streamChannelFuture = streamChannelFuture;
this.promise(streamChannelFuture.getParentChannel().newPromise());
}
@Override
public void run(Channel channel) {
if (streamChannelFuture.isSuccess()) {
super.run(channel);
return;
}
promise().setFailure(streamChannelFuture.cause());
}
@Override
public Channel channel() {
return this.streamChannelFuture.getNow();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/TextDataQueueCommand.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/TextDataQueueCommand.java | /*
* 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.rpc.protocol.tri.command;
import org.apache.dubbo.rpc.protocol.tri.stream.TripleStreamChannelFuture;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http2.DefaultHttp2DataFrame;
public class TextDataQueueCommand extends StreamQueueCommand {
private final String data;
private final boolean endStream;
private TextDataQueueCommand(TripleStreamChannelFuture streamChannelFuture, String text, boolean endStream) {
super(streamChannelFuture);
this.data = text;
this.endStream = endStream;
}
public static TextDataQueueCommand createCommand(
TripleStreamChannelFuture streamChannelFuture, String data, boolean endStream) {
return new TextDataQueueCommand(streamChannelFuture, data, endStream);
}
@Override
public void doSend(ChannelHandlerContext ctx, ChannelPromise promise) {
ByteBuf buf = ByteBufUtil.writeUtf8(ctx.alloc(), data);
ctx.write(new DefaultHttp2DataFrame(buf, endStream), promise);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/CancelQueueCommand.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/CancelQueueCommand.java | /*
* 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.rpc.protocol.tri.command;
import org.apache.dubbo.rpc.protocol.tri.stream.TripleStreamChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http2.DefaultHttp2ResetFrame;
import io.netty.handler.codec.http2.Http2Error;
public class CancelQueueCommand extends StreamQueueCommand {
private final Http2Error error;
public CancelQueueCommand(TripleStreamChannelFuture streamChannelFuture, Http2Error error) {
super(streamChannelFuture);
this.error = error;
}
public static CancelQueueCommand createCommand(TripleStreamChannelFuture streamChannelFuture, Http2Error error) {
return new CancelQueueCommand(streamChannelFuture, error);
}
@Override
public void doSend(ChannelHandlerContext ctx, ChannelPromise promise) {
ctx.write(new DefaultHttp2ResetFrame(error), promise);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/QueuedCommand.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/QueuedCommand.java | /*
* 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.rpc.protocol.tri.command;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
public abstract class QueuedCommand {
protected Channel channel;
private ChannelPromise promise;
public ChannelPromise promise() {
return promise;
}
public void promise(ChannelPromise promise) {
this.promise = promise;
}
public void cancel() {
promise.tryFailure(new IllegalStateException("Canceled"));
}
public void run(Channel channel) {
if (channel.isActive()) {
channel.write(this).addListener(future -> {
if (future.isSuccess()) {
promise.setSuccess();
} else {
promise.setFailure(future.cause());
}
});
} else {
promise.trySuccess();
}
}
public final void send(ChannelHandlerContext ctx, ChannelPromise promise) {
if (ctx.channel().isActive()) {
doSend(ctx, promise);
}
}
public QueuedCommand channel(Channel channel) {
this.channel = channel;
return this;
}
public Channel channel() {
return channel;
}
public abstract void doSend(ChannelHandlerContext ctx, ChannelPromise promise);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/DataQueueCommand.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/DataQueueCommand.java | /*
* 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.rpc.protocol.tri.command;
import org.apache.dubbo.rpc.protocol.tri.stream.TripleStreamChannelFuture;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http2.DefaultHttp2DataFrame;
public class DataQueueCommand extends StreamQueueCommand {
private final byte[] data;
private final int compressFlag;
private final boolean endStream;
private DataQueueCommand(
TripleStreamChannelFuture streamChannelFuture, byte[] data, int compressFlag, boolean endStream) {
super(streamChannelFuture);
this.data = data;
this.compressFlag = compressFlag;
this.endStream = endStream;
}
public static DataQueueCommand create(
TripleStreamChannelFuture streamChannelFuture, byte[] data, boolean endStream, int compressFlag) {
return new DataQueueCommand(streamChannelFuture, data, compressFlag, endStream);
}
@Override
public void doSend(ChannelHandlerContext ctx, ChannelPromise promise) {
if (data == null) {
ctx.write(new DefaultHttp2DataFrame(endStream), promise);
} else {
ByteBuf buf = ctx.alloc().buffer();
buf.writeByte(compressFlag);
buf.writeInt(data.length);
buf.writeBytes(data);
ctx.write(new DefaultHttp2DataFrame(buf, endStream), promise);
}
}
// for test
public byte[] getData() {
return data;
}
// for test
public boolean isEndStream() {
return endStream;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/CreateStreamQueueCommand.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/CreateStreamQueueCommand.java | /*
* 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.rpc.protocol.tri.command;
import org.apache.dubbo.rpc.protocol.tri.stream.TripleStreamChannelFuture;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http2.Http2StreamChannel;
import io.netty.handler.codec.http2.Http2StreamChannelBootstrap;
import io.netty.util.concurrent.Future;
public class CreateStreamQueueCommand extends QueuedCommand {
private final Http2StreamChannelBootstrap bootstrap;
private final TripleStreamChannelFuture streamChannelFuture;
private CreateStreamQueueCommand(
Http2StreamChannelBootstrap bootstrap, TripleStreamChannelFuture streamChannelFuture) {
this.bootstrap = bootstrap;
this.streamChannelFuture = streamChannelFuture;
this.promise(streamChannelFuture.getParentChannel().newPromise());
this.channel(streamChannelFuture.getParentChannel());
}
public static CreateStreamQueueCommand create(
Http2StreamChannelBootstrap bootstrap, TripleStreamChannelFuture streamChannelFuture) {
return new CreateStreamQueueCommand(bootstrap, streamChannelFuture);
}
@Override
public void doSend(ChannelHandlerContext ctx, ChannelPromise promise) {
// NOOP
}
@Override
public void run(Channel channel) {
// work in I/O thread
Future<Http2StreamChannel> future = bootstrap.open();
if (future.isSuccess()) {
streamChannelFuture.complete(future.getNow());
} else {
streamChannelFuture.completeExceptionally(future.cause());
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/ClientCall.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/ClientCall.java | /*
* 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.rpc.protocol.tri.call;
import org.apache.dubbo.common.stream.StreamObserver;
import org.apache.dubbo.rpc.TriRpcStatus;
import org.apache.dubbo.rpc.protocol.tri.RequestMetadata;
import java.util.Map;
/**
* ClientCall does not care about transport layer details.
*/
public interface ClientCall {
/**
* Listener for receive response.
*/
interface Listener {
/**
* Called when the call is started, user can use this to set some configurations.
*
* @param call call implementation
*/
void onStart(ClientCall call);
/**
* Callback when message received.
*
* @param message message received
* @param actualContentLength actual content length from body
*/
void onMessage(Object message, int actualContentLength);
/**
* Callback when call is finished.
*
* @param status response status
* @param trailers response trailers
*/
void onClose(TriRpcStatus status, Map<String, Object> trailers, boolean isReturnTriException);
}
/**
* Send reset to server, no more data will be sent or received.
*
* @param t cause
*/
void cancelByLocal(Throwable t);
/**
* Request max n message from server
*
* @param messageNumber max message number
*/
void request(int messageNumber);
/**
* Send message to server
*
* @param message request to send
*/
void sendMessage(Object message);
/**
* @param metadata request metadata
* @param responseListener the listener to receive response
* @return the stream observer representing the request sink
*/
StreamObserver<Object> start(RequestMetadata metadata, Listener responseListener);
/**
* @return true if this call is auto request
*/
boolean isAutoRequest();
/**
* Set auto request for this call
*
* @param autoRequest whether auto request is enabled
*/
void setAutoRequest(boolean autoRequest);
/**
* No more data will be sent.
*/
void halfClose();
/**
* Set compression algorithm for request.
*
* @param compression compression algorithm
*/
void setCompression(String compression);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/ObserverToClientCallListenerAdapter.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/ObserverToClientCallListenerAdapter.java | /*
* 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.rpc.protocol.tri.call;
import org.apache.dubbo.common.stream.StreamObserver;
import org.apache.dubbo.rpc.TriRpcStatus;
import java.util.Map;
import java.util.function.Consumer;
public class ObserverToClientCallListenerAdapter implements ClientCall.Listener {
private final StreamObserver<Object> delegate;
private ClientCall call;
private Consumer<ClientCall> onStartConsumer = clientCall -> {};
public ObserverToClientCallListenerAdapter(StreamObserver<Object> delegate) {
this.delegate = delegate;
}
public void setOnStartConsumer(Consumer<ClientCall> onStartConsumer) {
this.onStartConsumer = onStartConsumer;
}
@Override
public void onMessage(Object message, int actualContentLength) {
delegate.onNext(message);
if (call.isAutoRequest()) {
call.request(1);
}
}
@Override
public void onClose(TriRpcStatus status, Map<String, Object> trailers, boolean isReturnTriException) {
if (status.isOk()) {
delegate.onCompleted();
} else {
delegate.onError(status.asException());
}
}
@Override
public void onStart(ClientCall call) {
this.call = call;
if (call.isAutoRequest()) {
call.request(1);
}
onStartConsumer.accept(call);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/UnaryClientCallListener.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/UnaryClientCallListener.java | /*
* 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.rpc.protocol.tri.call;
import org.apache.dubbo.remoting.Constants;
import org.apache.dubbo.rpc.AppResponse;
import org.apache.dubbo.rpc.TriRpcStatus;
import org.apache.dubbo.rpc.protocol.tri.DeadlineFuture;
import java.util.Map;
public class UnaryClientCallListener implements ClientCall.Listener {
private final DeadlineFuture future;
private Object appResponse;
private int actualContentLength;
public UnaryClientCallListener(DeadlineFuture deadlineFuture) {
this.future = deadlineFuture;
}
@Override
public void onMessage(Object message, int actualContentLength) {
this.appResponse = message;
this.actualContentLength = actualContentLength;
}
@Override
public void onClose(TriRpcStatus status, Map<String, Object> trailers, boolean isReturnTriException) {
AppResponse result = new AppResponse();
result.setObjectAttachments(trailers);
if (status.isOk()) {
if (isReturnTriException) {
result.setException((Exception) appResponse);
} else {
result.setValue(appResponse);
}
} else {
result.setException(status.asException());
}
result.setAttribute(Constants.CONTENT_LENGTH_KEY, actualContentLength);
future.received(status, result);
}
@Override
public void onStart(ClientCall call) {
future.addTimeoutListener(() -> call.cancelByLocal(new IllegalStateException("client timeout")));
call.request(2);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/TripleClientCall.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/TripleClientCall.java | /*
* 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.rpc.protocol.tri.call;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.stream.StreamObserver;
import org.apache.dubbo.remoting.api.connection.AbstractConnectionClient;
import org.apache.dubbo.rpc.TriRpcStatus;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.protocol.tri.RequestMetadata;
import org.apache.dubbo.rpc.protocol.tri.compressor.Compressor;
import org.apache.dubbo.rpc.protocol.tri.compressor.Identity;
import org.apache.dubbo.rpc.protocol.tri.observer.ClientCallToObserverAdapter;
import org.apache.dubbo.rpc.protocol.tri.stream.ClientStream;
import org.apache.dubbo.rpc.protocol.tri.stream.ClientStreamFactory;
import org.apache.dubbo.rpc.protocol.tri.stream.StreamUtils;
import org.apache.dubbo.rpc.protocol.tri.transport.TripleWriteQueue;
import java.util.Map;
import java.util.concurrent.Executor;
import io.netty.handler.codec.http2.Http2Exception.StreamException;
import static io.netty.handler.codec.http2.Http2Error.FLOW_CONTROL_ERROR;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_RESPONSE;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_SERIALIZE_TRIPLE;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_STREAM_LISTENER;
public class TripleClientCall implements ClientCall, ClientStream.Listener {
private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(TripleClientCall.class);
private final AbstractConnectionClient connectionClient;
private final Executor executor;
private final FrameworkModel frameworkModel;
private final TripleWriteQueue writeQueue;
private RequestMetadata requestMetadata;
private ClientStream stream;
private ClientCall.Listener listener;
private boolean canceled;
private boolean headerSent;
private boolean autoRequest = true;
private boolean done;
private StreamException streamException;
public TripleClientCall(
AbstractConnectionClient connectionClient,
Executor executor,
FrameworkModel frameworkModel,
TripleWriteQueue writeQueue) {
this.connectionClient = connectionClient;
this.executor = executor;
this.frameworkModel = frameworkModel;
this.writeQueue = writeQueue;
}
// stream listener start
@Override
public void onMessage(byte[] message, boolean isReturnTriException) {
if (done) {
LOGGER.warn(
PROTOCOL_STREAM_LISTENER,
"",
"",
"Received message from closed stream,connection=" + connectionClient + " service="
+ requestMetadata.service + " method="
+ requestMetadata.method.getMethodName());
return;
}
try {
Object unpacked = requestMetadata.packableMethod.parseResponse(message, isReturnTriException);
listener.onMessage(unpacked, message.length);
} catch (Throwable t) {
TriRpcStatus status = TriRpcStatus.INTERNAL
.withDescription("Deserialize response failed")
.withCause(t);
cancelByLocal(status.asException());
listener.onClose(status, null, false);
LOGGER.error(
PROTOCOL_FAILED_RESPONSE,
"",
"",
String.format(
"Failed to deserialize triple response, service=%s, method=%s,connection=%s",
requestMetadata.service, requestMetadata.service, requestMetadata.method.getMethodName()),
t);
}
}
@Override
public void onCancelByRemote(TriRpcStatus status) {
if (canceled) {
return;
}
canceled = true;
if (requestMetadata.cancellationContext != null) {
requestMetadata.cancellationContext.cancel(status.asException());
}
onComplete(status, null, null, false);
}
@Override
public void onComplete(
TriRpcStatus status,
Map<String, Object> attachments,
Map<CharSequence, String> excludeHeaders,
boolean isReturnTriException) {
if (done) {
return;
}
done = true;
try {
listener.onClose(status, StreamUtils.toAttachments(attachments), isReturnTriException);
} catch (Throwable t) {
cancelByLocal(TriRpcStatus.INTERNAL
.withDescription("Close stream error")
.withCause(t)
.asException());
}
if (requestMetadata.cancellationContext != null) {
requestMetadata.cancellationContext.cancel(null);
}
}
@Override
public void onClose() {
if (done) {
return;
}
onCancelByRemote(TriRpcStatus.CANCELLED);
}
@Override
public void onStart() {
listener.onStart(this);
}
@Override
public void cancelByLocal(Throwable t) {
if (canceled) {
return;
}
// did not create stream
if (!headerSent) {
return;
}
canceled = true;
if (stream == null) {
return;
}
if (t instanceof StreamException && ((StreamException) t).error().equals(FLOW_CONTROL_ERROR)) {
TriRpcStatus status = TriRpcStatus.CANCELLED
.withCause(t)
.withDescription("Due flowcontrol over pendingbytes, Cancelled by client");
stream.cancelByLocal(status);
streamException = (StreamException) t;
} else {
TriRpcStatus status = TriRpcStatus.CANCELLED.withCause(t).withDescription("Cancelled by client");
stream.cancelByLocal(status);
}
TriRpcStatus status = TriRpcStatus.CANCELLED.withCause(t).withDescription("Cancelled by client");
stream.cancelByLocal(status);
if (requestMetadata.cancellationContext != null) {
requestMetadata.cancellationContext.cancel(t);
}
}
@Override
public void request(int messageNumber) {
stream.request(messageNumber);
}
@Override
public void sendMessage(Object message) {
if (canceled && null != streamException) {
throw new IllegalStateException("Due flowcontrol over pendingbytes, Call already canceled");
} else if (canceled) {
throw new IllegalStateException("Call already canceled");
}
if (!headerSent) {
headerSent = true;
stream.sendHeader(requestMetadata.toHeaders());
}
final byte[] data;
try {
data = requestMetadata.packableMethod.packRequest(message);
int compressed = Identity.MESSAGE_ENCODING.equals(requestMetadata.compressor.getMessageEncoding()) ? 0 : 1;
final byte[] compress = requestMetadata.compressor.compress(data);
stream.sendMessage(compress, compressed).addListener(f -> {
if (!f.isSuccess()) {
cancelByLocal(f.cause());
}
});
} catch (Throwable t) {
LOGGER.error(
PROTOCOL_FAILED_SERIALIZE_TRIPLE,
"",
"",
String.format(
"Serialize triple request failed, service=%s method=%s",
requestMetadata.service, requestMetadata.method.getMethodName()),
t);
cancelByLocal(t);
listener.onClose(
TriRpcStatus.INTERNAL
.withDescription("Serialize request failed")
.withCause(t),
null,
false);
}
}
// stream listener end
@Override
public void halfClose() {
if (!headerSent) {
return;
}
if (canceled) {
return;
}
stream.halfClose().addListener(f -> {
if (!f.isSuccess()) {
cancelByLocal(new IllegalStateException("Half close failed", f.cause()));
}
});
}
@Override
public void setCompression(String compression) {
requestMetadata.compressor = Compressor.getCompressor(frameworkModel, compression);
}
@Override
public StreamObserver<Object> start(RequestMetadata metadata, ClientCall.Listener responseListener) {
ClientStream stream;
for (ClientStreamFactory factory : frameworkModel.getActivateExtensions(ClientStreamFactory.class)) {
stream = factory.createClientStream(connectionClient, frameworkModel, executor, this, writeQueue);
if (stream != null) {
this.requestMetadata = metadata;
this.listener = responseListener;
this.stream = stream;
return new ClientCallToObserverAdapter<>(this);
}
}
throw new IllegalStateException("No available ClientStreamFactory");
}
@Override
public boolean isAutoRequest() {
return autoRequest;
}
@Override
public void setAutoRequest(boolean autoRequest) {
this.autoRequest = autoRequest;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/observer/CallStreamObserver.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/observer/CallStreamObserver.java | /*
* 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.rpc.protocol.tri.observer;
import org.apache.dubbo.common.stream.StreamObserver;
import org.apache.dubbo.rpc.protocol.tri.compressor.Compressor;
public interface CallStreamObserver<T> extends StreamObserver<T> {
/**
* Requests the peer to produce {@code count} more messages to be delivered to the 'inbound'
* {@link StreamObserver}.
*
* <p>This method is safe to call from multiple threads without external synchronization.
*
* @param count more messages
*/
void request(int count);
/**
* Sets the compression algorithm to use for the call
* <p>
* For stream set compression needs to determine whether the metadata has been sent, and carry
* on corresponding processing
*
* @param compression {@link Compressor}
*/
void setCompression(String compression);
/**
* Swaps to manual flow control where no message will be delivered to {@link
* StreamObserver#onNext(Object)} unless it is {@link #request request()}ed. Since {@code
* request()} may not be called before the call is started, a number of initial requests may be
* specified.
*/
void disableAutoFlowControl();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/observer/ClientCallToObserverAdapter.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/observer/ClientCallToObserverAdapter.java | /*
* 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.rpc.protocol.tri.observer;
import org.apache.dubbo.rpc.protocol.tri.CancelableStreamObserver;
import org.apache.dubbo.rpc.protocol.tri.ClientStreamObserver;
import org.apache.dubbo.rpc.protocol.tri.call.ClientCall;
public class ClientCallToObserverAdapter<T> extends CancelableStreamObserver<T> implements ClientStreamObserver<T> {
private final ClientCall call;
private boolean terminated;
public ClientCallToObserverAdapter(ClientCall call) {
this.call = call;
}
public boolean isAutoRequestEnabled() {
return call.isAutoRequest();
}
@Override
public void onNext(Object data) {
if (terminated) {
throw new IllegalStateException("Stream observer has been terminated, no more data is allowed");
}
call.sendMessage(data);
}
@Override
public void onError(Throwable throwable) {
call.cancelByLocal(throwable);
this.terminated = true;
}
@Override
public void onCompleted() {
if (terminated) {
return;
}
call.halfClose();
this.terminated = true;
}
@Override
public void cancel(Throwable throwable) {
call.cancelByLocal(throwable);
this.terminated = true;
}
@Override
public void setCompression(String compression) {
call.setCompression(compression);
}
@Override
public void request(int count) {
call.request(count);
}
@Override
public void disableAutoFlowControl() {
call.setAutoRequest(false);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/HttpContextFilter.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/HttpContextFilter.java | /*
* 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.rpc.protocol.tri.h12;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.remoting.http12.HttpRequest;
import org.apache.dubbo.remoting.http12.HttpResponse;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.RpcServiceContext;
import org.apache.dubbo.rpc.protocol.tri.TripleConstants;
@Activate(group = CommonConstants.PROVIDER, order = -29000)
public class HttpContextFilter implements Filter {
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
if (invocation.get(TripleConstants.HANDLER_TYPE_KEY) == null) {
return invoker.invoke(invocation);
}
HttpRequest request = (HttpRequest) invocation.get(TripleConstants.HTTP_REQUEST_KEY);
HttpResponse response = (HttpResponse) invocation.get(TripleConstants.HTTP_RESPONSE_KEY);
RpcServiceContext context = RpcContext.getServiceContext();
context.setRemoteAddress(request.remoteHost(), request.remotePort());
if (context.getLocalAddress() == null) {
context.setLocalAddress(request.localHost(), request.localPort());
}
context.setRequest(request);
context.setResponse(response);
return invoker.invoke(invocation);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/HttpResultPayloadExceptionHandler.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/HttpResultPayloadExceptionHandler.java | /*
* 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.rpc.protocol.tri.h12;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.logger.Level;
import org.apache.dubbo.remoting.http12.ExceptionHandler;
import org.apache.dubbo.remoting.http12.HttpResult;
import org.apache.dubbo.remoting.http12.RequestMetadata;
import org.apache.dubbo.remoting.http12.exception.HttpResultPayloadException;
import org.apache.dubbo.rpc.model.MethodDescriptor;
@Activate(order = -1000)
public final class HttpResultPayloadExceptionHandler implements ExceptionHandler<HttpResultPayloadException, Object> {
@Override
public Level resolveLogLevel(HttpResultPayloadException throwable) {
return Level.DEBUG;
}
@Override
public Object handle(HttpResultPayloadException e, RequestMetadata metadata, MethodDescriptor descriptor) {
return e.getResult();
}
@Override
public Object handleGrpc(HttpResultPayloadException e, RequestMetadata metadata, MethodDescriptor descriptor) {
return HttpResult.of(e);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/DefaultHttpMessageListener.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/DefaultHttpMessageListener.java | /*
* 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.rpc.protocol.tri.h12;
import org.apache.dubbo.remoting.http12.message.ListeningDecoder;
import java.io.InputStream;
public class DefaultHttpMessageListener implements HttpMessageListener {
private ListeningDecoder listeningDecoder;
public DefaultHttpMessageListener() {}
public DefaultHttpMessageListener(ListeningDecoder listeningDecoder) {
this.listeningDecoder = listeningDecoder;
}
public void setListeningDecoder(ListeningDecoder listeningDecoder) {
this.listeningDecoder = listeningDecoder;
}
@Override
public void onMessage(InputStream inputStream) {
listeningDecoder.decode(inputStream);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/HttpContextCallbackFilter.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/HttpContextCallbackFilter.java | /*
* 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.rpc.protocol.tri.h12;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.remoting.http12.HttpResponse;
import org.apache.dubbo.remoting.http12.HttpResult;
import org.apache.dubbo.remoting.http12.exception.HttpResultPayloadException;
import org.apache.dubbo.rpc.BaseFilter;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.protocol.tri.TripleConstants;
@Activate(group = CommonConstants.PROVIDER, order = 10)
public class HttpContextCallbackFilter implements Filter, BaseFilter.Listener {
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
return invoker.invoke(invocation);
}
@Override
public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) {
Object handlerType = invocation.get(TripleConstants.HANDLER_TYPE_KEY);
if (handlerType == null) {
return;
}
Throwable exception = appResponse.getException();
if (exception instanceof HttpResultPayloadException) {
Object value = TripleConstants.TRIPLE_HANDLER_TYPE_GRPC.equals(handlerType)
? HttpResult.of(exception)
: ((HttpResultPayloadException) exception).getResult();
appResponse.setValue(value);
appResponse.setException(null);
return;
}
HttpResponse response = (HttpResponse) invocation.get(TripleConstants.HTTP_RESPONSE_KEY);
if (response.isEmpty()) {
return;
}
if (!response.isCommitted()) {
if (response.isContentEmpty()) {
response.setBody(appResponse.hasException() ? appResponse.getException() : appResponse.getValue());
}
response.commit();
}
HttpResult<Object> result = response.toHttpResult();
if (result.getBody() instanceof Throwable) {
appResponse.setException((Throwable) result.getBody());
} else {
appResponse.setValue(result);
appResponse.setException(null);
}
}
@Override
public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) {}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/UnaryServerCallListener.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/UnaryServerCallListener.java | /*
* 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.rpc.protocol.tri.h12;
import org.apache.dubbo.common.stream.StreamObserver;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcInvocation;
public class UnaryServerCallListener extends AbstractServerCallListener {
public UnaryServerCallListener(
RpcInvocation invocation, Invoker<?> invoker, StreamObserver<Object> responseObserver) {
super(invocation, invoker, responseObserver);
}
@Override
public void onReturn(Object value) {
responseObserver.onNext(value);
responseObserver.onCompleted();
}
@Override
public void onMessage(Object message) {
if (message instanceof Object[]) {
invocation.setArguments((Object[]) message);
} else {
invocation.setArguments(new Object[] {message});
}
}
@Override
public void onCancel(long code) {}
@Override
public void onComplete() {
invoke();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/CompositeExceptionHandler.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/CompositeExceptionHandler.java | /*
* 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.rpc.protocol.tri.h12;
import org.apache.dubbo.common.logger.Level;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.remoting.http12.ExceptionHandler;
import org.apache.dubbo.remoting.http12.HttpHeaders;
import org.apache.dubbo.remoting.http12.HttpResult;
import org.apache.dubbo.remoting.http12.HttpStatus;
import org.apache.dubbo.remoting.http12.RequestMetadata;
import org.apache.dubbo.remoting.http12.exception.HttpStatusException;
import org.apache.dubbo.rpc.TriRpcStatus;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.MethodDescriptor;
import org.apache.dubbo.rpc.protocol.tri.ExceptionUtils;
import org.apache.dubbo.rpc.protocol.tri.TripleProtocol;
import org.apache.dubbo.rpc.protocol.tri.h12.grpc.GrpcHeaderNames;
import org.apache.dubbo.rpc.protocol.tri.rest.util.TypeUtils;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
@SuppressWarnings({"rawtypes", "unchecked"})
public final class CompositeExceptionHandler implements ExceptionHandler<Throwable, Object> {
private static final Logger LOGGER = LoggerFactory.getLogger(CompositeExceptionHandler.class);
private final List<ExceptionHandler> exceptionHandlers;
private final Map<Class, List<ExceptionHandler>> cache = CollectionUtils.newConcurrentHashMap();
public CompositeExceptionHandler(FrameworkModel frameworkModel) {
exceptionHandlers = frameworkModel.getActivateExtensions(ExceptionHandler.class);
}
@Override
public Level resolveLogLevel(Throwable throwable) {
List<ExceptionHandler> exceptionHandlers = getSuitableExceptionHandlers(throwable.getClass());
for (int i = 0, size = exceptionHandlers.size(); i < size; i++) {
Level level = exceptionHandlers.get(i).resolveLogLevel(throwable);
if (level != null) {
return level;
}
}
return ExceptionUtils.resolveLogLevel(throwable);
}
@Override
public boolean resolveGrpcStatus(
Throwable throwable, HttpHeaders headers, RequestMetadata metadata, MethodDescriptor descriptor) {
throwable = ExceptionUtils.unwrap(throwable);
List<ExceptionHandler> exceptionHandlers = getSuitableExceptionHandlers(throwable.getClass());
for (int i = 0, size = exceptionHandlers.size(); i < size; i++) {
if (exceptionHandlers.get(i).resolveGrpcStatus(throwable, headers, metadata, descriptor)) {
return true;
}
}
TriRpcStatus status = TriRpcStatus.getStatus(throwable);
headers.set(GrpcHeaderNames.GRPC_STATUS.getName(), String.valueOf(status.code.code));
headers.set(
GrpcHeaderNames.GRPC_MESSAGE.getName(),
TripleProtocol.VERBOSE_ENABLED
? ExceptionUtils.buildVerboseMessage(throwable)
: throwable.getMessage());
return true;
}
@Override
public Object handle(Throwable throwable, RequestMetadata metadata, MethodDescriptor descriptor) {
throwable = ExceptionUtils.unwrap(throwable);
Object result;
List<ExceptionHandler> exceptionHandlers = getSuitableExceptionHandlers(throwable.getClass());
for (int i = 0, size = exceptionHandlers.size(); i < size; i++) {
result = exceptionHandlers.get(i).handle(throwable, metadata, descriptor);
if (result != null) {
return result;
}
}
int statusCode = -1, grpcStatusCode = -1;
if (throwable instanceof HttpStatusException) {
statusCode = ((HttpStatusException) throwable).getStatusCode();
} else {
grpcStatusCode = TriRpcStatus.grpcCodeToHttpStatus(TriRpcStatus.getStatus(throwable).code);
}
if (TripleProtocol.VERBOSE_ENABLED) {
if (statusCode == -1) {
statusCode = grpcStatusCode < 0 ? HttpStatus.INTERNAL_SERVER_ERROR.getCode() : grpcStatusCode;
}
LOGGER.info("Http request process error: status={}", statusCode, throwable);
}
return grpcStatusCode < 0 ? null : new HttpStatusException(grpcStatusCode, throwable.getMessage(), throwable);
}
@Override
public Object handleGrpc(Throwable throwable, RequestMetadata metadata, MethodDescriptor descriptor) {
throwable = ExceptionUtils.unwrap(throwable);
Object result;
List<ExceptionHandler> exceptionHandlers = getSuitableExceptionHandlers(throwable.getClass());
for (int i = 0, size = exceptionHandlers.size(); i < size; i++) {
result = exceptionHandlers.get(i).handleGrpc(throwable, metadata, descriptor);
if (result != null) {
return result;
}
}
if (descriptor != null) {
Method method = descriptor.getMethod();
if (method != null) {
for (Class<?> exceptionClass : method.getExceptionTypes()) {
if (exceptionClass.isInstance(throwable)) {
return HttpResult.of(throwable);
}
}
}
}
if (TripleProtocol.VERBOSE_ENABLED) {
LOGGER.info("Grpc http request process error", throwable);
}
return null;
}
private List<ExceptionHandler> getSuitableExceptionHandlers(Class type) {
return cache.computeIfAbsent(type, k -> {
List<ExceptionHandler> result = new ArrayList<>();
for (ExceptionHandler handler : exceptionHandlers) {
Class<?> supportType = TypeUtils.getSuperGenericType(handler.getClass());
if (supportType != null && supportType.isAssignableFrom(type)) {
result.add(handler);
}
}
if (result.isEmpty()) {
return Collections.emptyList();
}
LOGGER.info("Found suitable ExceptionHandler for [{}], handlers: {}", type, result);
return result;
});
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/AttachmentHolder.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/AttachmentHolder.java | /*
* 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.rpc.protocol.tri.h12;
import java.util.Map;
public interface AttachmentHolder {
void setResponseAttachments(Map<String, Object> attachments);
Map<String, Object> getResponseAttachments();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/TripleProtocolDetector.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/TripleProtocolDetector.java | /*
* 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.rpc.protocol.tri.h12;
import org.apache.dubbo.remoting.api.ProtocolDetector;
import org.apache.dubbo.remoting.buffer.ByteBufferBackedChannelBuffer;
import org.apache.dubbo.remoting.buffer.ChannelBuffer;
import org.apache.dubbo.remoting.buffer.ChannelBuffers;
import org.apache.dubbo.remoting.http12.HttpMethods;
import org.apache.dubbo.remoting.http12.HttpVersion;
import io.netty.handler.codec.http2.Http2CodecUtil;
public class TripleProtocolDetector implements ProtocolDetector {
public static final String HTTP_VERSION = "HTTP_VERSION";
private static final ChannelBuffer CLIENT_PREFACE_STRING = new ByteBufferBackedChannelBuffer(
Http2CodecUtil.connectionPrefaceBuf().nioBuffer());
@Override
public Result detect(ChannelBuffer in) {
// http1
if (in.readableBytes() < 2) {
return Result.needMoreData();
}
byte[] magics = new byte[7];
in.getBytes(in.readerIndex(), magics, 0, 7);
if (isHttp(magics)) {
Result recognized = Result.recognized();
recognized.setAttribute(HTTP_VERSION, HttpVersion.HTTP1.getVersion());
return recognized;
}
in.resetReaderIndex();
// http2
int prefaceLen = CLIENT_PREFACE_STRING.readableBytes();
int bytesRead = Math.min(in.readableBytes(), prefaceLen);
if (bytesRead == 0 || !ChannelBuffers.prefixEquals(in, CLIENT_PREFACE_STRING, bytesRead)) {
return Result.unrecognized();
}
if (bytesRead == prefaceLen) {
Result recognized = Result.recognized();
recognized.setAttribute(HTTP_VERSION, HttpVersion.HTTP2.getVersion());
return recognized;
}
return Result.needMoreData();
}
private static boolean isHttp(byte[] magic) {
for (int i = 0; i < 8; i++) {
byte[] methodBytes = HttpMethods.HTTP_METHODS_BYTES[i];
int end = methodBytes.length - 1;
for (int j = 0; j <= end; j++) {
if (magic[j] != methodBytes[j]) {
break;
}
if (j == end) {
return true;
}
}
}
return false;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/AbstractServerTransportListener.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/AbstractServerTransportListener.java | /*
* 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.rpc.protocol.tri.h12;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.constants.LoggerCodeConstants;
import org.apache.dubbo.common.logger.FluentLogger;
import org.apache.dubbo.common.threadpool.manager.ExecutorRepository;
import org.apache.dubbo.common.threadpool.serial.SerializingExecutor;
import org.apache.dubbo.common.utils.MethodUtils;
import org.apache.dubbo.common.utils.UrlUtils;
import org.apache.dubbo.remoting.http12.HttpChannel;
import org.apache.dubbo.remoting.http12.HttpInputMessage;
import org.apache.dubbo.remoting.http12.HttpStatus;
import org.apache.dubbo.remoting.http12.HttpTransportListener;
import org.apache.dubbo.remoting.http12.RequestMetadata;
import org.apache.dubbo.remoting.http12.exception.HttpStatusException;
import org.apache.dubbo.remoting.http12.message.MethodMetadata;
import org.apache.dubbo.rpc.HeaderFilter;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.MethodDescriptor;
import org.apache.dubbo.rpc.protocol.tri.DescriptorUtils;
import org.apache.dubbo.rpc.protocol.tri.ExceptionUtils;
import org.apache.dubbo.rpc.protocol.tri.RpcInvocationBuildContext;
import org.apache.dubbo.rpc.protocol.tri.TripleConstants;
import org.apache.dubbo.rpc.protocol.tri.TripleHeaderEnum;
import org.apache.dubbo.rpc.protocol.tri.TripleProtocol;
import org.apache.dubbo.rpc.protocol.tri.route.DefaultRequestRouter;
import org.apache.dubbo.rpc.protocol.tri.route.RequestRouter;
import org.apache.dubbo.rpc.protocol.tri.stream.StreamUtils;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.function.Function;
import java.util.function.Supplier;
public abstract class AbstractServerTransportListener<HEADER extends RequestMetadata, MESSAGE extends HttpInputMessage>
implements HttpTransportListener<HEADER, MESSAGE> {
private static final FluentLogger LOGGER = FluentLogger.of(AbstractServerTransportListener.class);
private static final String HEADER_FILTERS_CACHE = "HEADER_FILTERS_CACHE";
private final FrameworkModel frameworkModel;
private final URL url;
private final HttpChannel httpChannel;
private final RequestRouter requestRouter;
private final ExceptionCustomizerWrapper exceptionCustomizerWrapper;
private Executor executor;
private HEADER httpMetadata;
private RpcInvocationBuildContext context;
private HttpMessageListener httpMessageListener;
protected AbstractServerTransportListener(FrameworkModel frameworkModel, URL url, HttpChannel httpChannel) {
this.frameworkModel = frameworkModel;
this.url = url;
this.httpChannel = httpChannel;
requestRouter = frameworkModel.getOrRegisterBean(DefaultRequestRouter.class);
exceptionCustomizerWrapper = new ExceptionCustomizerWrapper(frameworkModel);
}
@Override
public final void onMetadata(HEADER metadata) {
httpMetadata = metadata;
exceptionCustomizerWrapper.setMetadata(metadata);
try {
onBeforeMetadata(metadata);
} catch (Throwable t) {
logError(t);
onMetadataError(metadata, t);
return;
}
try {
executor = initializeExecutor(url, metadata);
} catch (Throwable t) {
LOGGER.error(LoggerCodeConstants.COMMON_ERROR_USE_THREAD_POOL, "Initialize executor failed.", t);
onError(t);
return;
}
if (executor == null) {
LOGGER.internalError("Executor must not be null.");
onError(new NullPointerException("Initialize executor return null"));
return;
}
executor.execute(() -> {
try {
onPrepareMetadata(metadata);
setHttpMessageListener(buildHttpMessageListener());
onMetadataCompletion(metadata);
} catch (Throwable t) {
logError(t);
onMetadataError(metadata, t);
}
});
}
protected void onBeforeMetadata(HEADER metadata) {
doRoute(metadata);
}
protected final void doRoute(HEADER metadata) {
context = requestRouter.route(url, metadata, httpChannel);
if (context == null) {
throw new HttpStatusException(HttpStatus.NOT_FOUND.getCode(), "Invoker not found");
}
exceptionCustomizerWrapper.setMethodDescriptor(context.getMethodDescriptor());
}
protected Executor initializeExecutor(URL url, HEADER metadata) {
url = context.getInvoker().getUrl();
return getExecutor(url, url);
}
protected final Executor getExecutor(URL url, Object data) {
return new SerializingExecutor(ExecutorRepository.getInstance(url.getOrDefaultApplicationModel())
.getExecutorSupport(url)
.getExecutor(data));
}
protected void onPrepareMetadata(HEADER metadata) {
// default no op
}
protected abstract HttpMessageListener buildHttpMessageListener();
protected void onMetadataCompletion(HEADER metadata) {
// default no op
}
protected void onMetadataError(HEADER metadata, Throwable throwable) {
initializeAltSvc(url);
onError(throwable);
}
/**
* <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Alt-Svc">Alt-Svc</a>
*/
protected void initializeAltSvc(URL url) {}
@Override
public final void onData(MESSAGE message) {
if (executor == null) {
onDataFinally(message);
return;
}
executor.execute(() -> {
try {
doOnData(message);
} catch (Throwable t) {
logError(t);
onError(message, t);
} finally {
onDataFinally(message);
}
});
}
protected void doOnData(MESSAGE message) {
if (httpMessageListener == null) {
return;
}
onPrepareData(message);
httpMessageListener.onMessage(message.getBody());
onDataCompletion(message);
}
protected void onPrepareData(MESSAGE message) {
// default no op
}
protected void onDataCompletion(MESSAGE message) {
// default no op
}
protected void onDataFinally(MESSAGE message) {
try {
message.close();
} catch (Exception e) {
onError(e);
}
}
protected void onError(MESSAGE message, Throwable throwable) {
onError(throwable);
}
protected void onError(Throwable throwable) {
throw ExceptionUtils.wrap(throwable);
}
private void logError(Throwable t) {
Supplier<String> msg = () -> {
StringBuilder sb = new StringBuilder(128);
sb.append("An error occurred while processing the http request with ")
.append(getClass().getSimpleName())
.append(", ")
.append(httpMetadata);
if (TripleProtocol.VERBOSE_ENABLED) {
sb.append(", headers=").append(httpMetadata.headers());
}
if (context != null) {
MethodDescriptor md = context.getMethodDescriptor();
if (md != null) {
sb.append(", method=").append(MethodUtils.toShortString(md));
}
if (TripleProtocol.VERBOSE_ENABLED) {
Invoker<?> invoker = context.getInvoker();
if (invoker != null) {
URL url = invoker.getUrl();
Object service = url.getServiceModel().getProxyObject();
sb.append(", service=")
.append(service.getClass().getSimpleName())
.append('@')
.append(Integer.toHexString(System.identityHashCode(service)))
.append(", url='")
.append(url)
.append('\'');
}
}
}
return sb.toString();
};
Throwable th = ExceptionUtils.unwrap(t);
LOGGER.msg(msg).log(exceptionCustomizerWrapper.resolveLogLevel(th), th);
}
protected final RpcInvocation buildRpcInvocation(RpcInvocationBuildContext context) {
MethodDescriptor methodDescriptor = context.getMethodDescriptor();
if (methodDescriptor == null) {
methodDescriptor = DescriptorUtils.findMethodDescriptor(
context.getServiceDescriptor(), context.getMethodName(), context.isHasStub());
setMethodDescriptor(methodDescriptor);
}
MethodMetadata methodMetadata = context.getMethodMetadata();
if (methodMetadata == null) {
methodMetadata = MethodMetadata.fromMethodDescriptor(methodDescriptor);
context.setMethodMetadata(methodMetadata);
}
Invoker<?> invoker = context.getInvoker();
URL url = invoker.getUrl();
RpcInvocation inv = new RpcInvocation(
url.getServiceModel(),
methodDescriptor.getMethodName(),
context.getServiceDescriptor().getInterfaceName(),
url.getProtocolServiceKey(),
methodDescriptor.getParameterClasses(),
new Object[0]);
inv.setTargetServiceUniqueName(url.getServiceKey());
inv.setReturnTypes(methodDescriptor.getReturnTypes());
inv.setObjectAttachments(StreamUtils.toAttachments(httpMetadata.headers()));
inv.put(TripleConstants.REMOTE_ADDRESS_KEY, httpChannel.remoteAddress());
inv.getAttributes().putAll(context.getAttributes());
String consumerAppName = httpMetadata.header(TripleHeaderEnum.CONSUMER_APP_NAME_KEY.getKey());
if (consumerAppName != null) {
inv.put(TripleHeaderEnum.CONSUMER_APP_NAME_KEY, consumerAppName);
}
// customizer RpcInvocation
HeaderFilter[] headerFilters =
UrlUtils.computeServiceAttribute(invoker.getUrl(), HEADER_FILTERS_CACHE, this::loadHeaderFilters);
if (headerFilters == null) {
headerFilters = this.loadHeaderFilters(invoker.getUrl());
}
for (HeaderFilter headerFilter : headerFilters) {
headerFilter.invoke(invoker, inv);
}
initializeAltSvc(url);
return onBuildRpcInvocationCompletion(inv);
}
private HeaderFilter[] loadHeaderFilters(URL url) {
List<HeaderFilter> headerFilters = frameworkModel
.getExtensionLoader(HeaderFilter.class)
.getActivateExtension(url, CommonConstants.HEADER_FILTER_KEY);
LOGGER.info("Header filters for [{}] loaded: {}", url, headerFilters);
return headerFilters.toArray(new HeaderFilter[0]);
}
protected RpcInvocation onBuildRpcInvocationCompletion(RpcInvocation invocation) {
String timeoutString = httpMetadata.header(TripleHeaderEnum.SERVICE_TIMEOUT.getKey());
try {
if (timeoutString != null) {
Long timeout = Long.parseLong(timeoutString);
invocation.put(CommonConstants.TIMEOUT_KEY, timeout);
}
} catch (Throwable t) {
LOGGER.warn(
LoggerCodeConstants.PROTOCOL_FAILED_PARSE,
"Failed to parse request timeout set from: {}, service={}, method={}",
timeoutString,
context.getServiceDescriptor().getInterfaceName(),
context.getMethodName());
}
return invocation;
}
protected final FrameworkModel getFrameworkModel() {
return frameworkModel;
}
protected final ExceptionCustomizerWrapper getExceptionCustomizerWrapper() {
return exceptionCustomizerWrapper;
}
protected final HEADER getHttpMetadata() {
return httpMetadata;
}
public final RpcInvocationBuildContext getContext() {
return context;
}
protected final void setHttpMessageListener(HttpMessageListener httpMessageListener) {
this.httpMessageListener = httpMessageListener;
}
protected Function<Throwable, Object> getExceptionCustomizer() {
return exceptionCustomizerWrapper::customize;
}
protected void setMethodDescriptor(MethodDescriptor methodDescriptor) {
context.setMethodDescriptor(methodDescriptor);
exceptionCustomizerWrapper.setMethodDescriptor(methodDescriptor);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/ExceptionCustomizerWrapper.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/ExceptionCustomizerWrapper.java | /*
* 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.rpc.protocol.tri.h12;
import org.apache.dubbo.common.logger.Level;
import org.apache.dubbo.remoting.http12.HttpHeaders;
import org.apache.dubbo.remoting.http12.HttpResult;
import org.apache.dubbo.remoting.http12.RequestMetadata;
import org.apache.dubbo.remoting.http12.message.DefaultHttpResult.Builder;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.TriRpcStatus;
import org.apache.dubbo.rpc.TriRpcStatus.Code;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.MethodDescriptor;
import org.apache.dubbo.rpc.protocol.tri.TripleHeaderEnum;
import org.apache.dubbo.rpc.protocol.tri.h12.grpc.GrpcHeaderNames;
public final class ExceptionCustomizerWrapper {
private final CompositeExceptionHandler exceptionHandler;
private RequestMetadata metadata;
private MethodDescriptor methodDescriptor;
private boolean needWrap;
public ExceptionCustomizerWrapper(FrameworkModel frameworkModel) {
exceptionHandler = frameworkModel.getOrRegisterBean(CompositeExceptionHandler.class);
}
public void setMetadata(RequestMetadata metadata) {
this.metadata = metadata;
}
public void setMethodDescriptor(MethodDescriptor methodDescriptor) {
this.methodDescriptor = methodDescriptor;
}
public void setNeedWrap(boolean needWrap) {
this.needWrap = needWrap;
}
public Level resolveLogLevel(Throwable throwable) {
return exceptionHandler.resolveLogLevel(throwable);
}
public void customizeGrpcStatus(HttpHeaders headers, Throwable throwable) {
if (throwable == null) {
headers.set(GrpcHeaderNames.GRPC_STATUS.getName(), "0");
return;
}
exceptionHandler.resolveGrpcStatus(throwable, headers, metadata, methodDescriptor);
}
public Object customize(Throwable throwable) {
return exceptionHandler.handle(throwable, metadata, methodDescriptor);
}
@SuppressWarnings("unchecked")
public Object customizeGrpc(Throwable throwable) {
Object result = exceptionHandler.handleGrpc(throwable, metadata, methodDescriptor);
if (needWrap) {
Builder<Object> builder = null;
if (result == null) {
builder = HttpResult.builder().body(throwable);
} else if (result instanceof Throwable) {
builder = HttpResult.builder().body(result);
} else if (result instanceof HttpResult) {
HttpResult<Object> httpResult = (HttpResult<Object>) result;
if (httpResult.getBody() instanceof Throwable) {
builder = HttpResult.builder().from(httpResult);
}
}
if (builder == null) {
return result;
}
Code code = TriRpcStatus.getStatus(throwable).code;
return builder.header(
TripleHeaderEnum.TRI_EXCEPTION_CODE.getName(),
code == TriRpcStatus.UNKNOWN.code ? RpcException.BIZ_EXCEPTION : code.code)
.build();
}
return result instanceof Throwable ? result : null;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/AbstractServerCallListener.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/AbstractServerCallListener.java | /*
* 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.rpc.protocol.tri.h12;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.stream.StreamObserver;
import org.apache.dubbo.remoting.http12.exception.HttpRequestTimeout;
import org.apache.dubbo.remoting.http12.h2.Http2CancelableStreamObserver;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.RpcServiceContext;
import org.apache.dubbo.rpc.protocol.tri.TripleConstants;
import org.apache.dubbo.rpc.protocol.tri.TripleHeaderEnum;
import java.net.InetSocketAddress;
import static org.apache.dubbo.common.constants.CommonConstants.REMOTE_APPLICATION_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_TIMEOUT_SERVER;
import static org.apache.dubbo.rpc.protocol.tri.TripleConstants.REMOTE_ADDRESS_KEY;
public abstract class AbstractServerCallListener implements ServerCallListener {
private static final ErrorTypeAwareLogger LOGGER =
LoggerFactory.getErrorTypeAwareLogger(AbstractServerCallListener.class);
protected final RpcInvocation invocation;
protected final Invoker<?> invoker;
protected final StreamObserver<Object> responseObserver;
public AbstractServerCallListener(
RpcInvocation invocation, Invoker<?> invoker, StreamObserver<Object> responseObserver) {
this.invocation = invocation;
this.invoker = invoker;
this.responseObserver = responseObserver;
}
public void invoke() {
if (responseObserver instanceof Http2CancelableStreamObserver) {
RpcContext.restoreCancellationContext(
((Http2CancelableStreamObserver<Object>) responseObserver).getCancellationContext());
}
RpcServiceContext serviceContext = RpcContext.getServiceContext();
serviceContext.setRemoteAddress((InetSocketAddress) invocation.remove(REMOTE_ADDRESS_KEY));
String remoteApp = (String) invocation.remove(TripleHeaderEnum.CONSUMER_APP_NAME_KEY);
if (remoteApp != null) {
serviceContext.setRemoteApplicationName(remoteApp);
invocation.setAttachmentIfAbsent(REMOTE_APPLICATION_KEY, remoteApp);
}
if (serviceContext.getRequest() == null) {
serviceContext.setRequest(invocation.get(TripleConstants.HTTP_REQUEST_KEY));
serviceContext.setResponse(invocation.get(TripleConstants.HTTP_RESPONSE_KEY));
}
try {
long stInMillis = System.currentTimeMillis();
Result response = invoker.invoke(invocation);
if (response.hasException()) {
responseObserver.onError(response.getException());
return;
}
response.whenCompleteWithContext((r, t) -> {
if (responseObserver instanceof AttachmentHolder) {
((AttachmentHolder) responseObserver).setResponseAttachments(response.getObjectAttachments());
}
if (t != null) {
responseObserver.onError(t);
return;
}
if (r.hasException()) {
responseObserver.onError(r.getException());
return;
}
long cost = System.currentTimeMillis() - stInMillis;
Long timeout = (Long) invocation.get("timeout");
if (timeout != null && timeout < cost) {
LOGGER.error(
PROTOCOL_TIMEOUT_SERVER,
"",
"",
String.format(
"Invoke timeout at server side, ignored to send response. service=%s method=%s cost=%s",
invocation.getTargetServiceUniqueName(), invocation.getMethodName(), cost));
HttpRequestTimeout serverSideTimeout = HttpRequestTimeout.serverSide();
responseObserver.onError(serverSideTimeout);
return;
}
onReturn(r.getValue());
});
} catch (Exception e) {
responseObserver.onError(e);
} finally {
RpcContext.removeCancellationContext();
RpcContext.removeContext();
}
}
public abstract void onReturn(Object value);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/ServerStreamServerCallListener.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/ServerStreamServerCallListener.java | /*
* 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.rpc.protocol.tri.h12;
import org.apache.dubbo.common.stream.StreamObserver;
import org.apache.dubbo.remoting.http12.HttpResult;
import org.apache.dubbo.remoting.http12.exception.HttpStatusException;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcInvocation;
public class ServerStreamServerCallListener extends AbstractServerCallListener {
public ServerStreamServerCallListener(
RpcInvocation invocation, Invoker<?> invoker, StreamObserver<Object> responseObserver) {
super(invocation, invoker, responseObserver);
}
@Override
public void onReturn(Object value) {
if (value instanceof HttpResult) {
responseObserver.onNext(value);
responseObserver.onCompleted();
}
}
@Override
public void onMessage(Object message) {
Class<?>[] params = invocation.getParameterTypes();
if (params.length == 1) {
if (params[0].isInstance(responseObserver)) {
invocation.setArguments(new Object[] {responseObserver});
return;
}
}
if (message instanceof Object[]) {
message = ((Object[]) message)[0];
}
invocation.setArguments(new Object[] {message, responseObserver});
}
@Override
public void onCancel(long code) {
responseObserver.onError(new HttpStatusException((int) code));
}
@Override
public void onComplete() {
invoke();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/BiStreamServerCallListener.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/BiStreamServerCallListener.java | /*
* 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.rpc.protocol.tri.h12;
import org.apache.dubbo.common.stream.StreamObserver;
import org.apache.dubbo.remoting.http12.FlowControlStreamObserver;
import org.apache.dubbo.remoting.http12.exception.HttpStatusException;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcInvocation;
public class BiStreamServerCallListener extends AbstractServerCallListener {
private StreamObserver<Object> requestObserver;
public BiStreamServerCallListener(
RpcInvocation invocation, Invoker<?> invoker, FlowControlStreamObserver<Object> responseObserver) {
super(invocation, invoker, responseObserver);
invocation.setArguments(new Object[] {responseObserver});
invoke();
}
@Override
@SuppressWarnings("unchecked")
public void onReturn(Object value) {
requestObserver = (StreamObserver<Object>) value;
}
@Override
public void onMessage(Object message) {
if (message instanceof Object[]) {
message = ((Object[]) message)[0];
}
requestObserver.onNext(message);
if (((FlowControlStreamObserver<Object>) responseObserver).isAutoRequestN()) {
((FlowControlStreamObserver<Object>) responseObserver).request(1);
}
}
@Override
public void onCancel(long code) {
requestObserver.onError(new HttpStatusException((int) code));
}
@Override
public void onComplete() {
requestObserver.onCompleted();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/ServerCallListener.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/ServerCallListener.java | /*
* 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.rpc.protocol.tri.h12;
public interface ServerCallListener {
/**
* Callback when a request message is received.
*
* @param message message received
*/
void onMessage(Object message);
/**
* @param code when the call is canceled.
*/
void onCancel(long code);
/**
* Request completed.
*/
void onComplete();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/CompressibleEncoder.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/CompressibleEncoder.java | /*
* 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.rpc.protocol.tri.h12;
import org.apache.dubbo.remoting.http12.exception.EncodeException;
import org.apache.dubbo.remoting.http12.message.HttpMessageEncoder;
import org.apache.dubbo.remoting.http12.message.MediaType;
import org.apache.dubbo.rpc.protocol.tri.compressor.Compressor;
import java.io.OutputStream;
import java.nio.charset.Charset;
public class CompressibleEncoder implements HttpMessageEncoder {
private final HttpMessageEncoder delegate;
private Compressor compressor = Compressor.NONE;
public CompressibleEncoder(HttpMessageEncoder delegate) {
this.delegate = delegate;
}
public void setCompressor(Compressor compressor) {
this.compressor = compressor;
}
public void encode(OutputStream outputStream, Object data, Charset charset) throws EncodeException {
delegate.encode(compressor.decorate(outputStream), data, charset);
}
public void encode(OutputStream outputStream, Object[] data, Charset charset) throws EncodeException {
delegate.encode(outputStream, data, charset);
}
@Override
public MediaType mediaType() {
return delegate.mediaType();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/HttpMessageEncoderWrapper.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/HttpMessageEncoderWrapper.java | /*
* 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.rpc.protocol.tri.h12;
import org.apache.dubbo.remoting.http12.exception.EncodeException;
import org.apache.dubbo.remoting.http12.message.HttpMessageEncoder;
import org.apache.dubbo.remoting.http12.message.MediaType;
import java.io.OutputStream;
import java.nio.charset.Charset;
public final class HttpMessageEncoderWrapper implements HttpMessageEncoder {
private final Charset charset;
private final MediaType mediaType;
private final HttpMessageEncoder httpMessageEncoder;
public HttpMessageEncoderWrapper(Charset charset, MediaType mediaType, HttpMessageEncoder httpMessageEncoder) {
this.charset = charset;
this.mediaType = mediaType;
this.httpMessageEncoder = httpMessageEncoder;
}
public HttpMessageEncoderWrapper(Charset charset, HttpMessageEncoder httpMessageEncoder) {
this.charset = charset;
mediaType = httpMessageEncoder.mediaType();
this.httpMessageEncoder = httpMessageEncoder;
}
public Charset charset() {
return charset;
}
@Override
public MediaType mediaType() {
return mediaType;
}
@Override
public boolean supports(String mediaType) {
return httpMessageEncoder.supports(mediaType);
}
@Override
public void encode(OutputStream outputStream, Object data, Charset charset) throws EncodeException {
httpMessageEncoder.encode(outputStream, data, this.charset);
}
@Override
public void encode(OutputStream outputStream, Object[] data, Charset charset) throws EncodeException {
httpMessageEncoder.encode(outputStream, data, this.charset);
}
@Override
public void encode(OutputStream outputStream, Object data) throws EncodeException {
httpMessageEncoder.encode(outputStream, data, charset);
}
@Override
public void encode(OutputStream outputStream, Object[] data) throws EncodeException {
httpMessageEncoder.encode(outputStream, data, charset);
}
@Override
public String contentType() {
return mediaType.getName() + ";charset=" + charset.name();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/HttpMessageListener.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/HttpMessageListener.java | /*
* 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.rpc.protocol.tri.h12;
import java.io.InputStream;
public interface HttpMessageListener {
void onMessage(InputStream inputStream);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/HttpMessageDecoderWrapper.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/HttpMessageDecoderWrapper.java | /*
* 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.rpc.protocol.tri.h12;
import org.apache.dubbo.remoting.http12.exception.DecodeException;
import org.apache.dubbo.remoting.http12.message.HttpMessageDecoder;
import org.apache.dubbo.remoting.http12.message.MediaType;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.nio.charset.Charset;
public final class HttpMessageDecoderWrapper implements HttpMessageDecoder {
private final Charset charset;
private final HttpMessageDecoder httpMessageDecoder;
public HttpMessageDecoderWrapper(Charset charset, HttpMessageDecoder httpMessageDecoder) {
this.charset = charset;
this.httpMessageDecoder = httpMessageDecoder;
}
@Override
public boolean supports(String mediaType) {
return httpMessageDecoder.supports(mediaType);
}
@Override
public Object decode(InputStream inputStream, Class<?> targetType, Charset charset) throws DecodeException {
return httpMessageDecoder.decode(inputStream, targetType, this.charset);
}
@Override
public Object decode(InputStream inputStream, Type targetType, Charset charset) throws DecodeException {
return httpMessageDecoder.decode(inputStream, targetType, this.charset);
}
@Override
public Object[] decode(InputStream inputStream, Class<?>[] targetTypes, Charset charset) throws DecodeException {
return httpMessageDecoder.decode(inputStream, targetTypes, this.charset);
}
@Override
public Object decode(InputStream inputStream, Class<?> targetType) throws DecodeException {
return httpMessageDecoder.decode(inputStream, targetType, charset);
}
@Override
public Object decode(InputStream inputStream, Type targetType) throws DecodeException {
return httpMessageDecoder.decode(inputStream, targetType, charset);
}
@Override
public Object[] decode(InputStream inputStream, Class<?>[] targetTypes) throws DecodeException {
return httpMessageDecoder.decode(inputStream, targetTypes, charset);
}
@Override
public MediaType mediaType() {
return httpMessageDecoder.mediaType();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.