You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@dubbo.apache.org by gu...@apache.org on 2022/03/01 04:34:08 UTC
[dubbo] branch 3.0 updated: [3.0-Triple] A reactor for better abstraction and futher stub api (#9708)
This is an automated email from the ASF dual-hosted git repository.
guohao pushed a commit to branch 3.0
in repository https://gitbox.apache.org/repos/asf/dubbo.git
The following commit(s) were added to refs/heads/3.0 by this push:
new 1add77e [3.0-Triple] A reactor for better abstraction and futher stub api (#9708)
1add77e is described below
commit 1add77ed6ec2872bb5cb8bbd69cdaea56f5b1acb
Author: GuoHao <gu...@gmail.com>
AuthorDate: Tue Mar 1 12:33:26 2022 +0800
[3.0-Triple] A reactor for better abstraction and futher stub api (#9708)
* Init
* update'
* Update
* add depressor
* Update
* Update
* Roughly finished server stream
* Move some comment
* Minor clean
* Store serialize type in request
* Try abstract unray/stream
* Fix compile
* Adapt protocol
* Fix add timeout listener NPE
* Fix setIfNull NPE
* Init client executor before invoke
* Flush when send init header
* Fix path
* Fix data frame not end
* Fix class cast err
* Fix no grpc-message returned in trailers
* Fix no delivery
* Fix write idx
* Fix decode
* Fix code is not 0
* Try seperate stream and unary method descriptor
* Add call
* Update call observer
* Adapt client stream and client call
* Fix compile
* Fix compile
* Fix dupliate reuqests
* Remove unused code
* Fix compile
* Fix large header
* Fix error exception
* Fix stream
* Remove generic unpack from call
* Abstract call to reduce code in tri invoker for stub usage
* Set callback executor
* Clean unused method
* Adapt server call
* Remove set decompressor method
* Pass unary client
* Fix npe at server side when unary call
* Pass unary server
* Move client call static methods to standalone file
* Fix biz error did not send EOS
* Fix duplicate send message methods in server call
* Do not send message when status is ok
* Support requestN()
* Close listener in delivery process
* Try set listener before data
* Fix multiple decdoe
* some code refactoring
* Release accumulate after close decoder
* Extract inner lambda
* Abstract managed stream observer
* Support cancel
* Basicly add cancel
* Support bi-cancel
* some code refactoring
* Add client cancel
* Support cancel server stream
* wrapper client SerializingExecutor
* Fix large size header
* Add client decompressor
* Support server set compression
* fix multi thread decoder
* Ignore version 1.0.0
* Extract single kv method
* Add state check in stream observer
* Fix cancel server stream
* Default flush write queue
* Simplify ssl judge
* fix defaultFuture error
* Simplify defaultFuture2
* fix license
* fix style
* fix style
* Generate throwable in client executor
* Close h2 channel when client timeout
* refactor grpc-status-detail handler
* Minor code clean up
* Rename grpc status to rpc status
* Abstract request meta to reduce arguments passing
* Abstract call stream methods
* Fix status with description
* Minor fix
* Try 1.0.0 version by default
* Format code
* Rebase 3.0
* backpress
* refactor run on eventLoop
* Enhance error handle
* Remove tranport state
* Add doc
* refactor thread
* Add client stream simple ut
* fix thread
* Fix status from trailers
* Update UT
* Use transport listener instead of stream
* Move netty operations to transport package
* fix style
* Fix some ut
* Fix ut format
* Ignore protocol test
* Add client stream ut
* Fix wrapper it
* Seperate wrap response from observer
* Some operations are removed from the thread
* Import timeout key
* Use millis to judge timeout
* Fix protocol error
* fix style
* fix style
* Add error log
* delete defaultSerialization
* override TripleInvoker getCallbackExecutor
* Add decoder test
* Format test
* Add Client response ut
* fix tri callbackExecutor
* Remove unused test
* Remove lookup executor in TripleInvoker
* Format
* Fix executor
* Fix UT
* Fix return type in server call
* ClientCall remove url param
Co-authored-by: earthchen <ea...@gmail.com>
---
.../apache/dubbo/common/stream/StreamObserver.java | 2 +
.../apache/dubbo/rpc/model/MethodDescriptor.java | 213 +++------
.../apache/dubbo/rpc/model/ServiceDescriptor.java | 16 +-
.../dubbo/rpc/model/StreamMethodDescriptor.java | 88 ++++
.../dubbo/descriptor/MethodDescriptorTest.java | 35 +-
dubbo-rpc/dubbo-rpc-triple/pom.xml | 2 +-
.../rpc/protocol/tri/AbstractClientStream.java | 487 -------------------
.../rpc/protocol/tri/AbstractServerStream.java | 439 -----------------
.../dubbo/rpc/protocol/tri/AbstractStream.java | 520 ---------------------
.../rpc/protocol/tri/CancelableStreamObserver.java | 29 +-
.../dubbo/rpc/protocol/tri/ClassLoadUtil.java | 1 +
.../tri/ClientOutboundTransportObserver.java | 82 ----
.../dubbo/rpc/protocol/tri/ClientStream.java | 122 -----
.../rpc/protocol/tri/ClientStreamObserver.java | 16 +-
.../dubbo/rpc/protocol/tri}/DefaultFuture2.java | 143 +++---
.../dubbo/rpc/protocol/tri/DefaultMetadata.java | 66 ---
.../dubbo/rpc/protocol/tri/GrpcDataDecoder.java | 114 -----
.../dubbo/rpc/protocol/tri/Http2HeaderMeta.java | 57 ---
.../rpc/protocol/tri/InboundTransportObserver.java | 60 ---
.../protocol/tri/OutboundTransportObserver.java | 101 ----
.../dubbo/rpc/protocol/tri/PathResolver.java | 1 +
.../tri/{Metadata.java => RequestMetadata.java} | 44 +-
.../tri/{GrpcStatus.java => RpcStatus.java} | 158 ++++---
.../tri/ServerOutboundTransportObserver.java | 88 ----
.../dubbo/rpc/protocol/tri/ServerStream.java | 210 ---------
.../rpc/protocol/tri/ServerStreamObserver.java | 13 +-
.../rpc/protocol/tri/SingleProtobufUtils.java | 1 +
.../org/apache/dubbo/rpc/protocol/tri/Stream.java | 69 ---
.../dubbo/rpc/protocol/tri/TransportState.java | 71 ---
.../protocol/tri/TripleClientRequestHandler.java | 68 ---
.../dubbo/rpc/protocol/tri/TripleConstant.java | 35 +-
.../dubbo/rpc/protocol/tri/TripleHeaderEnum.java | 1 +
.../tri/TripleHttp2FrameServerHandler.java | 297 ------------
.../rpc/protocol/tri/TripleHttp2Protocol.java | 40 +-
.../dubbo/rpc/protocol/tri/TripleInvoker.java | 137 +++---
.../dubbo/rpc/protocol/tri/TriplePathResolver.java | 1 +
.../dubbo/rpc/protocol/tri/TripleProtocol.java | 37 +-
.../protocol/tri/TripleServerInboundHandler.java | 32 --
.../dubbo/rpc/protocol/tri/UnaryClientStream.java | 103 ----
.../dubbo/rpc/protocol/tri/UnaryServerStream.java | 112 -----
.../tri/call/AbstractServerCallListener.java | 70 +++
.../tri/call/BiStreamServerCallListener.java | 58 +++
.../dubbo/rpc/protocol/tri/call/ClientCall.java | 260 +++++++++++
.../rpc/protocol/tri/call/ClientCallUtil.java | 137 ++++++
.../call/ObserverToClientCallListenerAdapter.java | 56 +++
.../dubbo/rpc/protocol/tri/call/ServerCall.java | 455 ++++++++++++++++++
.../rpc/protocol/tri/call/ServerCallUtil.java | 95 ++++
.../tri/call/ServerStreamServerCallListener.java | 55 +++
.../rpc/protocol/tri/call/UnaryCallListener.java | 57 +++
.../protocol/tri/call/UnaryServerCallListener.java | 62 +++
.../tri/call/WrapRequestServerCallListener.java | 51 ++
.../tri/call/WrapResponseCallListener.java | 62 +++
.../protocol/tri/command/CancelQueueCommand.java | 14 +-
.../rpc/protocol/tri/command/DataQueueCommand.java | 56 +--
...ueueCommand.java => EndStreamQueueCommand.java} | 9 +-
.../protocol/tri/command/FlushQueueCommand.java | 2 +-
.../protocol/tri/command/HeaderQueueCommand.java | 27 +-
.../rpc/protocol/tri/command/QueuedCommand.java | 61 +--
.../protocol/tri/command/TextDataQueueCommand.java | 2 +-
.../protocol/tri/{ => compressor}/Compressor.java | 28 +-
.../DeCompressor.java} | 45 +-
.../{GzipCompressor.java => compressor/Gzip.java} | 12 +-
.../Identity.java} | 10 +-
.../MessageEncoding.java} | 17 +-
.../dubbo/rpc/protocol/tri/frame/Deframer.java | 33 +-
.../dubbo/rpc/protocol/tri/frame/TriDecoder.java | 167 +++++++
.../protocol/tri/observer/CallStreamObserver.java} | 44 +-
.../tri/observer/ClientCallToObserverAdapter.java | 80 ++++
.../tri/observer/ServerCallToObserverAdapter.java | 118 +++++
.../tri/observer/WrapperRequestObserver.java | 82 ++++
.../tri/observer/WrapperResponseObserver.java | 66 +++
.../dubbo/rpc/protocol/tri/pack/GenericPack.java | 67 +++
.../dubbo/rpc/protocol/tri/pack/GenericUnpack.java | 47 ++
.../FlushQueueCommand.java => pack/Pack.java} | 13 +-
.../{IdentityCompressor.java => pack/PbPack.java} | 28 +-
.../tri/{Metadata.java => pack/PbUnpack.java} | 34 +-
.../rpc/protocol/tri/pack/WrapRequestUnpack.java | 47 ++
.../WrapResponseUnpack.java} | 29 +-
.../AbstractStream.java} | 33 +-
.../rpc/protocol/tri/stream/ClientStream.java | 342 ++++++++++++++
.../ClientStreamListener.java} | 35 +-
.../rpc/protocol/tri/stream/ServerStream.java | 349 ++++++++++++++
.../protocol/tri/stream/ServerStreamListener.java} | 26 +-
.../tri/{PathResolver.java => stream/Stream.java} | 25 +-
.../StreamListener.java} | 11 +-
.../dubbo/rpc/protocol/tri/stream/StreamUtils.java | 164 +++++++
.../tri/transport/AbstractH2TransportListener.java | 81 ++++
.../tri/{ => transport}/GracefulShutdown.java | 3 +-
.../H2TransportListener.java} | 46 +-
.../tri/{ => transport}/TripleClientHandler.java | 3 +-
.../TripleCommandOutBoundHandler.java | 6 +-
.../TripleHttp2ClientResponseHandler.java | 62 +--
.../transport/TripleHttp2FrameServerHandler.java | 115 +++++
.../TripleServerConnectionHandler.java | 5 +-
.../tri/{ => transport}/TripleTailHandler.java | 2 +-
.../protocol/tri/{ => transport}/WriteQueue.java | 9 +-
.../src/main/proto/triple_wrapper.proto | 24 +-
.../org.apache.dubbo.rpc.protocol.tri.Compressor | 1 -
...he.dubbo.rpc.protocol.tri.compressor.Compressor | 1 +
....dubbo.rpc.protocol.tri.compressor.DeCompressor | 1 +
.../dubbo/rpc/protocol/tri/AbstractStreamTest.java | 119 -----
.../dubbo/rpc/protocol/tri/ClientStreamTest.java | 368 ---------------
.../rpc/protocol/tri/GrpcDataDecoderTest.java | 102 ----
.../{GrpcStatusTest.java => RpcStatusTest.java} | 17 +-
.../dubbo/rpc/protocol/tri/ServerStreamTest.java | 293 ------------
.../rpc/protocol/tri/SingleProtobufUtilsTest.java | 4 +-
.../dubbo/rpc/protocol/tri/TransportStateTest.java | 122 -----
.../dubbo/rpc/protocol/tri/TripleProtocolTest.java | 12 +-
.../rpc/protocol/tri/UnaryClientStreamTest.java | 69 ---
.../rpc/protocol/tri/call/ClientCallTest.java | 52 +++
.../GzipTest.java} | 20 +-
.../rpc/protocol/tri/compressor/IdentityTest.java} | 40 +-
.../RecordListener.java} | 23 +-
.../rpc/protocol/tri/frame/TriDecoderTest.java | 54 +++
.../rpc/protocol/tri/stream/ClientStreamTest.java | 112 +++++
.../tri/stream/MockClientStreamListener.java} | 31 +-
.../rpc/protocol/tri/support/IGreeterImpl.java | 23 +-
.../transport/AbstractH2TransportListenerTest.java | 65 +++
.../TripleHttp2ClientResponseHandlerTest.java | 40 +-
.../tri/{ => transport}/WriteQueueTest.java | 27 +-
120 files changed, 4373 insertions(+), 5231 deletions(-)
diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/stream/StreamObserver.java b/dubbo-common/src/main/java/org/apache/dubbo/common/stream/StreamObserver.java
index 7ef12ea..89d7eed 100644
--- a/dubbo-common/src/main/java/org/apache/dubbo/common/stream/StreamObserver.java
+++ b/dubbo-common/src/main/java/org/apache/dubbo/common/stream/StreamObserver.java
@@ -24,6 +24,8 @@ package org.apache.dubbo.common.stream;
* @param <T> type of message
*/
public interface StreamObserver<T> {
+
+
/**
* onNext
*
diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/MethodDescriptor.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/MethodDescriptor.java
index 65e24c9..c7f9b7d 100644
--- a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/MethodDescriptor.java
+++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/MethodDescriptor.java
@@ -46,6 +46,7 @@ public class MethodDescriptor {
private static final String GRPC_STREAM_CLASS = "io.grpc.stub.StreamObserver";
private static final Logger logger = LoggerFactory.getLogger(MethodDescriptor.class);
+ protected final String methodName;
private final Method method;
private final String paramDesc;
/**
@@ -55,46 +56,19 @@ public class MethodDescriptor {
private final Class<?>[] parameterClasses;
private final Class<?> returnClass;
private final Type[] returnTypes;
- private final String methodName;
private final boolean generic;
private final boolean wrap;
- private final RpcType rpcType;
private final ConcurrentMap<String, Object> attributeMap = new ConcurrentHashMap<>();
- /**
- * only for tri protocol
- * support StreamObserver
- */
- private final Class<?>[] realParameterClasses;
- private final Class<?> realReturnClass;
-
public MethodDescriptor(Method method) {
+ this(method, method.getParameterTypes(), method.getReturnType());
+ }
+
+ public MethodDescriptor(Method method, Class<?>[] parameterClasses, Class<?> returnClass) {
this.method = method;
this.methodName = method.getName();
- Class<?>[] parameterTypes = method.getParameterTypes();
- realParameterClasses = parameterTypes;
- realReturnClass = method.getReturnType();
- // bidirectional-stream: StreamObserver<Request> foo(StreamObserver<Response>)
- if (parameterTypes.length == 1 && isStreamType(parameterTypes[0])) {
- this.parameterClasses = new Class<?>[]{
- (Class<?>) ((ParameterizedType) method.getGenericReturnType()).getActualTypeArguments()[0]};
- this.returnClass = (Class<?>) ((ParameterizedType) method.getGenericParameterTypes()[0])
- .getActualTypeArguments()[0];
- this.rpcType = RpcType.BIDIRECTIONAL_STREAM;
- // server-stream: void foo(Request, StreamObserver<Response>)
- } else if (parameterTypes.length == 2 && method.getReturnType().equals(Void.TYPE)
- && !isStreamType(parameterTypes[0]) && isStreamType(parameterTypes[1])) {
- this.parameterClasses = method.getParameterTypes();
- this.returnClass =
- (Class<?>) ((ParameterizedType) method.getGenericParameterTypes()[1]).getActualTypeArguments()[0];
- this.rpcType = RpcType.SERVER_STREAM;
- } else {
- // unary: Response foo(Request)
- this.parameterClasses = method.getParameterTypes();
- this.returnClass = method.getReturnType();
- this.rpcType = RpcType.UNARY;
- }
- this.wrap = needWrap();
+ this.parameterClasses = parameterClasses;
+ this.returnClass = returnClass;
Type[] returnTypesResult;
try {
returnTypesResult = ReflectUtils.getReturnTypes(method);
@@ -102,12 +76,12 @@ public class MethodDescriptor {
logger.error("fail to get return types. Method name: " + methodName + " Declaring class:" + method.getDeclaringClass().getName(), throwable);
returnTypesResult = new Type[]{returnClass, returnClass};
}
-
this.returnTypes = returnTypesResult;
+ this.wrap = needWrap();
this.paramDesc = ReflectUtils.getDesc(parameterClasses);
this.compatibleParamSignatures = Stream.of(parameterClasses)
- .map(Class::getName)
- .toArray(String[]::new);
+ .map(Class::getName)
+ .toArray(String[]::new);
this.generic = (methodName.equals($INVOKE) || methodName.equals($INVOKE_ASYNC)) && parameterClasses.length == 3;
}
@@ -115,32 +89,16 @@ public class MethodDescriptor {
return StreamObserver.class.isAssignableFrom(clz) || GRPC_STREAM_CLASS.equalsIgnoreCase(clz.getName());
}
- public boolean isStream() {
- return rpcType.equals(RpcType.SERVER_STREAM) || rpcType.equals(RpcType.BIDIRECTIONAL_STREAM) || rpcType.equals(RpcType.CLIENT_STREAM);
- }
-
- public boolean isServerStream() {
- return RpcType.SERVER_STREAM.equals(rpcType);
- }
-
- public boolean isUnary() {
- return rpcType.equals(RpcType.UNARY);
- }
-
public boolean isNeedWrap() {
return wrap;
}
- public RpcType getRpcType() {
- return rpcType;
- }
-
/**
* 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
*/
- private boolean needWrap() {
+ protected boolean needWrap() {
// generic call must be wrapped
if (CommonConstants.$INVOKE.equals(methodName) || CommonConstants.$INVOKE_ASYNC.equals(methodName)) {
return true;
@@ -149,106 +107,64 @@ public class MethodDescriptor {
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];
+ for (Class<?> parameterClass : parameterClasses) {
+ if (isStreamType(parameterClass)) {
+ // more than one stream param
+ throw new IllegalStateException("method params error: more than one Stream params. method=" + methodName);
+ }
if (isProtobufClass(parameterClass)) {
protobufParameterCount++;
} else {
- if (isStreamType(parameterClass)) {
- if (i == 1) {
- secondParameterStream = true;
- }
- streamParameterCount++;
- } else {
- javaParameterCount++;
- }
+ javaParameterCount++;
+ }
+ if (protobufParameterCount > 0 && javaParameterCount > 0) {
+ throw new IllegalStateException("Bad method type, can not mix protobuf and normal pojo");
}
- }
- // 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);
- }
+
+ boolean returnClassProtobuf = isProtobufClass(returnClass);
+ if (protobufParameterCount > 0 && returnClassProtobuf) {
+ return false;
}
- if (isStream()) {
- if (RpcType.SERVER_STREAM == rpcType) {
- 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)) {
+ // 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) method.getGenericReturnType()).getActualTypeArguments()[0];
+ boolean actualReturnClassProtobuf = isProtobufClass(actualReturnClass);
+ if (actualReturnClassProtobuf && protobufParameterCount == 1) {
return false;
}
- if (protobufParameterCount <= 0 && !returnClassProtobuf) {
+ if (!actualReturnClassProtobuf && protobufParameterCount == 0) {
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) method.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();
- if (ignore) {
- return protobufParameterCount != 1;
- }
+ }
+
+ // todo remove this in future
+ boolean ignore = checkNeedIgnore();
+ if (ignore) {
+ return protobufParameterCount != 1;
+ }
+ if (!returnClassProtobuf || javaParameterCount > 0) {
throw new IllegalStateException("method params error method=" + methodName);
}
+// throw new IllegalStateException("method params error method=" + methodName);
// java param should be wrapped
return javaParameterCount > 0;
}
@@ -257,10 +173,7 @@ public class MethodDescriptor {
* fixme will produce error on grpc. but is harmless so ignore now
*/
private boolean checkNeedIgnore() {
- if (Iterator.class.isAssignableFrom(returnClass)) {
- return true;
- }
- return false;
+ return Iterator.class.isAssignableFrom(returnClass);
}
private boolean isMono(Class<?> clz) {
@@ -271,7 +184,6 @@ public class MethodDescriptor {
return RX_RETURN_CLASS.equalsIgnoreCase(clz.getName());
}
-
public boolean isProtobufClass(Class<?> clazz) {
while (clazz != Object.class && clazz != null) {
Class<?>[] interfaces = clazz.getInterfaces();
@@ -331,19 +243,6 @@ public class MethodDescriptor {
return this.attributeMap.get(key);
}
-
- public Class<?>[] getRealParameterClasses() {
- return realParameterClasses;
- }
-
- public Class<?> getRealReturnClass() {
- return realReturnClass;
- }
-
- public enum RpcType {
- UNARY, SERVER_STREAM, CLIENT_STREAM, BIDIRECTIONAL_STREAM
- }
-
@Override
public boolean equals(Object o) {
if (this == o) {
@@ -355,7 +254,6 @@ public class MethodDescriptor {
MethodDescriptor that = (MethodDescriptor) o;
return generic == that.generic
&& wrap == that.wrap
- && rpcType == that.rpcType
&& Objects.equals(method, that.method)
&& Objects.equals(paramDesc, that.paramDesc)
&& Arrays.equals(compatibleParamSignatures, that.compatibleParamSignatures)
@@ -363,18 +261,15 @@ public class MethodDescriptor {
&& Objects.equals(returnClass, that.returnClass)
&& Arrays.equals(returnTypes, that.returnTypes)
&& Objects.equals(methodName, that.methodName)
- && Objects.equals(attributeMap, that.attributeMap)
- && Arrays.equals(realParameterClasses, that.realParameterClasses)
- && Objects.equals(realReturnClass, that.realReturnClass);
+ && Objects.equals(attributeMap, that.attributeMap);
}
@Override
public int hashCode() {
- int result = Objects.hash(method, paramDesc, returnClass, methodName, generic, wrap, rpcType, attributeMap, realReturnClass);
+ int result = Objects.hash(method, paramDesc, returnClass, methodName, generic, wrap, attributeMap);
result = 31 * result + Arrays.hashCode(compatibleParamSignatures);
result = 31 * result + Arrays.hashCode(parameterClasses);
result = 31 * result + Arrays.hashCode(returnTypes);
- result = 31 * result + Arrays.hashCode(realParameterClasses);
return result;
}
}
diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ServiceDescriptor.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ServiceDescriptor.java
index 621a3b1..c09dd9a 100644
--- a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ServiceDescriptor.java
+++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ServiceDescriptor.java
@@ -51,8 +51,7 @@ public class ServiceDescriptor {
}
public FullServiceDefinition getFullServiceDefinition(String serviceKey) {
- return serviceDefinitions.computeIfAbsent(serviceKey,
- (k) -> ServiceDefinitionBuilder.buildFullDefinition(serviceInterfaceClass, Collections.emptyMap()));
+ return serviceDefinitions.computeIfAbsent(serviceKey, (k) -> ServiceDefinitionBuilder.buildFullDefinition(serviceInterfaceClass, Collections.emptyMap()));
}
private void initMethods() {
@@ -60,7 +59,12 @@ public class ServiceDescriptor {
for (Method method : methodsToExport) {
method.setAccessible(true);
- MethodDescriptor methodDescriptor = new MethodDescriptor(method);
+ MethodDescriptor methodDescriptor;
+ if (StreamMethodDescriptor.isStreamMethod(method)) {
+ methodDescriptor = new StreamMethodDescriptor(method);
+ } else {
+ methodDescriptor = new MethodDescriptor(method);
+ }
List<MethodDescriptor> methodModels = methods.computeIfAbsent(method.getName(), (k) -> new ArrayList<>(1));
methodModels.add(methodDescriptor);
@@ -137,9 +141,9 @@ public class ServiceDescriptor {
}
ServiceDescriptor that = (ServiceDescriptor) o;
return Objects.equals(interfaceName, that.interfaceName)
- && Objects.equals(serviceInterfaceClass, that.serviceInterfaceClass)
- && Objects.equals(methods, that.methods)
- && Objects.equals(descToMethods, that.descToMethods);
+ && Objects.equals(serviceInterfaceClass, that.serviceInterfaceClass)
+ && Objects.equals(methods, that.methods)
+ && Objects.equals(descToMethods, that.descToMethods);
}
@Override
diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/StreamMethodDescriptor.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/StreamMethodDescriptor.java
new file mode 100644
index 0000000..046519a
--- /dev/null
+++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/StreamMethodDescriptor.java
@@ -0,0 +1,88 @@
+/*
+ * 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.model;
+
+import org.apache.dubbo.common.Experimental;
+import org.apache.dubbo.common.stream.StreamObserver;
+
+import java.lang.reflect.Method;
+import java.lang.reflect.ParameterizedType;
+
+@Experimental("Experiment api for abstract method descriptor, this class may be renamed or deleted in the future")
+public class StreamMethodDescriptor extends MethodDescriptor {
+
+ private static final String GRPC_STREAM_CLASS = "io.grpc.stub.StreamObserver";
+
+ public Class<?> requestType;
+ public Class<?> responseType;
+ public StreamType streamType;
+
+ public StreamMethodDescriptor(Method method) {
+ super(method);
+ }
+
+ public static boolean isStreamMethod(Method method) {
+ Class<?>[] parameterTypes = method.getParameterTypes();
+ return (parameterTypes.length == 1 && isStreamType(parameterTypes[0])) ||
+ (parameterTypes.length == 2 && method.getReturnType().equals(Void.TYPE)
+ && !isStreamType(parameterTypes[0]) && isStreamType(parameterTypes[1]));
+ }
+
+ private static boolean isStreamType(Class<?> clz) {
+ return StreamObserver.class.isAssignableFrom(clz) || GRPC_STREAM_CLASS.equalsIgnoreCase(clz.getName());
+ }
+
+ @Override
+ public Class<?> getReturnClass() {
+ return responseType;
+ }
+
+ @Override
+ protected boolean needWrap() {
+ Class<?>[] parameterTypes = getMethod().getParameterTypes();
+ // bidirectional-stream: StreamObserver<Request> foo(StreamObserver<Response>)
+ if (parameterTypes.length == 1 && isStreamType(parameterTypes[0])) {
+ this.requestType =
+ (Class<?>) ((ParameterizedType) getMethod().getGenericReturnType()).getActualTypeArguments()[0];
+ this.responseType = (Class<?>) ((ParameterizedType) getMethod().getGenericParameterTypes()[0])
+ .getActualTypeArguments()[0];
+ this.streamType = StreamType.BI_DIRECTIONAL;
+ // server-stream: void foo(Request, StreamObserver<Response>)
+ } else {
+ this.requestType = getMethod().getParameterTypes()[0];
+ this.responseType =
+ (Class<?>) ((ParameterizedType) getMethod().getGenericParameterTypes()[1]).getActualTypeArguments()[0];
+ this.streamType = StreamType.SERVER;
+ }
+ if (isProtobufClass(requestType) && isProtobufClass(responseType)) {
+ return false;
+ } else if (!isProtobufClass(requestType) && !isProtobufClass(responseType)) {
+ return true;
+ }
+ throw new IllegalStateException("method params error method=" + methodName);
+ }
+
+ public boolean isServerStream() {
+ return streamType == StreamType.SERVER;
+ }
+
+
+ public enum StreamType {
+ SERVER, CLIENT, BI_DIRECTIONAL
+ }
+}
diff --git a/dubbo-common/src/test/java/org/apache/dubbo/descriptor/MethodDescriptorTest.java b/dubbo-common/src/test/java/org/apache/dubbo/descriptor/MethodDescriptorTest.java
index 333557c..4f4429c 100644
--- a/dubbo-common/src/test/java/org/apache/dubbo/descriptor/MethodDescriptorTest.java
+++ b/dubbo-common/src/test/java/org/apache/dubbo/descriptor/MethodDescriptorTest.java
@@ -19,6 +19,7 @@ package org.apache.dubbo.descriptor;
import org.apache.dubbo.common.stream.StreamObserver;
import org.apache.dubbo.proto.HelloReply;
import org.apache.dubbo.rpc.model.MethodDescriptor;
+import org.apache.dubbo.rpc.model.StreamMethodDescriptor;
import io.reactivex.Single;
import org.junit.jupiter.api.Assertions;
@@ -48,7 +49,6 @@ public class MethodDescriptorTest {
MethodDescriptor descriptor = new MethodDescriptor(method);
assertEquals("", descriptor.getParamDesc());
Assertions.assertEquals(0, descriptor.getParameterClasses().length);
- assertTrue(descriptor.isUnary());
assertFalse(descriptor.isNeedWrap());
}
@@ -58,63 +58,56 @@ public class MethodDescriptorTest {
MethodDescriptor descriptor = new MethodDescriptor(method);
assertEquals("", descriptor.getParamDesc());
Assertions.assertEquals(0, descriptor.getParameterClasses().length);
- assertTrue(descriptor.isUnary());
assertTrue(descriptor.isNeedWrap());
}
@Test
public void testWrapperBiStream() throws Exception {
Method method = DescriptorService.class.getMethod("wrapBidirectionalStream", StreamObserver.class);
- MethodDescriptor descriptor = new MethodDescriptor(method);
+ StreamMethodDescriptor descriptor = new StreamMethodDescriptor(method);
Assertions.assertEquals(1, descriptor.getParameterClasses().length);
- assertTrue(descriptor.isStream());
- assertSame(descriptor.getRpcType(), MethodDescriptor.RpcType.BIDIRECTIONAL_STREAM);
+ assertSame(descriptor.streamType, StreamMethodDescriptor.StreamType.BI_DIRECTIONAL);
assertTrue(descriptor.isNeedWrap());
}
@Test
public void testBiStream() throws Exception {
Method method = DescriptorService.class.getMethod("bidirectionalStream", StreamObserver.class);
- MethodDescriptor descriptor = new MethodDescriptor(method);
+ StreamMethodDescriptor descriptor = new StreamMethodDescriptor(method);
Assertions.assertEquals(1, descriptor.getParameterClasses().length);
- assertTrue(descriptor.isStream());
- assertSame(descriptor.getRpcType(), MethodDescriptor.RpcType.BIDIRECTIONAL_STREAM);
+ assertSame(descriptor.streamType, StreamMethodDescriptor.StreamType.BI_DIRECTIONAL);
assertFalse(descriptor.isNeedWrap());
}
@Test
public void testIsStream() throws NoSuchMethodException {
Method method = DescriptorService.class.getMethod("noParameterMethod");
- MethodDescriptor descriptor = new MethodDescriptor(method);
- Assertions.assertFalse(descriptor.isStream());
+
+ Assertions.assertFalse(StreamMethodDescriptor.isStreamMethod(method));
method = DescriptorService.class.getMethod("sayHello", HelloReply.class);
- descriptor = new MethodDescriptor(method);
- Assertions.assertFalse(descriptor.isStream());
+ Assertions.assertFalse(StreamMethodDescriptor.isStreamMethod(method));
}
@Test
public void testIsUnary() throws NoSuchMethodException {
Method method = DescriptorService.class.getMethod("noParameterMethod");
MethodDescriptor descriptor = new MethodDescriptor(method);
- Assertions.assertTrue(descriptor.isUnary());
+ Assertions.assertFalse(StreamMethodDescriptor.isStreamMethod(method));
method = DescriptorService.class.getMethod("sayHello", HelloReply.class);
- descriptor = new MethodDescriptor(method);
- Assertions.assertTrue(descriptor.isUnary());
+ Assertions.assertFalse(StreamMethodDescriptor.isStreamMethod(method));
}
@Test
public void testIsServerStream() throws NoSuchMethodException {
Method method = DescriptorService.class.getMethod("sayHelloServerStream", HelloReply.class,
StreamObserver.class);
- MethodDescriptor descriptor = new MethodDescriptor(method);
- Assertions.assertFalse(descriptor.isUnary());
+ StreamMethodDescriptor descriptor = new StreamMethodDescriptor(method);
Assertions.assertFalse(descriptor.isNeedWrap());
Method method2 = DescriptorService.class.getMethod("sayHelloServerStream2", Object.class, StreamObserver.class);
- MethodDescriptor descriptor2 = new MethodDescriptor(method2);
- Assertions.assertFalse(descriptor2.isUnary());
+ StreamMethodDescriptor descriptor2 = new StreamMethodDescriptor(method2);
Assertions.assertTrue(descriptor2.isNeedWrap());
}
@@ -140,12 +133,12 @@ public class MethodDescriptorTest {
Assertions.assertFalse(descriptor2.isNeedWrap());
Method method3 = DescriptorService.class.getMethod("reactorMethod2", Mono.class);
- MethodDescriptor descriptor3 = new MethodDescriptor(method3);
+ MethodDescriptor descriptor3 = new MethodDescriptor(method3);
Assertions.assertFalse(descriptor3.isNeedWrap());
Method method4 = DescriptorService.class.getMethod("rxJavaMethod", Single.class);
- MethodDescriptor descriptor4 = new MethodDescriptor(method4);
+ MethodDescriptor descriptor4 = new MethodDescriptor(method4);
Assertions.assertFalse(descriptor4.isNeedWrap());
}
diff --git a/dubbo-rpc/dubbo-rpc-triple/pom.xml b/dubbo-rpc/dubbo-rpc-triple/pom.xml
index 6744fde..adda188 100644
--- a/dubbo-rpc/dubbo-rpc-triple/pom.xml
+++ b/dubbo-rpc/dubbo-rpc-triple/pom.xml
@@ -14,7 +14,7 @@
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/AbstractClientStream.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/AbstractClientStream.java
deleted file mode 100644
index b3540e8..0000000
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/AbstractClientStream.java
+++ /dev/null
@@ -1,487 +0,0 @@
-/*
- * 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.ConfigurationUtils;
-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.common.utils.CollectionUtils;
-import org.apache.dubbo.remoting.Constants;
-import org.apache.dubbo.remoting.api.Connection;
-import org.apache.dubbo.remoting.exchange.Request;
-import org.apache.dubbo.remoting.exchange.support.DefaultFuture2;
-import org.apache.dubbo.rpc.CancellationContext;
-import org.apache.dubbo.rpc.RpcException;
-import org.apache.dubbo.rpc.RpcInvocation;
-import org.apache.dubbo.rpc.model.ConsumerModel;
-import org.apache.dubbo.rpc.model.MethodDescriptor;
-import org.apache.dubbo.rpc.model.ServiceModel;
-import org.apache.dubbo.triple.TripleWrapper;
-
-import com.google.protobuf.Any;
-import com.google.protobuf.ByteString;
-import com.google.rpc.DebugInfo;
-import com.google.rpc.ErrorInfo;
-import com.google.rpc.Status;
-import io.netty.channel.ChannelPromise;
-import io.netty.handler.codec.http.HttpHeaderNames;
-import io.netty.handler.codec.http.HttpHeaderValues;
-import io.netty.handler.codec.http.HttpMethod;
-import io.netty.handler.codec.http2.Http2Headers;
-import io.netty.util.AsciiString;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.RejectedExecutionException;
-
-import static org.apache.dubbo.rpc.Constants.COMPRESSOR_KEY;
-import static org.apache.dubbo.rpc.protocol.tri.Compressor.DEFAULT_COMPRESSOR;
-
-
-/**
- * Abstracting common actions for client streaming.
- */
-public abstract class AbstractClientStream extends AbstractStream implements Stream {
-
- private final AsciiString scheme;
- private ConsumerModel consumerModel;
- private Connection connection;
- private RpcInvocation rpcInvocation;
- private long requestId;
-
- protected AbstractClientStream(URL url) {
- super(url);
- this.scheme = getSchemeFromUrl(url);
- this.getCancellationContext().addListener(context -> {
- Throwable throwable = this.getCancellationContext().getCancellationCause();
- if (LOGGER.isWarnEnabled()) {
- LOGGER.warn("Triple request to "
- + getConsumerModel().getServiceName() + "#" + getMethodName() +
- " was canceled by local exception ", throwable);
- }
- // for client cancel,send rst frame to server
- this.outboundTransportObserver()
- .onError(GrpcStatus.fromCode(GrpcStatus.Code.CANCELLED).withCause(throwable));
- });
- }
-
-
- public static UnaryClientStream unary(URL url) {
- return new UnaryClientStream(url);
- }
-
- public static ClientStream stream(URL url) {
- return new ClientStream(url);
- }
-
- /**
- * TODO move this method to somewhere else
- *
- * @param req the request
- * @param connection connection
- * @return a client stream
- */
- public static AbstractClientStream newClientStream(Request req, Connection connection) {
- final RpcInvocation inv = (RpcInvocation) req.getData();
- final URL url = inv.getInvoker().getUrl();
- ConsumerModel consumerModel = inv.getServiceModel() != null ? (ConsumerModel) inv.getServiceModel() : (ConsumerModel) url.getServiceModel();
- MethodDescriptor methodDescriptor = getTriMethodDescriptor(consumerModel, inv);
- ClassLoadUtil.switchContextLoader(consumerModel.getClassLoader());
- AbstractClientStream stream = methodDescriptor.isUnary() ? unary(url) : stream(url);
- Compressor compressor = getCompressor(url, consumerModel);
- stream.request(req)
- .service(consumerModel)
- .connection(connection)
- .serialize((String) inv.getObjectAttachment(Constants.SERIALIZATION_KEY))
- .method(methodDescriptor)
- .setCompressor(compressor);
- return stream;
- }
-
- private static Compressor getCompressor(URL url, ServiceModel model) {
- String compressorStr = url.getParameter(COMPRESSOR_KEY);
- if (compressorStr == null) {
- // Compressor can not be set by dynamic config
- compressorStr = ConfigurationUtils
- .getCachedDynamicProperty(model.getModuleModel(), COMPRESSOR_KEY, DEFAULT_COMPRESSOR);
- }
- return Compressor.getCompressor(url.getOrDefaultFrameworkModel(), compressorStr);
- }
-
- /**
- * Get the tri protocol special MethodDescriptor
- */
- private static MethodDescriptor getTriMethodDescriptor(ConsumerModel consumerModel, RpcInvocation inv) {
- List<MethodDescriptor> methodDescriptors = consumerModel.getServiceModel().getMethods(inv.getMethodName());
- if (CollectionUtils.isEmpty(methodDescriptors)) {
- throw new IllegalStateException("methodDescriptors must not be null method=" + inv.getMethodName());
- }
- for (MethodDescriptor methodDescriptor : methodDescriptors) {
- if (Arrays.equals(inv.getParameterTypes(), methodDescriptor.getRealParameterClasses())) {
- return methodDescriptor;
- }
- }
- throw new IllegalStateException("methodDescriptors must not be null method=" + inv.getMethodName());
- }
-
- private Map<Class<?>, Object> tranFromStatusDetails(List<Any> detailList) {
- Map<Class<?>, Object> map = new HashMap<>();
- 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("tran from grpc-status-details error", t);
- }
- return map;
- }
-
- Throwable getThrowableFromTrailers(Metadata metadata) {
- if (null == metadata) {
- return null;
- }
- // second get status detail
- if (!metadata.contains(TripleHeaderEnum.STATUS_DETAIL_KEY.getHeader())) {
- return null;
- }
- final CharSequence raw = metadata.get(TripleHeaderEnum.STATUS_DETAIL_KEY.getHeader());
- byte[] statusDetailBin = decodeASCIIByte(raw);
- ClassLoader tccl = Thread.currentThread().getContextClassLoader();
- try {
- final Status statusDetail = unpack(statusDetailBin, Status.class);
- List<Any> detailList = statusDetail.getDetailsList();
- Map<Class<?>, Object> classObjectMap = tranFromStatusDetails(detailList);
-
- // get common exception from DebugInfo
- DebugInfo debugInfo = (DebugInfo) classObjectMap.get(DebugInfo.class);
- if (debugInfo == null) {
- return new RpcException(statusDetail.getCode(),
- GrpcStatus.decodeMessage(statusDetail.getMessage()));
- }
- String msg = ExceptionUtils.getStackFrameString(debugInfo.getStackEntriesList());
- return new RpcException(statusDetail.getCode(), msg);
- } finally {
- ClassLoadUtil.switchContextLoader(tccl);
- }
- }
-
- protected void startCall(WriteQueue queue, ChannelPromise promise) {
- execute(() -> {
- final ClientOutboundTransportObserver clientTransportObserver = new ClientOutboundTransportObserver(queue, promise);
- subscribe(clientTransportObserver);
- try {
- doOnStartCall();
- } catch (Throwable throwable) {
- cancel(throwable);
- DefaultFuture2.getFuture(getRequestId()).cancel();
- }
- });
- }
-
- protected abstract void doOnStartCall();
-
- @Override
- protected StreamObserver<Object> createStreamObserver() {
- return new ClientStreamObserverImpl(getCancellationContext());
- }
-
- @Override
- protected void cancelByRemoteReset() {
- DefaultFuture2.getFuture(getRequestId()).cancel();
- }
-
- @Override
- protected void cancelByLocal(Throwable throwable) {
- getCancellationContext().cancel(throwable);
- }
-
- @Override
- public void execute(Runnable runnable) {
- try {
- super.execute(runnable);
- } catch (RejectedExecutionException e) {
- LOGGER.error("Consumer's thread pool is full", e);
- outboundMessageSubscriber().onError(GrpcStatus.fromCode(GrpcStatus.Code.RESOURCE_EXHAUSTED)
- .withDescription("Consumer's thread pool is full").asException());
- } catch (Throwable t) {
- LOGGER.error("Consumer submit request to thread pool error ", t);
- outboundMessageSubscriber().onError(GrpcStatus.fromCode(GrpcStatus.Code.INTERNAL)
- .withCause(t)
- .withDescription("Consumer's error")
- .asException());
- }
- }
-
- public AbstractClientStream service(ConsumerModel model) {
- this.consumerModel = model;
- return this;
- }
-
- public AbstractClientStream request(Request request) {
- this.requestId = request.getId();
- this.rpcInvocation = (RpcInvocation) request.getData();
- return this;
- }
-
- protected RpcInvocation getRpcInvocation() {
- return this.rpcInvocation;
- }
-
- public AsciiString getScheme() {
- return scheme;
- }
-
- public long getRequestId() {
- return requestId;
- }
-
- private AsciiString getSchemeFromUrl(URL url) {
- try {
- Boolean ssl = url.getParameter(CommonConstants.SSL_ENABLED_KEY, Boolean.class);
- if (ssl == null) {
- return TripleConstant.HTTP_SCHEME;
- }
- return ssl ? TripleConstant.HTTPS_SCHEME : TripleConstant.HTTP_SCHEME;
- } catch (Exception e) {
- return TripleConstant.HTTP_SCHEME;
- }
- }
-
- public ConsumerModel getConsumerModel() {
- return consumerModel;
- }
-
- public AbstractClientStream connection(Connection connection) {
- this.connection = connection;
- return this;
- }
-
- public Connection getConnection() {
- return connection;
- }
-
- protected byte[] encodeRequest(Object value) {
- final byte[] out;
- final Object obj;
-
- if (getMethodDescriptor().isNeedWrap()) {
- obj = getRequestWrapper(value);
- } else {
- obj = getRequestValue(value);
- }
- out = pack(obj);
- return super.compress(out);
- }
-
- private TripleWrapper.TripleRequestWrapper getRequestWrapper(Object value) {
- if (getMethodDescriptor().isStream()) {
- String type = getMethodDescriptor().getParameterClasses()[0].getName();
- return wrapReq(getUrl(), getSerializeType(), value, type, getMultipleSerialization());
- } else {
- RpcInvocation invocation = (RpcInvocation) value;
- return wrapReq(getUrl(), invocation, getMultipleSerialization());
- }
- }
-
- private TripleWrapper.TripleRequestWrapper wrapReq(URL url, RpcInvocation invocation,
- MultipleSerialization serialization) {
- try {
- String serializationName = (String) invocation.getObjectAttachment(Constants.SERIALIZATION_KEY);
- final TripleWrapper.TripleRequestWrapper.Builder builder = TripleWrapper.TripleRequestWrapper.newBuilder()
- .setSerializeType(convertHessianToWrapper(serializationName));
- for (int i = 0; i < invocation.getArguments().length; i++) {
- final String clz = invocation.getParameterTypes()[i].getName();
- builder.addArgTypes(clz);
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- serialization.serialize(url, serializationName, clz, invocation.getArguments()[i], bos);
- builder.addArgs(ByteString.copyFrom(bos.toByteArray()));
- }
- return builder.build();
- } catch (IOException e) {
- throw new RuntimeException("Failed to pack wrapper req", e);
- }
- }
-
- public TripleWrapper.TripleRequestWrapper wrapReq(URL url, String serializeType, Object req,
- String type,
- MultipleSerialization multipleSerialization) {
- try {
- final TripleWrapper.TripleRequestWrapper.Builder builder = TripleWrapper.TripleRequestWrapper.newBuilder()
- .addArgTypes(type)
- .setSerializeType(convertHessianToWrapper(serializeType));
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- multipleSerialization.serialize(url, serializeType, type, req, bos);
- builder.addArgs(ByteString.copyFrom(bos.toByteArray()));
- bos.close();
- return builder.build();
- } catch (IOException e) {
- throw new RuntimeException("Failed to pack wrapper req", e);
- }
- }
-
- private Object getRequestValue(Object value) {
- if (getMethodDescriptor().isUnary()) {
- RpcInvocation invocation = (RpcInvocation) value;
- return invocation.getArguments()[0];
- }
- return value;
- }
-
- protected Object deserializeResponse(byte[] data) {
- ClassLoader tccl = Thread.currentThread().getContextClassLoader();
- try {
- if (getConsumerModel() != null) {
- ClassLoadUtil.switchContextLoader(getConsumerModel().getClassLoader());
- }
- if (getMethodDescriptor().isNeedWrap()) {
- final TripleWrapper.TripleResponseWrapper wrapper = unpack(data,
- TripleWrapper.TripleResponseWrapper.class);
- if (!getSerializeType().equals(convertHessianFromWrapper(wrapper.getSerializeType()))) {
- throw new UnsupportedOperationException("Received inconsistent serialization type from server, " +
- "reject to deserialize! Expected:" + getSerializeType() +
- " Actual:" + convertHessianFromWrapper(wrapper.getSerializeType()));
- }
- return unwrapResp(getUrl(), wrapper, getMultipleSerialization());
- } else {
- return unpack(data, getMethodDescriptor().getReturnClass());
- }
- } finally {
- ClassLoadUtil.switchContextLoader(tccl);
- }
- }
-
- public Object unwrapResp(URL url, TripleWrapper.TripleResponseWrapper wrap,
- MultipleSerialization serialization) {
- String serializeType = convertHessianFromWrapper(wrap.getSerializeType());
- try {
- final ByteArrayInputStream bais = new ByteArrayInputStream(wrap.getData().toByteArray());
- final Object ret = serialization.deserialize(url, serializeType, wrap.getType(), bais);
- bais.close();
- return ret;
- } catch (Exception e) {
- throw new RuntimeException("Failed to unwrap resp", e);
- }
- }
-
-
- protected Metadata createRequestMeta(RpcInvocation inv) {
- Metadata metadata = new DefaultMetadata();
- // put http2 params
- metadata.put(Http2Headers.PseudoHeaderName.SCHEME.value(), this.getScheme())
- .put(Http2Headers.PseudoHeaderName.PATH.value(), getMethodPath(inv))
- .put(Http2Headers.PseudoHeaderName.AUTHORITY.value(), getUrl().getAddress())
- .put(Http2Headers.PseudoHeaderName.METHOD.value(), HttpMethod.POST.asciiName());
-
- metadata.put(TripleHeaderEnum.CONTENT_TYPE_KEY.getHeader(), TripleConstant.CONTENT_PROTO)
- .put(HttpHeaderNames.TE, HttpHeaderValues.TRAILERS);
-
- if (inv.get(CommonConstants.TIMEOUT_KEY) != null) {
- metadata.put(TripleHeaderEnum.TIMEOUT.getHeader(), inv.get(CommonConstants.TIMEOUT_KEY) + "m");
- }
- if (!"1.0.0".equals(getUrl().getVersion())) {
- metadata.putIfNotNull(TripleHeaderEnum.SERVICE_VERSION.getHeader(), getUrl().getVersion());
- }
- metadata.putIfNotNull(TripleHeaderEnum.CONSUMER_APP_NAME_KEY.getHeader(),
- (String) inv.getObjectAttachments().remove(CommonConstants.APPLICATION_KEY))
- .putIfNotNull(TripleHeaderEnum.CONSUMER_APP_NAME_KEY.getHeader(),
- (String) inv.getObjectAttachments().remove(CommonConstants.REMOTE_APPLICATION_KEY))
- .putIfNotNull(TripleHeaderEnum.SERVICE_GROUP.getHeader(), getUrl().getGroup())
- .putIfNotNull(TripleHeaderEnum.GRPC_ACCEPT_ENCODING.getHeader(), Compressor.getAcceptEncoding(getUrl().getOrDefaultFrameworkModel()));
- if (!Compressor.NONE.getMessageEncoding().equals(getCompressor().getMessageEncoding())) {
- metadata.putIfNotNull(TripleHeaderEnum.GRPC_ENCODING.getHeader(), getCompressor().getMessageEncoding());
- }
- final Map<String, Object> attachments = inv.getObjectAttachments();
- if (attachments != null) {
- convertAttachment(metadata, attachments);
- }
- return metadata;
- }
-
- private String getMethodPath(RpcInvocation inv) {
- return "/" + inv.getObjectAttachment(CommonConstants.PATH_KEY) + "/" + inv.getMethodName();
- }
-
- protected class ClientStreamObserverImpl extends CancelableStreamObserver<Object> implements ClientStreamObserver<Object> {
-
- public ClientStreamObserverImpl(CancellationContext cancellationContext) {
- super(cancellationContext);
- }
-
- @Override
- public void onNext(Object data) {
- if (getState().allowSendMeta()) {
- final Metadata metadata = createRequestMeta(getRpcInvocation());
- outboundTransportObserver().onMetadata(metadata, false);
- }
- if (getState().allowSendData()) {
- final byte[] bytes = encodeRequest(data);
- outboundTransportObserver().onData(bytes, false);
- }
- }
-
- /**
- * Handle all exceptions in the request process, other procedures directly throw
- * <p>
- * other procedures is {@link ClientStreamObserver#onNext(Object)} and {@link ClientStreamObserver#onCompleted()}
- */
- @Override
- public void onError(Throwable throwable) {
- if (getState().allowSendEndStream()) {
- GrpcStatus status = GrpcStatus.getStatus(throwable);
- transportError(status, null, getState().allowSendMeta());
- } else {
- if (LOGGER.isErrorEnabled()) {
- LOGGER.error("Triple request to "
- + getConsumerModel().getServiceName() + "#" + getMethodName() +
- " was failed by exception ", throwable);
- }
- }
- }
-
- @Override
- public void onCompleted() {
- if (getState().allowSendEndStream()) {
- outboundTransportObserver().onComplete();
- }
- }
-
- @Override
- public void setCompression(String compression) {
- if (!getState().allowSendMeta()) {
- cancel(new IllegalStateException("Metadata already has been sent,can not set compression"));
- return;
- }
- Compressor compressor = Compressor.getCompressor(getUrl().getOrDefaultFrameworkModel(), compression);
- setCompressor(compressor);
- }
- }
-}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/AbstractServerStream.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/AbstractServerStream.java
deleted file mode 100644
index 2f18323..0000000
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/AbstractServerStream.java
+++ /dev/null
@@ -1,439 +0,0 @@
-/*
- * 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.utils.StringUtils;
-import org.apache.dubbo.remoting.Constants;
-import org.apache.dubbo.rpc.HeaderFilter;
-import org.apache.dubbo.rpc.Invoker;
-import org.apache.dubbo.rpc.RpcException;
-import org.apache.dubbo.rpc.RpcInvocation;
-import org.apache.dubbo.rpc.model.FrameworkServiceRepository;
-import org.apache.dubbo.rpc.model.MethodDescriptor;
-import org.apache.dubbo.rpc.model.ProviderModel;
-import org.apache.dubbo.rpc.model.ScopeModelUtil;
-import org.apache.dubbo.rpc.model.ServiceDescriptor;
-import org.apache.dubbo.triple.TripleWrapper;
-
-import com.google.protobuf.ByteString;
-import com.google.protobuf.Message;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Map;
-import java.util.Objects;
-import java.util.concurrent.Executor;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.RejectedExecutionException;
-import java.util.concurrent.TimeUnit;
-
-import static org.apache.dubbo.common.constants.CommonConstants.HEADER_FILTER_KEY;
-import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY;
-
-public abstract class AbstractServerStream extends AbstractStream implements Stream {
-
- private final ProviderModel providerModel;
- private final List<HeaderFilter> headerFilters;
- private ServiceDescriptor serviceDescriptor;
- private List<MethodDescriptor> methodDescriptors;
- private Invoker<?> invoker;
-
- protected AbstractServerStream(URL url) {
- this(url, lookupProviderModel(url));
- }
-
- protected AbstractServerStream(URL url, ProviderModel providerModel) {
- this(url, lookupExecutor(providerModel), providerModel);
- }
-
- protected AbstractServerStream(URL url, Executor executor, ProviderModel providerModel) {
- super(url, executor);
- this.providerModel = providerModel;
- this.serialize(getUrl().getParameter(Constants.SERIALIZATION_KEY, Constants.DEFAULT_REMOTING_SERIALIZATION));
- this.headerFilters = url.getOrDefaultApplicationModel().getExtensionLoader(HeaderFilter.class).getActivateExtension(url, HEADER_FILTER_KEY);
- }
-
- private static Executor lookupExecutor(ProviderModel providerModel) {
- if (providerModel == null) {
- return null;
- }
- return (ExecutorService) providerModel.getServiceMetadata()
- .getAttribute(CommonConstants.THREADPOOL_KEY);
- }
-
- public static UnaryServerStream unary(URL url) {
- return new UnaryServerStream(url);
- }
-
- public static ServerStream stream(URL url) {
- return new ServerStream(url);
- }
-
- public static AbstractServerStream newServerStream(URL url, boolean unary) {
- return unary ? unary(url) : stream(url);
- }
-
- private static ProviderModel lookupProviderModel(URL url) {
- FrameworkServiceRepository repo = ScopeModelUtil.getFrameworkModel(url.getScopeModel()).getServiceRepository();
- final ProviderModel model = repo.lookupExportedService(url.getServiceKey());
- if (model != null) {
- ClassLoadUtil.switchContextLoader(model.getClassLoader());
- }
- return model;
- }
-
- public List<MethodDescriptor> getMethodDescriptors() {
- return methodDescriptors;
- }
-
- public AbstractServerStream methods(List<MethodDescriptor> methods) {
- this.methodDescriptors = methods;
- return this;
- }
-
- public ServiceDescriptor getServiceDescriptor() {
- return serviceDescriptor;
- }
-
- public void setServiceDescriptor(ServiceDescriptor serviceDescriptor) {
- this.serviceDescriptor = serviceDescriptor;
- }
-
- public Invoker<?> getInvoker() {
- return invoker;
- }
-
- public List<HeaderFilter> getHeaderFilters() {
- return headerFilters;
- }
-
- public ProviderModel getProviderModel() {
- return providerModel;
- }
-
- /**
- * Build the RpcInvocation with metadata and execute headerFilter
- *
- * @param metadata request header
- * @return RpcInvocation
- */
- protected RpcInvocation buildInvocation(Metadata metadata) {
- RpcInvocation inv = new RpcInvocation(getUrl().getServiceModel(),
- getMethodName(), getServiceDescriptor().getInterfaceName(),
- getUrl().getProtocolServiceKey(), getMethodDescriptor().getRealParameterClasses(), new Object[0]);
- inv.setTargetServiceUniqueName(getUrl().getServiceKey());
- inv.setReturnTypes(getMethodDescriptor().getReturnTypes());
-
- final Map<String, Object> attachments = parseMetadataToAttachmentMap(metadata);
- inv.setObjectAttachments(attachments);
- // handle timeout
- CharSequence timeout = metadata.get(TripleHeaderEnum.TIMEOUT.getHeader());
- try {
- if (!Objects.isNull(timeout)) {
- final Long timeoutInNanos = parseTimeoutToNanos(timeout.toString());
- if (!Objects.isNull(timeoutInNanos)) {
- inv.setAttachment(TIMEOUT_KEY, timeoutInNanos);
- }
- }
- } catch (Throwable t) {
- LOGGER.warn(String.format("Failed to parse request timeout set from:%s, service=%s method=%s", timeout, getServiceDescriptor().getInterfaceName(),
- getMethodName()));
- }
- invokeHeaderFilter(inv);
- return inv;
- }
-
- /**
- * Intercept the header to do some validation
- * <p>
- * for example, check the token or a user-defined permission check operation
- *
- * @param inv RPC Invocation
- * @throws RpcException maybe throw rpcException
- */
- protected void invokeHeaderFilter(RpcInvocation inv) throws RpcException {
- for (HeaderFilter headerFilter : getHeaderFilters()) {
- headerFilter.invoke(getInvoker(), inv);
- }
- }
-
- /**
- * For the unary method, there may be overloaded methods,
- * so need to parse out the Wrapper from the data and continue buildRpcInvocation
- * <p>
- * Also, to prevent serialization attacks, headerFilter needs to be executed
- *
- * @param metadata request headers
- * @param data request data
- * @return RPC Invocation
- */
- protected RpcInvocation buildUnaryInvocation(Metadata metadata, byte[] data) {
- ClassLoader tccl = Thread.currentThread().getContextClassLoader();
- try {
- if (getProviderModel() != null) {
- ClassLoadUtil.switchContextLoader(getProviderModel().getServiceInterfaceClass().getClassLoader());
- }
- // For the Wrapper method,the methodDescriptor needs to get from data, so parse the request first
- if (needDeserializeWrapper(getMethodDescriptor())) {
- // the wrapper structure is first resolved without actual deserialization
- TripleWrapper.TripleRequestWrapper wrapper = deserializeWrapperSetMdIfNeed(data);
- if (wrapper == null) {
- return null;
- }
- RpcInvocation inv = buildInvocation(metadata);
- inv.setArguments(unwrapReq(getUrl(), wrapper, getMultipleSerialization()));
- return inv;
- } else {
- // Protobuf MethodDescriptor must not be null
- RpcInvocation inv = buildInvocation(metadata);
- inv.setArguments(new Object[]{unpack(data, getMethodDescriptor().getParameterClasses()[0])});
- return inv;
- }
- } catch (RpcException rpcException) {
- // for catch exceptions in headerFilter
- transportError(GrpcStatus.getStatus(rpcException, rpcException.getMessage()));
- return null;
- } catch (Throwable throwable) {
- LOGGER.warn("Decode request failed:", throwable);
- transportError(GrpcStatus.fromCode(GrpcStatus.Code.INTERNAL)
- .withDescription("Decode request failed:" + throwable.getMessage()));
- return null;
- } finally {
- ClassLoadUtil.switchContextLoader(tccl);
- }
- }
-
- /**
- * Deserialize the stream request data
- *
- * @param data request data
- * @return Deserialized object
- */
- protected Object[] deserializeRequest(byte[] data) {
- ClassLoader tccl = Thread.currentThread().getContextClassLoader();
- try {
- if (getProviderModel() != null) {
- ClassLoadUtil.switchContextLoader(getProviderModel().getServiceInterfaceClass().getClassLoader());
- }
- if (needDeserializeWrapper(getMethodDescriptor())) {
- TripleWrapper.TripleRequestWrapper wrapper = deserializeWrapperSetMdIfNeed(data);
- if (wrapper == null) {
- return null;
- }
- return unwrapReq(getUrl(), wrapper, getMultipleSerialization());
- } else {
- // Protobuf MethodDescriptor must not be null
- return new Object[]{unpack(data, getMethodDescriptor().getParameterClasses()[0])};
- }
- } catch (Throwable throwable) {
- LOGGER.warn("Decode request failed:", throwable);
- transportError(GrpcStatus.fromCode(GrpcStatus.Code.INTERNAL)
- .withDescription("Decode request failed:" + throwable.getMessage()));
- return null;
- } finally {
- ClassLoadUtil.switchContextLoader(tccl);
- }
- }
-
- private boolean needDeserializeWrapper(MethodDescriptor md) {
- if (md == null) {
- return true;
- }
- return getMethodDescriptor().isNeedWrap();
- }
-
- private TripleWrapper.TripleRequestWrapper deserializeWrapperSetMdIfNeed(byte[] data) {
- final TripleWrapper.TripleRequestWrapper wrapper = unpack(data, TripleWrapper.TripleRequestWrapper.class);
- if (!getSerializeType().equals(convertHessianFromWrapper(wrapper.getSerializeType()))) {
- transportError(GrpcStatus.fromCode(GrpcStatus.Code.INVALID_ARGUMENT)
- .withDescription("Received inconsistent serialization type from client, " +
- "reject to deserialize! Expected:" + getSerializeType() +
- " Actual:" + convertHessianFromWrapper(wrapper.getSerializeType())));
- return null;
- }
- if (getMethodDescriptor() == null) {
- final String[] paramTypes = wrapper.getArgTypesList().toArray(new String[wrapper.getArgsCount()]);
- // wrapper mode the method can overload so maybe list
- for (MethodDescriptor descriptor : getMethodDescriptors()) {
- // params type is array
- if (Arrays.equals(descriptor.getCompatibleParamSignatures(), paramTypes)) {
- method(descriptor);
- break;
- }
- }
- if (getMethodDescriptor() == null) {
- transportError(GrpcStatus.fromCode(GrpcStatus.Code.UNIMPLEMENTED)
- .withDescription("Method :" + getMethodName() + "[" + Arrays.toString(paramTypes) + "] " +
- "not found of service:" + getServiceDescriptor().getInterfaceName()));
- return null;
- }
- }
- return wrapper;
- }
-
- private Object[] unwrapReq(URL url, TripleWrapper.TripleRequestWrapper wrap,
- MultipleSerialization multipleSerialization) {
- String serializeType = convertHessianFromWrapper(wrap.getSerializeType());
- try {
- Object[] arguments = new Object[wrap.getArgsCount()];
- for (int i = 0; i < arguments.length; i++) {
- final ByteArrayInputStream bais = new ByteArrayInputStream(wrap.getArgs(i).toByteArray());
- Object obj = multipleSerialization.deserialize(url,
- serializeType, wrap.getArgTypes(i), bais);
- arguments[i] = obj;
- }
- return arguments;
- } catch (Exception e) {
- throw new RuntimeException("Failed to unwrap req: " + e.getMessage(), e);
- }
- }
-
- /**
- * create basic meta data
- */
- protected Metadata createResponseMeta() {
- Metadata metadata = createDefaultMetadata();
- metadata.putIfNotNull(TripleHeaderEnum.GRPC_ENCODING.getHeader(), super.getCompressor().getMessageEncoding())
- .putIfNotNull(TripleHeaderEnum.GRPC_ACCEPT_ENCODING.getHeader(), getAcceptEncoding());
- return metadata;
- }
-
- protected Long parseTimeoutToNanos(String timeoutVal) {
- if (StringUtils.isEmpty(timeoutVal) || StringUtils.isContains(timeoutVal, "null")) {
- return null;
- }
- long value = Long.parseLong(timeoutVal.substring(0, timeoutVal.length() - 1));
- char unit = timeoutVal.charAt(timeoutVal.length() - 1);
- switch (unit) {
- case 'n':
- return value;
- case 'u':
- return TimeUnit.MICROSECONDS.toNanos(value);
- case 'm':
- return TimeUnit.MILLISECONDS.toNanos(value);
- case 'S':
- return TimeUnit.SECONDS.toNanos(value);
- case 'M':
- return TimeUnit.MINUTES.toNanos(value);
- case 'H':
- return TimeUnit.HOURS.toNanos(value);
- default:
- // invalid timeout config
- return null;
- }
- }
-
- protected byte[] encodeResponse(Object value) {
- final ClassLoader tccl = Thread.currentThread().getContextClassLoader();
- try {
- if (getProviderModel() != null) {
- ClassLoadUtil.switchContextLoader(getProviderModel().getServiceInterfaceClass().getClassLoader());
- }
- final Message message;
- if (getMethodDescriptor().isNeedWrap()) {
- message = wrapResp(getUrl(), getSerializeType(), value, getMethodDescriptor(),
- getMultipleSerialization());
- } else {
- message = (Message) value;
- }
- byte[] out = pack(message);
- return super.compress(out);
- } catch (Throwable throwable) {
- LOGGER.error("Encode Response data error ", throwable);
- transportError(GrpcStatus.fromCode(GrpcStatus.Code.UNKNOWN)
- .withCause(throwable)
- .withDescription("Encode Response data error"));
- return null;
- } finally {
- ClassLoadUtil.switchContextLoader(tccl);
- }
- }
-
- @Override
- public void execute(Runnable runnable) {
- try {
- super.execute(() -> {
- try {
- runnable.run();
- } catch (Throwable t) {
- LOGGER.error("Exception processing triple message", t);
- transportError(GrpcStatus.fromCode(GrpcStatus.Code.INTERNAL)
- .withDescription("Exception in invoker chain :" + t.getMessage())
- .withCause(t));
- }
- });
- } catch (RejectedExecutionException e) {
- LOGGER.error("Provider's thread pool is full", e);
- transportError(GrpcStatus.fromCode(GrpcStatus.Code.RESOURCE_EXHAUSTED)
- .withDescription("Provider's thread pool is full"));
- } catch (Throwable t) {
- LOGGER.error("Provider submit request to thread pool error ", t);
- transportError(GrpcStatus.fromCode(GrpcStatus.Code.INTERNAL)
- .withCause(t)
- .withDescription("Provider's error"));
- }
- }
-
- public AbstractServerStream service(ServiceDescriptor sd) {
- setServiceDescriptor(sd);
- return this;
- }
-
- public AbstractServerStream invoker(Invoker<?> invoker) {
- this.invoker = invoker;
- return this;
- }
-
- @Override
- protected void cancelByRemoteReset() {
- getCancellationContext().cancel(null);
- }
-
-
- @Override
- protected void cancelByLocal(Throwable throwable) {
- inboundTransportObserver()
- .onError(GrpcStatus.fromCode(GrpcStatus.Code.CANCELLED)
- .withCause(throwable));
- }
-
-
- public TripleWrapper.TripleResponseWrapper wrapResp(URL url, String serializeType, Object resp,
- MethodDescriptor desc,
- MultipleSerialization multipleSerialization) {
- try {
- final TripleWrapper.TripleResponseWrapper.Builder builder = TripleWrapper.TripleResponseWrapper.newBuilder()
- .setType(desc.getReturnClass().getName())
- .setSerializeType(convertHessianToWrapper(serializeType));
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- multipleSerialization.serialize(url, serializeType, desc.getReturnClass().getName(), resp, bos);
- builder.setData(ByteString.copyFrom(bos.toByteArray()));
- bos.close();
- return builder.build();
- } catch (IOException e) {
- throw new RuntimeException("Failed to pack wrapper req", e);
- }
- }
-
-}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/AbstractStream.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/AbstractStream.java
deleted file mode 100644
index dcf4082..0000000
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/AbstractStream.java
+++ /dev/null
@@ -1,520 +0,0 @@
-/*
- * 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.common.threadpool.manager.ExecutorRepository;
-import org.apache.dubbo.common.threadpool.serial.SerializingExecutor;
-import org.apache.dubbo.common.utils.StringUtils;
-import org.apache.dubbo.config.Constants;
-import org.apache.dubbo.rpc.CancellationContext;
-import org.apache.dubbo.rpc.model.MethodDescriptor;
-
-import com.google.protobuf.Any;
-import com.google.rpc.DebugInfo;
-import com.google.rpc.Status;
-import io.netty.handler.codec.http.HttpHeaderNames;
-import io.netty.handler.codec.http.HttpResponseStatus;
-import io.netty.handler.codec.http2.Http2Headers;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.Closeable;
-import java.io.IOException;
-import java.io.InputStream;
-import java.nio.charset.StandardCharsets;
-import java.util.Base64;
-import java.util.HashMap;
-import java.util.Locale;
-import java.util.Map;
-import java.util.concurrent.Executor;
-
-/**
- * AbstractStream provides more detailed actions for streaming process.
- */
-public abstract class AbstractStream implements Stream {
-
- private static final Base64.Decoder BASE64_DECODER = Base64.getDecoder();
- private static final Base64.Encoder BASE64_ENCODER = Base64.getEncoder().withoutPadding();
-
- private final URL url;
- private final MultipleSerialization multipleSerialization;
- private final StreamObserver<Object> inboundMessageObserver;
- private final InboundTransportObserver inboundTransportObserver;
- private final Executor executor;
- private final CancellationContext cancellationContext;
- // AcceptEncoding does not change after the application is started,
- // so it can be obtained when constructing the stream
- private final String acceptEncoding;
-
- private MethodDescriptor methodDescriptor;
- private String methodName;
- private String serializeType;
- private StreamObserver<Object> outboundMessageSubscriber;
- private OutboundTransportObserver outboundTransportObserver;
- private Compressor compressor = IdentityCompressor.NONE;
- private Compressor deCompressor = IdentityCompressor.NONE;
- private volatile boolean cancelled = false;
-
- protected AbstractStream(URL url) {
- this(url, null);
- }
-
- protected AbstractStream(URL url, Executor executor) {
- this.url = url;
- final Executor sourceExecutor = lookupExecutor(url, executor);
- // wrap executor to ensure linear stream message processing
- this.executor = wrapperSerializingExecutor(sourceExecutor);
- final String value = url.getParameter(Constants.MULTI_SERIALIZATION_KEY, CommonConstants.DEFAULT_KEY);
- this.multipleSerialization = url.getOrDefaultFrameworkModel()
- .getExtensionLoader(MultipleSerialization.class)
- .getExtension(value);
- this.cancellationContext = new CancellationContext();
- // A stream implementation must know how to process inbound transport message
- this.inboundTransportObserver = createInboundTransportObserver();
- // A stream implementation must know how to process inbound App level message
- this.inboundMessageObserver = createStreamObserver();
- this.acceptEncoding = Compressor.getAcceptEncoding(getUrl().getOrDefaultFrameworkModel());
- }
-
-
- /**
- * Cancel by remote by receiving reset frame
- */
- protected abstract void cancelByRemoteReset();
-
- /**
- * Cancel by local by some error
- *
- * @param throwable the cancel cause
- */
- protected abstract void cancelByLocal(Throwable throwable);
-
- /**
- * create request StreamObserver
- */
- protected abstract StreamObserver<Object> createStreamObserver();
-
- /**
- * create response TransportObserver
- */
- protected abstract InboundTransportObserver createInboundTransportObserver();
-
- private void closeQuietly(Closeable c) {
- if (c != null) {
- try {
- c.close();
- } catch (IOException ignore) {
- // ignored
- }
- }
- }
-
- private Executor lookupExecutor(URL url, Executor executor) {
- // only server maybe not null
- if (executor != null) {
- return executor;
- }
- ExecutorRepository executorRepository = url.getOrDefaultApplicationModel()
- .getExtensionLoader(ExecutorRepository.class)
- .getDefaultExtension();
- Executor urlExecutor = executorRepository.getExecutor(url);
- if (urlExecutor == null) {
- urlExecutor = executorRepository.createExecutorIfAbsent(url);
- }
- return urlExecutor;
- }
-
- private Executor wrapperSerializingExecutor(Executor executor) {
- return new SerializingExecutor(executor);
- }
-
- public String getAcceptEncoding() {
- return acceptEncoding;
- }
-
- public TransportState getState() {
- return outboundTransportObserver.state;
- }
-
- public boolean isCancelled() {
- return cancelled;
- }
-
- protected CancellationContext getCancellationContext() {
- return cancellationContext;
- }
-
- @Override
- public void execute(Runnable runnable) {
- executor.execute(runnable);
- }
-
- public String getMethodName() {
- return methodName;
- }
-
- public AbstractStream methodName(String methodName) {
- this.methodName = methodName;
- return this;
- }
-
- public AbstractStream method(MethodDescriptor md) {
- this.methodDescriptor = md;
- this.methodName = md.getMethodName();
- return this;
- }
-
- /**
- * local cancel
- *
- * @param cause cancel case
- */
- protected final void cancel(Throwable cause) {
- cancel();
- cancelByLocal(cause);
- }
-
- private void cancel() {
- cancelled = true;
- }
-
- /**
- * remote cancel
- */
- protected final void cancelByRemote() {
- cancel();
- cancelByRemoteReset();
- }
-
-
- public String getSerializeType() {
- return serializeType;
- }
-
- public AbstractStream serialize(String serializeType) {
- if (TripleConstant.HESSIAN4.equals(serializeType)) {
- serializeType = TripleConstant.HESSIAN2;
- }
- this.serializeType = serializeType;
- return this;
- }
-
- public MultipleSerialization getMultipleSerialization() {
- return multipleSerialization;
- }
-
- public StreamObserver<Object> outboundMessageSubscriber() {
- return outboundMessageSubscriber;
- }
-
- public OutboundTransportObserver outboundTransportObserver() {
- return outboundTransportObserver;
- }
-
- public MethodDescriptor getMethodDescriptor() {
- return methodDescriptor;
- }
-
- public Compressor getCompressor() {
- return this.compressor;
- }
-
- /**
- * set compressor if required
- *
- * @param compressor {@link Compressor}
- */
- protected AbstractStream setCompressor(Compressor compressor) {
- // If compressor is NULL, this will not be set.
- // Consider whether to throw an exception or handle silently,
- // But now choose silent processing, Fall back to default.
- if (compressor != null) {
- this.compressor = compressor;
- } else {
- if (LOGGER.isErrorEnabled()) {
- LOGGER.error("Compressor is Null, Fall back to default compression." +
- " MessageEncoding is " + getCompressor().getMessageEncoding());
- }
- }
- return this;
- }
-
- public Compressor getDeCompressor() {
- return this.deCompressor;
- }
-
- protected AbstractStream setDeCompressor(Compressor compressor) {
- // If compressor is NULL, this will not be set.
- // Consider whether to throw an exception or handle silently,
- // But now choose silent processing, Fall back to default.
- if (compressor != null) {
- this.deCompressor = compressor;
- } else {
- if (LOGGER.isErrorEnabled()) {
- LOGGER.error("Compressor is Null, Fall back to default deCompression." +
- " MessageEncoding is " + getDeCompressor().getMessageEncoding());
- }
- }
- return this;
- }
-
- public URL getUrl() {
- return url;
- }
-
- @Override
- public void subscribe(StreamObserver<Object> outboundMessageObserver) {
- this.outboundMessageSubscriber = outboundMessageObserver;
- }
-
- @Override
- public void subscribe(OutboundTransportObserver observer) {
- this.outboundTransportObserver = observer;
- }
-
- public StreamObserver<Object> inboundMessageObserver() {
- return inboundMessageObserver;
- }
-
- @Override
- public TransportObserver inboundTransportObserver() {
- return inboundTransportObserver;
- }
-
- // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#responses
- protected void transportError(GrpcStatus status, Map<String, Object> attachments, boolean onlyTrailers) {
- if (!onlyTrailers) {
- // set metadata
- Metadata metadata = createDefaultMetadata();
- outboundTransportObserver().onMetadata(metadata, false);
- }
- // set trailers
- Metadata trailers = getTrailers(status);
- if (attachments != null) {
- convertAttachment(trailers, attachments);
- }
- outboundTransportObserver().onMetadata(trailers, true);
- if (LOGGER.isErrorEnabled()) {
- LOGGER.error("[Triple-Error] status=" + status.code.code
- + " method=" + getMethodName() + " onlyTrailers=" + onlyTrailers, status.cause);
- }
- }
-
- protected void transportError(GrpcStatus status) {
- transportError(status, null, false);
- }
-
- private String getGrpcMessage(GrpcStatus status) {
- if (StringUtils.isNotEmpty(status.description)) {
- return status.description;
- }
- if (status.cause != null) {
- return status.cause.getMessage();
- }
- return "unknown";
- }
-
- private Metadata getTrailers(GrpcStatus grpcStatus) {
- Metadata metadata = new DefaultMetadata();
- String grpcMessage = getGrpcMessage(grpcStatus);
- grpcMessage = GrpcStatus.encodeMessage(grpcMessage);
- metadata.put(TripleHeaderEnum.MESSAGE_KEY.getHeader(), grpcMessage);
- metadata.put(TripleHeaderEnum.STATUS_KEY.getHeader(), String.valueOf(grpcStatus.code.code));
- Status.Builder builder = Status.newBuilder()
- .setCode(grpcStatus.code.code)
- .setMessage(grpcMessage);
- Throwable throwable = grpcStatus.cause;
- if (throwable == null) {
- Status status = builder.build();
- metadata.put(TripleHeaderEnum.STATUS_DETAIL_KEY.getHeader(),
- encodeBase64ASCII(status.toByteArray()));
- return metadata;
- }
- DebugInfo debugInfo = DebugInfo.newBuilder()
- .addAllStackEntries(ExceptionUtils.getStackFrameList(throwable, 10))
- // can not use now
- // .setDetail(throwable.getMessage())
- .build();
- builder.addDetails(Any.pack(debugInfo));
- Status status = builder.build();
- metadata.put(TripleHeaderEnum.STATUS_DETAIL_KEY.getHeader(),
- encodeBase64ASCII(status.toByteArray()));
- return metadata;
- }
-
-
- /**
- * default header
- * <p>
- * only status and content-type
- */
- protected Metadata createDefaultMetadata() {
- Metadata metadata = new DefaultMetadata();
- metadata.put(Http2Headers.PseudoHeaderName.STATUS.value(), HttpResponseStatus.OK.codeAsText());
- metadata.put(HttpHeaderNames.CONTENT_TYPE, TripleConstant.CONTENT_PROTO);
- return metadata;
- }
-
- /**
- * Parse metadata to a KV pairs map.
- *
- * @param metadata the metadata from remote
- * @return KV pairs map
- */
- protected Map<String, Object> parseMetadataToAttachmentMap(Metadata metadata) {
- Map<String, Object> attachments = new HashMap<>();
- for (Map.Entry<CharSequence, CharSequence> header : metadata) {
- String key = header.getKey().toString();
- if (Http2Headers.PseudoHeaderName.isPseudoHeader(key)) {
- continue;
- }
- // avoid subsequent parse protocol header
- if (TripleHeaderEnum.containsExcludeAttachments(key)) {
- continue;
- }
- if (key.endsWith(TripleConstant.GRPC_BIN_SUFFIX) && key.length() > TripleConstant.GRPC_BIN_SUFFIX.length()) {
- try {
- attachments.put(key.substring(0, key.length() - TripleConstant.GRPC_BIN_SUFFIX.length()), decodeASCIIByte(header.getValue()));
- } catch (Exception e) {
- LOGGER.error("Failed to parse response attachment key=" + key, e);
- }
- } else {
- attachments.put(key, header.getValue().toString());
- }
- }
- return attachments;
- }
-
- /**
- * Parse and put the KV pairs into metadata. Ignore Http2 PseudoHeaderName and internal name.
- * Only raw byte array or string value will be put.
- *
- * @param metadata the metadata holder
- * @param attachments KV pairs
- */
- protected void convertAttachment(Metadata metadata, Map<String, Object> attachments) {
- if (attachments == null) {
- return;
- }
- for (Map.Entry<String, Object> entry : attachments.entrySet()) {
- final String key = entry.getKey().toLowerCase(Locale.ROOT);
- if (Http2Headers.PseudoHeaderName.isPseudoHeader(key)) {
- continue;
- }
- if (TripleHeaderEnum.containsExcludeAttachments(key)) {
- continue;
- }
- final Object v = entry.getValue();
- convertSingleAttachment(metadata, key, v);
- }
- }
-
- /**
- * Convert each user's attach value to metadata
- *
- * @param metadata {@link Metadata}
- * @param key metadata key
- * @param v metadata value (Metadata Only string and byte arrays are allowed)
- */
- private void convertSingleAttachment(Metadata metadata, String key, Object v) {
- try {
- if (v instanceof String) {
- String str = (String) v;
- metadata.put(key, str);
- } else if (v instanceof byte[]) {
- String str = encodeBase64ASCII((byte[]) v);
- metadata.put(key + TripleConstant.GRPC_BIN_SUFFIX, str);
- }
- } catch (Throwable t) {
- LOGGER.warn("Meet exception when convert single attachment key:" + key + " value=" + v, t);
- }
- }
-
- protected String convertHessianFromWrapper(String serializeType) {
- if (TripleConstant.HESSIAN4.equals(serializeType)) {
- return TripleConstant.HESSIAN2;
- }
- return serializeType;
- }
-
- protected <T> T unpack(byte[] data, Class<T> clz) {
- return unpack(new ByteArrayInputStream(data), clz);
- }
-
- protected <T> T unpack(InputStream is, Class<T> clz) {
- try {
- final T req = SingleProtobufUtils.deserialize(is, clz);
- return req;
- } catch (IOException e) {
- throw new RuntimeException("Failed to unpack req", e);
- } finally {
- closeQuietly(is);
- }
- }
-
- protected byte[] pack(Object obj) {
- final ByteArrayOutputStream baos = new ByteArrayOutputStream();
- try {
- SingleProtobufUtils.serialize(obj, baos);
- } catch (IOException e) {
- throw new RuntimeException("Failed to pack protobuf object", e);
- }
- return baos.toByteArray();
- }
-
-
- protected String encodeBase64ASCII(byte[] in) {
- byte[] bytes = encodeBase64(in);
- return new String(bytes, StandardCharsets.US_ASCII);
- }
-
- protected byte[] encodeBase64(byte[] in) {
- return BASE64_ENCODER.encode(in);
- }
-
- protected byte[] decodeASCIIByte(CharSequence value) {
- return BASE64_DECODER.decode(value.toString().getBytes(StandardCharsets.US_ASCII));
- }
-
- /**
- * 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
- */
- protected String convertHessianToWrapper(String serializeType) {
- if (TripleConstant.HESSIAN2.equals(serializeType)) {
- return TripleConstant.HESSIAN4;
- }
- return serializeType;
- }
-
- protected byte[] compress(byte[] data) {
- return this.getCompressor().compress(data);
- }
-
- protected byte[] decompress(byte[] data) {
- return this.getDeCompressor().decompress(data);
- }
-
-
-}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/CancelableStreamObserver.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/CancelableStreamObserver.java
index 7d107f9..3a059bc 100644
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/CancelableStreamObserver.java
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/CancelableStreamObserver.java
@@ -17,40 +17,19 @@
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.stream.StreamObserver;
import org.apache.dubbo.rpc.CancellationContext;
-import java.util.concurrent.atomic.AtomicBoolean;
-
public abstract class CancelableStreamObserver<T> implements StreamObserver<T> {
- private static final Logger LOGGER = LoggerFactory.getLogger(CancelableStreamObserver.class);
- private final AtomicBoolean contextSet = new AtomicBoolean(false);
private CancellationContext cancellationContext;
- public CancelableStreamObserver() {
- }
-
- public CancelableStreamObserver(CancellationContext cancellationContext) {
- setCancellationContext(cancellationContext);
+ public void setCancellationContext(CancellationContext cancellationContext) {
+ this.cancellationContext = cancellationContext;
}
- public final void setCancellationContext(CancellationContext cancellationContext) {
- if (contextSet.compareAndSet(false, true)) {
- this.cancellationContext = cancellationContext;
- } else {
- if (LOGGER.isWarnEnabled()) {
- LOGGER.warn("CancellationContext already set,do not repeat the set, ignore this set");
- }
- }
- }
-
- public final void cancel(Throwable throwable) {
- if (cancellationContext == null) {
- return;
- }
+ public void cancel(Throwable throwable) {
cancellationContext.cancel(throwable);
}
+
}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ClassLoadUtil.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ClassLoadUtil.java
index d4a790a..7a9ca0f 100644
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ClassLoadUtil.java
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ClassLoadUtil.java
@@ -14,6 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.dubbo.rpc.protocol.tri;
public class ClassLoadUtil {
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ClientOutboundTransportObserver.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ClientOutboundTransportObserver.java
deleted file mode 100644
index 672802b..0000000
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ClientOutboundTransportObserver.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * 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.command.CancelQueueCommand;
-import org.apache.dubbo.rpc.protocol.tri.command.DataQueueCommand;
-import org.apache.dubbo.rpc.protocol.tri.command.HeaderQueueCommand;
-
-import io.netty.channel.ChannelPromise;
-
-/**
- * Send stream data to remote
- * {@link ClientOutboundTransportObserver#promise} will be set success after rst or complete sent,
- */
-public class ClientOutboundTransportObserver extends OutboundTransportObserver {
-
- private final ChannelPromise promise;
-
- public ClientOutboundTransportObserver(WriteQueue writeQueue, ChannelPromise promise) {
- super(writeQueue);
- this.promise = promise;
- }
-
- @Override
- protected void doOnMetadata(Metadata metadata, boolean endStream) {
- writeQueue.enqueue(HeaderQueueCommand.createHeaders(metadata, endStream), true)
- .addListener(future -> {
- if (!future.isSuccess()) {
- promise.tryFailure(future.cause());
- }
- });
- }
-
- @Override
- protected void doOnData(byte[] data, boolean endStream) {
- writeQueue.enqueue(DataQueueCommand.createGrpcCommand(data, endStream, true), true)
- .addListener(future -> {
- if (!future.isSuccess()) {
- promise.tryFailure(future.cause());
- }
- });
- }
-
- @Override
- protected void doOnError(GrpcStatus status) {
- writeQueue.enqueue(CancelQueueCommand.createCommand(status), true)
- .addListener(future -> {
- if (future.isSuccess()) {
- promise.trySuccess();
- } else {
- promise.tryFailure(future.cause());
- }
- });
- }
-
- @Override
- protected void doOnComplete() {
- writeQueue.enqueue(DataQueueCommand.createGrpcCommand(true), true)
- .addListener(future -> {
- if (future.isSuccess()) {
- promise.trySuccess();
- } else {
- promise.tryFailure(future.cause());
- }
- });
- }
-}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ClientStream.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ClientStream.java
deleted file mode 100644
index 535be88..0000000
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ClientStream.java
+++ /dev/null
@@ -1,122 +0,0 @@
-/*
- * 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.stream.StreamObserver;
-import org.apache.dubbo.remoting.exchange.Response;
-import org.apache.dubbo.remoting.exchange.support.DefaultFuture2;
-import org.apache.dubbo.rpc.AppResponse;
-import org.apache.dubbo.rpc.CancellationContext;
-
-public class ClientStream extends AbstractClientStream implements Stream {
-
- protected ClientStream(URL url) {
- super(url);
- }
-
- @Override
- protected InboundTransportObserver createInboundTransportObserver() {
- return new ClientStreamInboundTransportObserverImpl();
- }
-
- @Override
- protected void doOnStartCall() {
- Response response = new Response(getRequestId(), TripleConstant.TRI_VERSION);
- AppResponse result = getMethodDescriptor().isServerStream() ? callServerStream() : callBiStream();
- response.setResult(result);
- DefaultFuture2.received(getConnection(), response);
- }
-
- private AppResponse callServerStream() {
- StreamObserver<Object> obServer = (StreamObserver<Object>) getRpcInvocation().getArguments()[1];
- obServer = attachCancelContext(obServer, getCancellationContext());
- subscribe(obServer);
- inboundMessageObserver().onNext(getRpcInvocation().getArguments()[0]);
- inboundMessageObserver().onCompleted();
- return new AppResponse();
- }
-
- private AppResponse callBiStream() {
- StreamObserver<Object> obServer = (StreamObserver<Object>) getRpcInvocation().getArguments()[0];
- obServer = attachCancelContext(obServer, getCancellationContext());
- subscribe(obServer);
- return new AppResponse(inboundMessageObserver());
- }
-
- private <T> StreamObserver<T> attachCancelContext(StreamObserver<T> observer, CancellationContext context) {
- if (observer instanceof CancelableStreamObserver) {
- CancelableStreamObserver<T> streamObserver = (CancelableStreamObserver<T>) observer;
- streamObserver.setCancellationContext(context);
- return streamObserver;
- }
- return observer;
- }
-
- private class ClientStreamInboundTransportObserverImpl extends InboundTransportObserver {
-
- private boolean error = false;
-
- @Override
- public void onData(byte[] data, boolean endStream) {
- execute(() -> {
- try {
- final Object resp = deserializeResponse(data);
- outboundMessageSubscriber().onNext(resp);
- } catch (Throwable throwable) {
- onError(throwable);
- }
- });
- }
-
- @Override
- public void onError(GrpcStatus status) {
- onError(status.asException());
- }
-
- @Override
- public void onComplete() {
- execute(() -> {
- getState().setServerEndStreamReceived();
- final Metadata trailers = getTrailers() == null ? getHeaders() : getTrailers();
- final GrpcStatus status = extractStatusFromMeta(trailers);
- if (GrpcStatus.Code.isOk(status.code.code)) {
- outboundMessageSubscriber().onCompleted();
- } else {
- final Throwable trailersException = getThrowableFromTrailers(trailers);
- if (trailersException != null) {
- onError(trailersException);
- } else {
- onError(status.cause);
- }
- }
- });
- }
-
- private void onError(Throwable throwable) {
- if (error) {
- return;
- }
- error = true;
- if (!getState().serverSendStreamReceived()) {
- cancel(throwable);
- }
- outboundMessageSubscriber().onError(throwable);
- }
- }
-}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ClientStreamObserver.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ClientStreamObserver.java
index 145551a..b28499a 100644
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ClientStreamObserver.java
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ClientStreamObserver.java
@@ -17,18 +17,18 @@
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 StreamObserver<T> {
+public interface ClientStreamObserver<T> extends CallStreamObserver<T> {
/**
- * 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}
+ * 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 setCompression(String compression);
-
+ void disableAutoRequest();
}
diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/DefaultFuture2.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/DefaultFuture2.java
similarity index 59%
rename from dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/DefaultFuture2.java
rename to dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/DefaultFuture2.java
index e9eb4f3..9c7e0ff 100644
--- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/DefaultFuture2.java
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/DefaultFuture2.java
@@ -14,7 +14,8 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.dubbo.remoting.exchange.support;
+
+package org.apache.dubbo.rpc.protocol.tri;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
@@ -28,8 +29,9 @@ import org.apache.dubbo.common.utils.NamedThreadFactory;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.TimeoutException;
import org.apache.dubbo.remoting.api.Connection;
-import org.apache.dubbo.remoting.exchange.Request;
-import org.apache.dubbo.remoting.exchange.Response;
+import org.apache.dubbo.remoting.exchange.support.DefaultFuture;
+import org.apache.dubbo.rpc.AppResponse;
+import org.apache.dubbo.rpc.Invocation;
import java.net.InetSocketAddress;
import java.text.SimpleDateFormat;
@@ -41,6 +43,7 @@ import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicLong;
/**
* DefaultFuture2.
@@ -50,39 +53,43 @@ import java.util.concurrent.TimeUnit;
*/
public class DefaultFuture2 extends CompletableFuture<Object> {
- private static final GlobalResourceInitializer<Timer> TIME_OUT_TIMER =
- new GlobalResourceInitializer<>(() -> new HashedWheelTimer(new NamedThreadFactory("dubbo-future-timeout", true),
- 30, TimeUnit.MILLISECONDS), DefaultFuture2::destroy);
+ private static final AtomicLong INVOKE_ID = new AtomicLong(0);
+
private static final Logger logger = LoggerFactory.getLogger(DefaultFuture2.class);
private static final Map<Long, DefaultFuture2> FUTURES = new ConcurrentHashMap<>();
- // invoke id.
- private final Request request;
+ public final long requestId;
+ private final Invocation invocation;
private final Connection connection;
private final int timeout;
private final long start = System.currentTimeMillis();
- private final List<Runnable> timeoutListeners = new ArrayList<>();
- private volatile long sent;
+ private final List<Runnable> timeoutListeners = new ArrayList<>(); private static final GlobalResourceInitializer<Timer> TIME_OUT_TIMER = new GlobalResourceInitializer<>(() -> new HashedWheelTimer(new NamedThreadFactory("dubbo-future-timeout", true), 30, TimeUnit.MILLISECONDS), DefaultFuture2::destroy);
private Timeout timeoutCheckTask;
+ private volatile long sent;
private ExecutorService executor;
-
- private DefaultFuture2(Connection client2, Request request, int timeout) {
- this.connection = client2;
- this.request = request;
+ private DefaultFuture2(Connection connection, Invocation invocation, int timeout) {
+ this.connection = connection;
+ this.invocation = invocation;
this.timeout = timeout;
+ this.requestId = INVOKE_ID.getAndIncrement();
// put into waiting map.
- FUTURES.put(request.getId(), this);
+ FUTURES.put(requestId, this);
}
public static void addTimeoutListener(long id, Runnable runnable) {
- DefaultFuture2 defaultFuture2 = FUTURES.get(id);
- defaultFuture2.addTimeoutListener(runnable);
+ DefaultFuture2 future = FUTURES.get(id);
+ if (future == null) {
+ // already time out
+ runnable.run();
+ } else {
+ future.addTimeoutListener(runnable);
+ }
}
/**
* check time out of the future
*/
private static void timeoutCheck(DefaultFuture2 future) {
- TimeoutCheckTask task = new TimeoutCheckTask(future.getId());
+ TimeoutCheckTask task = new TimeoutCheckTask(future.requestId);
future.timeoutCheckTask = TIME_OUT_TIMER.get().newTimeout(task, future.getTimeout(), TimeUnit.MILLISECONDS);
}
@@ -97,12 +104,12 @@ public class DefaultFuture2 extends CompletableFuture<Object> {
* 2.timeout check
*
* @param connection connection
- * @param request the request
+ * @param invocation the invocation
* @param timeout timeout
* @return a new DefaultFuture
*/
- public static DefaultFuture2 newFuture(Connection connection, Request request, int timeout, ExecutorService executor) {
- final DefaultFuture2 future = new DefaultFuture2(connection, request, timeout);
+ public static DefaultFuture2 newFuture(Connection connection, Invocation invocation, int timeout, ExecutorService executor) {
+ final DefaultFuture2 future = new DefaultFuture2(connection, invocation, timeout);
future.setExecutor(executor);
// ThreadlessExecutor needs to hold the waiting future in case of circuit return.
if (executor instanceof ThreadlessExecutor) {
@@ -117,32 +124,26 @@ public class DefaultFuture2 extends CompletableFuture<Object> {
return FUTURES.get(id);
}
- public static void sent(Request request) {
- DefaultFuture2 future = FUTURES.get(request.getId());
+ public static void sent(long requestId) {
+ DefaultFuture2 future = FUTURES.get(requestId);
if (future != null) {
future.doSent();
}
}
- public static void received(Connection connection, Response response) {
- received(connection, response, false);
- }
-
- public static void received(Connection connection, Response response, boolean timeout) {
- DefaultFuture2 future = FUTURES.remove(response.getId());
+ public static void received(long requestId, RpcStatus status, AppResponse appResponse) {
+ DefaultFuture2 future = FUTURES.remove(requestId);
if (future != null) {
Timeout t = future.timeoutCheckTask;
- if (!timeout) {
+ if (status.code != RpcStatus.Code.DEADLINE_EXCEEDED) {
// decrease Time
t.cancel();
}
- future.doReceived(response);
- } else {
- logger.warn("The timeout response finally returned at "
- + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date()))
- + ", response status is " + response.getStatus()
- + (connection == null ? "" : ", channel: " + connection.getChannel().localAddress()
- + " -> " + connection.getRemote()) + ", please check provider side for detailed result.");
+ if (future.executor != null) {
+ future.executor.execute(() -> future.doReceived(status, appResponse));
+ } else {
+ future.doReceived(status, appResponse);
+ }
}
}
@@ -164,11 +165,8 @@ public class DefaultFuture2 extends CompletableFuture<Object> {
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
- Response errorResult = new Response(request.getId());
- errorResult.setStatus(Response.CLIENT_ERROR);
- errorResult.setErrorMessage("request future has been canceled.");
- this.doReceived(errorResult);
- FUTURES.remove(request.getId());
+ doReceived(RpcStatus.CANCELLED, null);
+ FUTURES.remove(requestId);
timeoutCheckTask.cancel();
return true;
}
@@ -177,21 +175,19 @@ public class DefaultFuture2 extends CompletableFuture<Object> {
this.cancel(true);
}
- private void doReceived(Response res) {
- if (res == null) {
- throw new IllegalStateException("response cannot be null");
- }
- if (res.getStatus() == Response.OK) {
- this.complete(res.getResult());
- } else if (res.getStatus() == Response.CLIENT_TIMEOUT || res.getStatus() == Response.SERVER_TIMEOUT) {
- this.completeExceptionally(new TimeoutException(res.getStatus() == Response.SERVER_TIMEOUT, null, connection.getRemote(), res.getErrorMessage()));
+ private void doReceived(RpcStatus status, AppResponse appResponse) {
+ if (status.isOk()) {
+ this.complete(appResponse);
+ } else if (status.code == RpcStatus.Code.DEADLINE_EXCEEDED) {
+ this.completeExceptionally(new TimeoutException(isSent(), null, connection.getRemote(), "Request timeout"));
} else {
+ final InetSocketAddress local;
if (connection.getChannel() != null) {
- final InetSocketAddress local = (InetSocketAddress) connection.getChannel().localAddress();
- this.completeExceptionally(new RemotingException(local, connection.getRemote(), res.getErrorMessage()));
+ local = (InetSocketAddress) connection.getChannel().localAddress();
} else {
- this.completeExceptionally(new RemotingException(null, connection.getRemote(), res.getErrorMessage()));
+ local = null;
}
+ this.completeExceptionally(new RemotingException(local, connection.getRemote(), status.toMessage()));
}
// the result is returning, but the caller thread may still waiting
@@ -199,20 +195,11 @@ public class DefaultFuture2 extends CompletableFuture<Object> {
if (executor != null && executor instanceof ThreadlessExecutor) {
ThreadlessExecutor threadlessExecutor = (ThreadlessExecutor) executor;
if (threadlessExecutor.isWaiting()) {
- threadlessExecutor.notifyReturn(new IllegalStateException("The result has returned, but the biz thread is still waiting" +
- " which is not an expected state, interrupt the thread manually by returning an exception."));
+ threadlessExecutor.notifyReturn(new IllegalStateException("The result has returned, but the biz thread is still waiting" + " which is not an expected state, interrupt the thread manually by returning an exception."));
}
}
}
- private long getId() {
- return request.getId();
- }
-
- private Connection getConnection() {
- return connection;
- }
-
private boolean isSent() {
return sent > 0;
}
@@ -225,22 +212,13 @@ public class DefaultFuture2 extends CompletableFuture<Object> {
sent = System.currentTimeMillis();
}
- private String getTimeoutMessage(boolean scan) {
+ private String getTimeoutMessage() {
long nowTimestamp = System.currentTimeMillis();
- return (sent > 0 ? "Waiting server-side response timeout" : "Sending request timeout in client-side")
- + (scan ? " 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))) + ","
- + (sent > 0 ? " client elapsed: " + (sent - start)
- + " ms, server elapsed: " + (nowTimestamp - sent)
- : " elapsed: " + (nowTimestamp - start)) + " ms, timeout: "
- + timeout + " ms, request: " + (logger.isDebugEnabled() ? request : getRequestWithoutData()) + ", channel: " + connection.getChannel();
+ return (sent > 0 ? "Waiting server-side response timeout" : "Sending request timeout in client-side") + " 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))) + "," + (sent > 0 ? " client elapsed: " + (sent - start) + " ms, server elapsed: " + (nowTimestamp - sent) : " elapsed: " + (nowTimestamp - start)) + " ms, timeout: " + time [...]
}
- private Request getRequestWithoutData() {
- Request newRequest = request;
- newRequest.setData(null);
- return newRequest;
+ private String getRequestWithoutPayload() {
+ return "Request(id=" + requestId + ", service=" + invocation.getTargetServiceUniqueName() + ", method=" + invocation.getMethodName() + ")";
}
private static class TimeoutCheckTask implements TimerTask {
@@ -271,13 +249,12 @@ public class DefaultFuture2 extends CompletableFuture<Object> {
}
private void notifyTimeout(DefaultFuture2 future) {
- // create exception response.
- Response timeoutResponse = new Response(future.getId());
- // set timeout status.
- timeoutResponse.setStatus(future.isSent() ? Response.SERVER_TIMEOUT : Response.CLIENT_TIMEOUT);
- timeoutResponse.setErrorMessage(future.getTimeoutMessage(true));
- // handle response.
- DefaultFuture2.received(future.getConnection(), timeoutResponse, true);
+ final RpcStatus status = RpcStatus.DEADLINE_EXCEEDED.withDescription(future.getTimeoutMessage());
+ DefaultFuture2.received(future.requestId, status, null);
}
}
+
+
+
+
}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/DefaultMetadata.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/DefaultMetadata.java
deleted file mode 100644
index c05ff36..0000000
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/DefaultMetadata.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * 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.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Spliterator;
-import java.util.function.Consumer;
-
-public class DefaultMetadata implements Metadata {
- private final Map<CharSequence, CharSequence> innerMap = new HashMap<>();
-
- @Override
- public CharSequence get(CharSequence key) {
- return innerMap.get(key);
- }
-
- @Override
- public Metadata put(CharSequence key, CharSequence value) {
- innerMap.put(key, value);
- return this;
- }
-
- @Override
- public Iterator<Map.Entry<CharSequence, CharSequence>> iterator() {
- return innerMap.entrySet().iterator();
- }
-
- @Override
- public void forEach(Consumer<? super Map.Entry<CharSequence, CharSequence>> action) {
- innerMap.entrySet().forEach(action);
- }
-
- @Override
- public Spliterator<Map.Entry<CharSequence, CharSequence>> spliterator() {
- return innerMap.entrySet().spliterator();
- }
-
- @Override
- public boolean contains(CharSequence key) {
- return innerMap.containsKey(key);
- }
-
- @Override
- public boolean remove(CharSequence key) {
- innerMap.remove(key);
- return true;
- }
-
-}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/GrpcDataDecoder.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/GrpcDataDecoder.java
deleted file mode 100644
index 4e1e5c3..0000000
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/GrpcDataDecoder.java
+++ /dev/null
@@ -1,114 +0,0 @@
-/*
- * 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 io.netty.buffer.ByteBuf;
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.handler.codec.ReplayingDecoder;
-
-import java.util.List;
-
-public class GrpcDataDecoder extends ReplayingDecoder<GrpcDataDecoder.GrpcDecodeState> {
- private static final Logger LOGGER = LoggerFactory.getLogger(GrpcDataDecoder.class);
- private static final int RESERVED_MASK = 0xFE;
- private static final int COMPRESSED_FLAG_MASK = 1;
- private final int maxDataSize;
- private final boolean client;
- private int len;
- private boolean compressedFlag;
-
- public GrpcDataDecoder(int maxDataSize, boolean client) {
- super(GrpcDecodeState.HEADER);
- this.maxDataSize = maxDataSize;
- this.client = client;
- }
-
- @Override
- public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
- if (LOGGER.isErrorEnabled()) {
- LOGGER.error("Grpc data read error ", cause);
- }
- ctx.close();
- }
-
- @Override
- protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
- switch (state()) {
- case HEADER:
- int type = in.readByte();
- if ((type & RESERVED_MASK) != 0) {
- throw GrpcStatus.fromCode(GrpcStatus.Code.INTERNAL)
- .withDescription("gRPC frame header malformed: reserved bits not zero")
- .asException();
- }
- compressedFlag = (type & COMPRESSED_FLAG_MASK) != 0;
-
- len = in.readInt();
- if (len < 0 || len > maxDataSize) {
- throw GrpcStatus.fromCode(GrpcStatus.Code.RESOURCE_EXHAUSTED)
- .withDescription(String.format("gRPC message exceeds maximum size %d: %d",
- maxDataSize, len))
- .asException();
- }
- checkpoint(GrpcDecodeState.PAYLOAD);
- case PAYLOAD:
- byte[] dst = new byte[len];
- in.readBytes(dst);
- out.add(this.decompressData(dst, ctx));
- checkpoint(GrpcDecodeState.HEADER);
- break;
- default:
- throw new RuntimeException("Should not reach here");
- }
- }
-
- private byte[] decompressData(byte[] data, ChannelHandlerContext ctx) {
- if (!compressedFlag) {
- return data;
- }
- Compressor compressor = getDeCompressor(ctx, client);
- if (null == compressor) {
- throw GrpcStatus.fromCode(GrpcStatus.Code.UNIMPLEMENTED)
- .withDescription("gRPC message compressor not found")
- .asException();
- }
- return compressor.decompress(data);
- }
-
- private Compressor getDeCompressor(ChannelHandlerContext ctx, boolean client) {
- AbstractStream stream = client ? getClientStream(ctx) : getServerStream(ctx);
- return stream.getDeCompressor();
- }
-
- private AbstractClientStream getClientStream(ChannelHandlerContext ctx) {
- return ctx.channel().attr(TripleConstant.CLIENT_STREAM_KEY).get();
- }
-
- private AbstractServerStream getServerStream(ChannelHandlerContext ctx) {
- return ctx.channel().attr(TripleConstant.SERVER_STREAM_KEY).get();
- }
-
- enum GrpcDecodeState {
- HEADER,
- PAYLOAD
- }
-
-
-}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/Http2HeaderMeta.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/Http2HeaderMeta.java
deleted file mode 100644
index 24ef489..0000000
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/Http2HeaderMeta.java
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * 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.handler.codec.http2.Http2Headers;
-
-import java.util.Iterator;
-import java.util.Map;
-
-public class Http2HeaderMeta implements Metadata {
- private final Http2Headers headers;
-
- public Http2HeaderMeta(Http2Headers headers) {
- this.headers = headers;
- }
-
- @Override
- public Metadata put(CharSequence key, CharSequence value) {
- headers.set(key, value);
- return this;
- }
-
- @Override
- public CharSequence get(CharSequence key) {
- return headers.get(key);
- }
-
- @Override
- public boolean contains(CharSequence key) {
- return headers.contains(key);
- }
-
- @Override
- public boolean remove(CharSequence key) {
- return headers.remove(key);
- }
-
- @Override
- public Iterator<Map.Entry<CharSequence, CharSequence>> iterator() {
- return headers.iterator();
- }
-}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/InboundTransportObserver.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/InboundTransportObserver.java
deleted file mode 100644
index 911dffa..0000000
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/InboundTransportObserver.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * 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.GrpcStatus.Code;
-
-public abstract class InboundTransportObserver implements TransportObserver {
- private Metadata headers;
- private Metadata trailers;
-
- public Metadata getHeaders() {
- return headers;
- }
-
- public Metadata getTrailers() {
- return trailers;
- }
-
- @Override
- public void onMetadata(Metadata metadata, boolean endStream) {
- if (headers == null) {
- headers = metadata;
- } else {
- trailers = metadata;
- }
- }
-
- protected GrpcStatus extractStatusFromMeta(Metadata metadata) {
- if (!metadata.contains(TripleHeaderEnum.STATUS_KEY.getHeader())) {
- return GrpcStatus.fromCode(Code.OK);
- }
- final int code = Integer.parseInt(metadata.get(TripleHeaderEnum.STATUS_KEY.getHeader()).toString());
-
- if (Code.isOk(code)) {
- return GrpcStatus.fromCode(Code.OK);
- }
- GrpcStatus status = GrpcStatus.fromCode(code);
- if (!metadata.contains(TripleHeaderEnum.MESSAGE_KEY.getHeader())) {
- return status;
- }
- final String raw = metadata.get(TripleHeaderEnum.MESSAGE_KEY.getHeader()).toString();
- status = status.withDescription(GrpcStatus.decodeMessage(raw));
- return status;
- }
-}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/OutboundTransportObserver.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/OutboundTransportObserver.java
deleted file mode 100644
index bd7a570..0000000
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/OutboundTransportObserver.java
+++ /dev/null
@@ -1,101 +0,0 @@
-/*
- * 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;
-
-/**
- * Provides loosely state management for write message to outbound.
- */
-public abstract class OutboundTransportObserver implements TransportObserver {
-
- protected final TransportState state = new TransportState();
- protected final WriteQueue writeQueue;
-
- public OutboundTransportObserver(WriteQueue writeQueue) {
- this.writeQueue = writeQueue;
- }
-
- @Override
- public void onMetadata(Metadata metadata, boolean endStream) {
- checkSendMeta(metadata, endStream);
- doOnMetadata(metadata, endStream);
- }
-
- protected void checkSendMeta(Object metadata, boolean endStream) {
- if (endStream) {
- // trailers-only or metadata + trailers
- if (!state.allowSendEndStream()) {
- throw new IllegalStateException("Metadata endStream already sent to peer, send " + metadata + " failed!");
- }
- state.setMetaSend();
- state.setEndStreamSend();
- } else {
- // metadata
- if (!state.allowSendMeta()) {
- throw new IllegalStateException("Metadata already sent to peer, send " + metadata + " failed!");
- }
- state.setMetaSend();
- }
- }
-
- @Override
- public void onData(byte[] data, boolean endStream) {
- checkSendData(endStream);
- doOnData(data, endStream);
- }
-
-
- protected void checkSendData(boolean endStream) {
- if (!state.allowSendData()) {
- throw new IllegalStateException("data has not sent to peer!");
- }
- if (endStream) {
- state.setEndStreamSend();
- }
- }
-
- @Override
- public void onError(GrpcStatus status) {
- if (!state.allowSendReset()) {
- throw new IllegalStateException("Duplicated rst!");
- }
- state.setResetSend();
- doOnError(status);
- }
-
- @Override
- public void onComplete() {
- if (!state.allowSendEndStream()) {
- throw new IllegalStateException("Stream already closed!");
- }
- state.setEndStreamSend();
- doOnComplete();
- }
-
-
- protected abstract void doOnMetadata(Metadata metadata, boolean endStream);
-
- protected abstract void doOnData(byte[] data, boolean endStream);
-
- protected abstract void doOnError(GrpcStatus status);
-
- protected abstract void doOnComplete();
-
-}
-
-
-
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/PathResolver.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/PathResolver.java
index 54f8415..ba1abca 100644
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/PathResolver.java
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/PathResolver.java
@@ -14,6 +14,7 @@
* 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;
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/Metadata.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/RequestMetadata.java
similarity index 52%
copy from dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/Metadata.java
copy to dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/RequestMetadata.java
index f7c49f7..1e18566 100644
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/Metadata.java
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/RequestMetadata.java
@@ -17,29 +17,29 @@
package org.apache.dubbo.rpc.protocol.tri;
-import java.util.Map;
-import java.util.Optional;
-
-public interface Metadata extends Iterable<Map.Entry<CharSequence, CharSequence>> {
-
- Metadata put(CharSequence key, CharSequence value);
-
- default Metadata putIfNotNull(CharSequence key, CharSequence value) {
- if (value != null) {
- put(key, value);
- }
- return this;
- }
+import org.apache.dubbo.rpc.model.MethodDescriptor;
+import org.apache.dubbo.rpc.protocol.tri.compressor.Compressor;
+import org.apache.dubbo.rpc.protocol.tri.pack.GenericPack;
+import org.apache.dubbo.rpc.protocol.tri.pack.GenericUnpack;
- CharSequence get(CharSequence key);
+import io.netty.util.AsciiString;
+import java.util.Map;
- default CharSequence getOrDefault(CharSequence key, CharSequence val) {
- return Optional.ofNullable(get(key)).orElse(val);
- }
-
- boolean contains(CharSequence key);
-
- boolean remove(CharSequence key);
-
+public class RequestMetadata {
+ public long requestId;
+ 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 MethodDescriptor method;
+ public Object[] arguments;
+ public Map<String, Object> attachments;
+ public GenericPack genericPack;
+ public GenericUnpack genericUnpack;
}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/GrpcStatus.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/RpcStatus.java
similarity index 61%
rename from dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/GrpcStatus.java
rename to dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/RpcStatus.java
index 1ae5be5..4ba77c7 100644
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/GrpcStatus.java
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/RpcStatus.java
@@ -14,13 +14,14 @@
* 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.StringUtils;
import org.apache.dubbo.remoting.TimeoutException;
-import org.apache.dubbo.remoting.exchange.Response;
import org.apache.dubbo.rpc.RpcException;
+import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.QueryStringDecoder;
import io.netty.handler.codec.http.QueryStringEncoder;
@@ -31,87 +32,55 @@ 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.protocol.tri.GrpcStatus.Code.UNAVAILABLE;
/**
* See https://github.com/grpc/grpc/blob/master/doc/statuscodes.md
*/
-public class GrpcStatus {
+public class RpcStatus {
+ public static final RpcStatus OK = fromCode(Code.OK);
+ public static final RpcStatus UNKNOWN = fromCode(Code.UNKNOWN);
+ public static final RpcStatus INTERNAL = fromCode(Code.INTERNAL);
+ public static final RpcStatus CANCELLED = fromCode(Code.CANCELLED);
+ public static final RpcStatus UNAVAILABLE = fromCode(Code.UNAVAILABLE);
+ public static final RpcStatus UNIMPLEMENTED = fromCode(Code.UNIMPLEMENTED);
+ public static final RpcStatus DEADLINE_EXCEEDED = fromCode(Code.DEADLINE_EXCEEDED);
+
public final Code code;
- public Throwable cause;
- public String description;
+ public final Throwable cause;
+ public final String description;
- public GrpcStatus(Code code, Throwable cause, String description) {
+ public RpcStatus(Code code, Throwable cause, String description) {
this.code = code;
this.cause = cause;
this.description = description;
}
- public static GrpcStatus fromCode(int code) {
+ public static RpcStatus fromCode(int code) {
return fromCode(Code.fromCode(code));
}
- public static GrpcStatus fromCode(Code code) {
- return new GrpcStatus(code, null, null);
- }
-
- public static GrpcStatus fromCodeWithDescription(Code code, String description) {
- return new GrpcStatus(code, null, description);
- }
-
- public static byte toDubboStatus(Code code) {
- byte status;
- switch (code) {
- case OK:
- status = Response.OK;
- break;
- case UNKNOWN:
- status = Response.SERVICE_ERROR;
- break;
- case DEADLINE_EXCEEDED:
- status = Response.SERVER_TIMEOUT;
- break;
- case RESOURCE_EXHAUSTED:
- status = Response.SERVER_THREADPOOL_EXHAUSTED_ERROR;
- break;
- case UNIMPLEMENTED:
- status = Response.SERVICE_NOT_FOUND;
- break;
- case INVALID_ARGUMENT:
- status = Response.BAD_REQUEST;
- break;
- case INTERNAL:
- status = Response.SERVER_ERROR;
- break;
- case UNAVAILABLE:
- case DATA_LOSS:
- status = Response.CHANNEL_INACTIVE;
- break;
- default:
- status = Response.CLIENT_ERROR;
- break;
- }
- return status;
+ public static RpcStatus fromCode(Code code) {
+ return new RpcStatus(code, null, null);
}
/**
* todo The remaining exceptions are converted to status
*/
- public static GrpcStatus getStatus(Throwable throwable) {
+ public static RpcStatus getStatus(Throwable throwable) {
return getStatus(throwable, null);
}
- public static GrpcStatus getStatus(Throwable throwable, String description) {
+ public static RpcStatus getStatus(Throwable throwable, String description) {
if (throwable instanceof RpcException) {
RpcException rpcException = (RpcException) throwable;
Code code = rpcExceptionCodeToGrpcCode(rpcException.getCode());
- return new GrpcStatus(code, throwable, description);
+ return new RpcStatus(code, throwable, description);
}
if (throwable instanceof TimeoutException) {
- return new GrpcStatus(GrpcStatus.Code.DEADLINE_EXCEEDED, throwable, description);
+ return new RpcStatus(RpcStatus.Code.DEADLINE_EXCEEDED, throwable, description);
}
- return new GrpcStatus(Code.UNKNOWN, throwable, description);
+ return new RpcStatus(Code.UNKNOWN, throwable, description);
}
public static Code rpcExceptionCodeToGrpcCode(int rpcExceptionCode) {
@@ -126,7 +95,7 @@ public class GrpcStatus {
break;
case LIMIT_EXCEEDED_EXCEPTION:
case NETWORK_EXCEPTION:
- code = UNAVAILABLE;
+ code = Code.UNAVAILABLE;
break;
case METHOD_NOT_FOUND:
code = Code.NOT_FOUND;
@@ -156,7 +125,6 @@ public class GrpcStatus {
return QueryStringDecoder.decodeComponent(raw);
}
-
public static String encodeMessage(String raw) {
if (StringUtils.isEmpty(raw)) {
return "";
@@ -164,43 +132,79 @@ public class GrpcStatus {
return encodeComponent(raw);
}
- public GrpcStatus withCause(Throwable cause) {
- this.cause = cause;
- return this;
+ private static String encodeComponent(String raw) {
+ QueryStringEncoder encoder = new QueryStringEncoder("");
+ encoder.addParam("", raw);
+ // ?=
+ return encoder.toString().substring(2);
}
- public GrpcStatus withDescription(String description) {
- this.description = description;
- return this;
+ public static RpcStatus.Code httpStatusToGrpcCode(int httpStatusCode) {
+ if (httpStatusCode >= 100 && httpStatusCode < 200) {
+ return RpcStatus.Code.INTERNAL;
+ }
+ if (httpStatusCode == HttpResponseStatus.BAD_REQUEST.code() ||
+ httpStatusCode == HttpResponseStatus.REQUEST_HEADER_FIELDS_TOO_LARGE.code()
+ ) {
+ return RpcStatus.Code.INTERNAL;
+ } else if (httpStatusCode == HttpResponseStatus.UNAUTHORIZED.code()) {
+ return RpcStatus.Code.UNAUTHENTICATED;
+ } else if (httpStatusCode == HttpResponseStatus.FORBIDDEN.code()) {
+ return RpcStatus.Code.PERMISSION_DENIED;
+ } else if (httpStatusCode == HttpResponseStatus.NOT_FOUND.code()) {
+ return RpcStatus.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 RpcStatus.Code.UNKNOWN;
+ }
+ }
+
+ public boolean isOk() {
+ return Code.isOk(code.code);
+ }
+
+ public RpcStatus withCause(Throwable cause) {
+ return new RpcStatus(this.code, cause, this.description);
+ }
+
+ public RpcStatus withDescription(String description) {
+ return new RpcStatus(code, cause, description);
+ }
+
+ public RpcStatus appendDescription(String description) {
+ if (this.description == null) {
+ return withDescription(description);
+ } else {
+ String newDescription = this.description + "\n" + description;
+ return withDescription(newDescription);
+ }
}
public RpcException asException() {
return new RpcException(this.code.code, this.description, this.cause);
}
+ public String toEncodedMessage() {
+ String output = limitSizeTo4KB(toMessage());
+ return encodeComponent(output);
+ }
+
public String toMessage() {
- final String msg;
+ String msg = "";
if (cause == null) {
- msg = description;
+ msg += description;
} else {
String placeHolder = description == null ? "" : description;
- msg = StringUtils.toString(placeHolder, cause);
- }
- if (msg == null) {
- return "";
+ msg += StringUtils.toString(placeHolder, cause);
}
- String output = limitSizeTo4KB(msg);
- return encodeComponent(output);
+ return msg;
}
- private static String encodeComponent(String raw) {
- QueryStringEncoder encoder = new QueryStringEncoder("");
- encoder.addParam("", raw);
- // ?=
- return encoder.toString().substring(2);
- }
-
public enum Code {
OK(0),
CANCELLED(1),
@@ -224,7 +228,7 @@ public class GrpcStatus {
*/
UNAUTHENTICATED(16);
- final int code;
+ public final int code;
Code(int code) {
this.code = code;
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ServerOutboundTransportObserver.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ServerOutboundTransportObserver.java
deleted file mode 100644
index 584be8d..0000000
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ServerOutboundTransportObserver.java
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
- * 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.rpc.protocol.tri.command.CancelQueueCommand;
-import org.apache.dubbo.rpc.protocol.tri.command.DataQueueCommand;
-import org.apache.dubbo.rpc.protocol.tri.command.HeaderQueueCommand;
-
-import io.netty.handler.codec.http2.DefaultHttp2Headers;
-import io.netty.handler.codec.http2.Http2Headers;
-
-public class ServerOutboundTransportObserver extends OutboundTransportObserver {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(ServerOutboundTransportObserver.class);
-
- public ServerOutboundTransportObserver(WriteQueue queue) {
- super(queue);
- }
-
- public void onMetadata(Http2Headers headers, boolean endStream) {
- checkSendMeta(headers, endStream);
- writeQueue.enqueue(HeaderQueueCommand.createHeaders(headers, endStream), true)
- .addListener(future -> {
- if (!future.isSuccess()) {
- LOGGER.warn("send header error endStream=" + endStream, future.cause());
- }
- });
- }
-
- @Override
- public void onMetadata(Metadata metadata, boolean endStream) {
- doOnMetadata(metadata, endStream);
- }
-
- @Override
- public void onData(byte[] data, boolean endStream) {
- doOnData(data, endStream);
- }
-
- @Override
- protected void doOnMetadata(Metadata metadata, boolean endStream) {
- final DefaultHttp2Headers headers = new DefaultHttp2Headers(true);
- metadata.forEach(e -> headers.set(e.getKey(), e.getValue()));
- onMetadata(headers, endStream);
- }
-
- @Override
- protected void doOnData(byte[] data, boolean endStream) {
- writeQueue.enqueue(DataQueueCommand.createGrpcCommand(data, endStream, false), true)
- .addListener(future -> {
- if (!future.isSuccess()) {
- LOGGER.warn("send data error endStream=" + endStream, future.cause());
- }
- });
- }
-
- @Override
- protected void doOnError(GrpcStatus status) {
- writeQueue.enqueue(CancelQueueCommand.createCommand(status), true)
- .addListener(future -> {
- if (!future.isSuccess()) {
- LOGGER.warn("write reset error", future.cause());
- }
- });
- }
-
- @Override
- protected void doOnComplete() {
-
- }
-}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ServerStream.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ServerStream.java
deleted file mode 100644
index f5ff7c9..0000000
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ServerStream.java
+++ /dev/null
@@ -1,210 +0,0 @@
-/*
- * 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.stream.StreamObserver;
-import org.apache.dubbo.rpc.Result;
-import org.apache.dubbo.rpc.RpcContext;
-import org.apache.dubbo.rpc.RpcInvocation;
-
-public class ServerStream extends AbstractServerStream implements Stream {
- protected ServerStream(URL url) {
- super(url);
- }
-
- @Override
- protected StreamObserver<Object> createStreamObserver() {
- return new ServerStreamObserverImpl();
- }
-
- @Override
- protected InboundTransportObserver createInboundTransportObserver() {
- return new ServerStreamInboundTransportObserver();
- }
-
- private class ServerStreamObserverImpl implements ServerStreamObserver<Object> {
-
- @Override
- public void onNext(Object data) {
- if (getState().allowSendMeta()) {
- outboundTransportObserver().onMetadata(createResponseMeta(), false);
- }
- final byte[] bytes = encodeResponse(data);
- if (bytes == null) {
- return;
- }
- if (getState().allowSendData()) {
- outboundTransportObserver().onData(bytes, false);
- }
- }
-
- @Override
- public void onError(Throwable throwable) {
- if (!getState().allowSendEndStream()) {
- return;
- }
- final GrpcStatus status = GrpcStatus.fromCode(GrpcStatus.Code.INTERNAL)
- .withCause(throwable)
- .withDescription("Biz exception");
- transportError(status);
- }
-
- @Override
- public void onCompleted() {
- if (!getState().allowSendEndStream()) {
- return;
- }
- outboundTransportObserver().onMetadata(TripleConstant.SUCCESS_RESPONSE_META, true);
- }
-
- @Override
- public void setCompression(String compression) {
- if (!getState().allowSendMeta()) {
- final GrpcStatus status = GrpcStatus.fromCode(GrpcStatus.Code.INTERNAL)
- .withDescription("Metadata already has been sent,can not set compression");
- transportError(status);
- return;
- }
- Compressor compressor = Compressor.getCompressor(getUrl().getOrDefaultFrameworkModel(), compression);
- setCompressor(compressor);
- }
- }
-
- private class ServerStreamInboundTransportObserver extends InboundTransportObserver implements TransportObserver {
-
- /**
- * for server stream the method only save header
- * <p>
- * for bi stream run api impl code and put observer to streamSubscriber
- *
- * <pre class="code">
- * public StreamObserver<GreeterRequest> biStream(StreamObserver<GreeterReply> replyStream) {
- * // happen on this
- * // you can add cancel listener on use {@link RpcContext#getCancellationContext()}
- * return new StreamObserver<GreeterRequest>() {
- * // ...
- * };
- * }
- * </pre>
- */
- @Override
- public void onMetadata(Metadata metadata, boolean endStream) {
- super.onMetadata(metadata, endStream);
- if (getMethodDescriptor().isServerStream()) {
- return;
- }
- execute(() -> {
- try {
- RpcContext.restoreCancellationContext(getCancellationContext());
- final RpcInvocation inv = buildInvocation(metadata);
- inv.setArguments(new Object[]{inboundMessageObserver()});
- final Result result = getInvoker().invoke(inv);
- if (result.hasException()) {
- transportError(GrpcStatus.getStatus(result.getException()));
- return;
- }
- try {
- subscribe((StreamObserver<Object>) result.getValue());
- } catch (Throwable t) {
- transportError(GrpcStatus.fromCode(GrpcStatus.Code.INTERNAL)
- .withDescription("Failed to create server's observer"));
- }
- } finally {
- RpcContext.removeCancellationContext();
- }
- });
-
- }
-
- @Override
- public void onData(byte[] in, boolean endStream) {
- execute(() -> {
- try {
- if (getMethodDescriptor().isServerStream()) {
- serverStreamOnData(in);
- return;
- }
- biStreamOnData(in);
- } catch (Throwable t) {
- transportError(GrpcStatus.fromCode(GrpcStatus.Code.INTERNAL)
- .withDescription("Deserialize request failed")
- .withCause(t));
- }
- });
- }
-
- /**
- * This method should not be called for a while
- */
- @Override
- public void onError(GrpcStatus status) {
- }
-
- /**
- * call observer onNext
- */
- private void biStreamOnData(byte[] in) {
- final Object[] arguments = deserializeRequest(in);
- if (arguments != null) {
- outboundMessageSubscriber().onNext(arguments[0]);
- }
- }
-
- /**
- * call api impl code
- *
- * <pre class="code">
- * public void cancelServerStream(GreeterRequest request, StreamObserver<GreeterReply> replyStream) {
- * // happen on this
- * // you can add cancel listener on use {@link RpcContext#getCancellationContext()}
- * // if you want listener cancel,plz do not call onCompleted()
- * }
- * </pre>
- */
- private void serverStreamOnData(byte[] in) {
- try {
- RpcContext.restoreCancellationContext(getCancellationContext());
- RpcInvocation inv = buildInvocation(getHeaders());
- final Object[] arguments = deserializeRequest(in);
- if (arguments != null) {
- inv.setArguments(new Object[]{arguments[0], inboundMessageObserver()});
- final Result result = getInvoker().invoke(inv);
- if (result.hasException()) {
- transportError(GrpcStatus.getStatus(result.getException()));
- }
- }
- } finally {
- RpcContext.removeCancellationContext();
- }
- }
-
- /**
- * for server stream the method do nothing
- * <p>
- * for bi stream call onCompleted
- */
- @Override
- public void onComplete() {
- if (getMethodDescriptor().isServerStream()) {
- return;
- }
- execute(() -> outboundMessageSubscriber().onCompleted());
- }
- }
-}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ServerStreamObserver.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ServerStreamObserver.java
index 9aaba38..3ca3f1d 100644
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ServerStreamObserver.java
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ServerStreamObserver.java
@@ -17,18 +17,11 @@
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 ServerStreamObserver<T> extends StreamObserver<T> {
+public interface ServerStreamObserver<T> extends CallStreamObserver<T> {
- /**
- * 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);
+ void disableAutoInboundFlowControl();
}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/SingleProtobufUtils.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/SingleProtobufUtils.java
index ab73a52..0c9aeeb 100644
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/SingleProtobufUtils.java
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/SingleProtobufUtils.java
@@ -14,6 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.dubbo.rpc.protocol.tri;
import com.google.protobuf.BoolValue;
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/Stream.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/Stream.java
deleted file mode 100644
index 890c299..0000000
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/Stream.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * 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.stream.StreamObserver;
-
-/**
- * Stream acts as a bi-directional intermediate layer for processing streaming data . It serializes object instance to
- * byte[] then send to remote, and deserializes byte[] to object instance from remote. {@link #inboundTransportObserver()}
- * and {@link #subscribe(OutboundTransportObserver)} provide {@link TransportObserver} to receive or send remote data.
- * {@link #inboundMessageObserver()} and {@link #subscribe(StreamObserver)} provide {@link StreamObserver}
- * as API for users fetching/emitting objects from/to remote peer.
- */
-public interface Stream {
-
- Logger LOGGER = LoggerFactory.getLogger(Stream.class);
-
- /**
- * Register an upstream data observer to receive byte[] sent by this stream
- *
- * @param observer receives remote byte[] data
- */
- void subscribe(OutboundTransportObserver observer);
-
- /**
- * Get a downstream data observer for writing byte[] data to this stream
- *
- * @return an observer for writing byte[] to remote peer
- */
- TransportObserver inboundTransportObserver();
-
- /**
- * Register an upstream data observer to receive instance sent by this stream
- *
- * @param outboundMessageObserver receives remote byte[] data
- */
- void subscribe(StreamObserver<Object> outboundMessageObserver);
-
- /**
- * Get a downstream data observer for transmitting instances to application code
- *
- * @return an observer for writing byte[] to remote peer
- */
- StreamObserver<Object> inboundMessageObserver();
-
- /**
- * Execute a task in stream's executor
- *
- * @param runnable task to run
- */
- void execute(Runnable runnable);
-
-}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TransportState.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TransportState.java
deleted file mode 100644
index f4b9357..0000000
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TransportState.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * 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;
-
-/**
- * A state for recording stream
- * A normal state transition :
- * Meta -> (EndStream) -> Data -> (EndStream) -> (Rst)
- */
-public class TransportState {
-
- private static final int META_SEND = 0b00000000000000000000000000000001;
- private static final int RESET_SEND = 0b00000000000000000000000000000010;
- private static final int END_STREAM_SEND = 0b00000000000000000000000000000100;
- private static final int SERVER_SEND_STREAM_RECEIVED = 0b00000000000000000000000000001000;
- private static final int ALLOW_META_SEND = 0b00000000000000000000000000000000;
- private static final int ALLOW_DATA_SEND = META_SEND;
- private volatile int state = 0;
-
- public void setMetaSend() {
- this.state = this.state | META_SEND;
- }
-
- public void setResetSend() {
- this.state = this.state | RESET_SEND;
- }
-
- public void setEndStreamSend() {
- this.state = this.state | END_STREAM_SEND;
- }
-
- public void setServerEndStreamReceived() {
- this.state = this.state | SERVER_SEND_STREAM_RECEIVED;
- }
-
- public boolean serverSendStreamReceived() {
- return (this.state & SERVER_SEND_STREAM_RECEIVED) > 0;
- }
-
- public boolean allowSendMeta() {
- return this.state == ALLOW_META_SEND;
- }
-
- public boolean allowSendReset() {
- return (this.state & RESET_SEND) != RESET_SEND;
- }
-
- public boolean allowSendData() {
- return this.state == ALLOW_DATA_SEND;
- }
-
- public boolean allowSendEndStream() {
- return allowSendReset() && (this.state & END_STREAM_SEND) != END_STREAM_SEND;
- }
-
-}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleClientRequestHandler.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleClientRequestHandler.java
deleted file mode 100644
index 187db26..0000000
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleClientRequestHandler.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * 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.Connection;
-import org.apache.dubbo.remoting.exchange.Request;
-import org.apache.dubbo.remoting.exchange.support.DefaultFuture2;
-import org.apache.dubbo.rpc.model.FrameworkModel;
-
-import io.netty.channel.ChannelDuplexHandler;
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.channel.ChannelPromise;
-import io.netty.handler.codec.http2.Http2StreamChannel;
-import io.netty.handler.codec.http2.Http2StreamChannelBootstrap;
-
-public class TripleClientRequestHandler extends ChannelDuplexHandler {
-
- private final FrameworkModel frameworkModel;
-
- public TripleClientRequestHandler(FrameworkModel frameworkModel) {
- this.frameworkModel = frameworkModel;
- }
-
- @Override
- public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
- if (!(msg instanceof Request)) {
- super.write(ctx, msg, promise);
- return;
- }
- final Request req = (Request) msg;
- Connection connection = Connection.getConnectionFromChannel(ctx.channel());
- final AbstractClientStream stream = AbstractClientStream.newClientStream(req, connection);
- final Http2StreamChannelBootstrap streamChannelBootstrap = new Http2StreamChannelBootstrap(ctx.channel());
- streamChannelBootstrap.open()
- .addListener(future -> {
- if (future.isSuccess()) {
- final Http2StreamChannel channel = (Http2StreamChannel) future.get();
- channel.pipeline()
- .addLast(new TripleCommandOutBoundHandler())
- .addLast(new TripleHttp2ClientResponseHandler())
- .addLast(new GrpcDataDecoder(Integer.MAX_VALUE, true))
- .addLast(new TripleClientInboundHandler());
- channel.attr(TripleConstant.CLIENT_STREAM_KEY).set(stream);
- DefaultFuture2.addTimeoutListener(req.getId(), channel::close);
- WriteQueue writeQueue = new WriteQueue(channel);
- // Start call only when the channel creation is successful
- stream.startCall(writeQueue, promise);
- } else {
- promise.tryFailure(future.cause());
- DefaultFuture2.getFuture(req.getId()).cancel();
- }
- });
- }
-}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleConstant.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleConstant.java
index 8d7ec48..2b9df2a 100644
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleConstant.java
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleConstant.java
@@ -14,8 +14,15 @@
* 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.stream.ClientStream;
+import org.apache.dubbo.rpc.protocol.tri.stream.ServerStream;
+
+import io.netty.handler.codec.http.HttpHeaderNames;
+import io.netty.handler.codec.http.HttpResponseStatus;
+import io.netty.handler.codec.http2.DefaultHttp2Headers;
import io.netty.util.AsciiString;
import io.netty.util.AttributeKey;
@@ -24,7 +31,7 @@ public class TripleConstant {
public static final String CONTENT_PROTO = "application/grpc+proto";
public static final String APPLICATION_GRPC = "application/grpc";
public static final String TEXT_PLAIN_UTF8 = "text/plain; encoding=utf-8";
- public static final String TRI_VERSION = "1.0.0";
+ public static final String TRI_VERSION = "3.0-TRI";
public static final String SERIALIZATION_KEY = "serialization";
public static final String TE_KEY = "te";
@@ -39,18 +46,28 @@ public class TripleConstant {
public static final AsciiString HTTPS_SCHEME = AsciiString.of("https");
public static final AsciiString HTTP_SCHEME = AsciiString.of("http");
- public static final AttributeKey<AbstractServerStream> SERVER_STREAM_KEY = AttributeKey.valueOf("tri_server_stream");
- public static final AttributeKey<AbstractClientStream> CLIENT_STREAM_KEY = AttributeKey.valueOf("tri_client_stream");
+ public static final AttributeKey<ServerStream> SERVER_STREAM_KEY = AttributeKey.valueOf("tri_server_stream");
+ public static final AttributeKey<ClientStream> CLIENT_STREAM_KEY = AttributeKey.valueOf("tri_client_stream");
public static final String SUCCESS_RESPONSE_MESSAGE = "OK";
- public static final String SUCCESS_RESPONSE_STATUS = Integer.toString(GrpcStatus.Code.OK.code);
+ public static final String SUCCESS_RESPONSE_STATUS = Integer.toString(RpcStatus.Code.OK.code);
- public static final Metadata SUCCESS_RESPONSE_META = getSuccessResponseMeta();
+ /**
+ * default header
+ * <p>
+ * only status and content-type
+ */
+ public static DefaultHttp2Headers createSuccessHttp2Headers() {
+ DefaultHttp2Headers headers = new DefaultHttp2Headers();
+ headers.status(HttpResponseStatus.OK.codeAsText());
+ headers.set(HttpHeaderNames.CONTENT_TYPE, TripleConstant.CONTENT_PROTO);
+ return headers;
+ }
- static Metadata getSuccessResponseMeta() {
- Metadata metadata = new DefaultMetadata();
- metadata.put(TripleHeaderEnum.MESSAGE_KEY.getHeader(), TripleConstant.SUCCESS_RESPONSE_MESSAGE);
- metadata.put(TripleHeaderEnum.STATUS_KEY.getHeader(), TripleConstant.SUCCESS_RESPONSE_STATUS);
+ public static DefaultHttp2Headers createSuccessHttp2Trailers() {
+ DefaultHttp2Headers metadata = new DefaultHttp2Headers();
+ metadata.set(TripleHeaderEnum.MESSAGE_KEY.getHeader(), TripleConstant.SUCCESS_RESPONSE_MESSAGE);
+ metadata.set(TripleHeaderEnum.STATUS_KEY.getHeader(), TripleConstant.SUCCESS_RESPONSE_STATUS);
return metadata;
}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleHeaderEnum.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleHeaderEnum.java
index 249dd29..453fd20 100644
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleHeaderEnum.java
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleHeaderEnum.java
@@ -14,6 +14,7 @@
* 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;
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleHttp2FrameServerHandler.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleHttp2FrameServerHandler.java
deleted file mode 100644
index 27f942b..0000000
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleHttp2FrameServerHandler.java
+++ /dev/null
@@ -1,297 +0,0 @@
-/*
- * 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.logger.Logger;
-import org.apache.dubbo.common.logger.LoggerFactory;
-import org.apache.dubbo.common.utils.CollectionUtils;
-import org.apache.dubbo.rpc.Invoker;
-import org.apache.dubbo.rpc.model.FrameworkModel;
-import org.apache.dubbo.rpc.model.FrameworkServiceRepository;
-import org.apache.dubbo.rpc.model.MethodDescriptor;
-import org.apache.dubbo.rpc.model.ProviderModel;
-import org.apache.dubbo.rpc.protocol.tri.GrpcStatus.Code;
-import org.apache.dubbo.rpc.protocol.tri.command.HeaderQueueCommand;
-import org.apache.dubbo.rpc.protocol.tri.command.TextDataQueueCommand;
-import org.apache.dubbo.rpc.service.ServiceDescriptorInternalCache;
-
-import io.netty.channel.Channel;
-import io.netty.channel.ChannelDuplexHandler;
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.handler.codec.http.HttpHeaderNames;
-import io.netty.handler.codec.http.HttpMethod;
-import io.netty.handler.codec.http.HttpResponseStatus;
-import io.netty.handler.codec.http.HttpUtil;
-import io.netty.handler.codec.http2.DefaultHttp2Headers;
-import io.netty.handler.codec.http2.Http2DataFrame;
-import io.netty.handler.codec.http2.Http2Headers;
-import io.netty.handler.codec.http2.Http2HeadersFrame;
-import io.netty.handler.codec.http2.Http2ResetFrame;
-import io.netty.util.ReferenceCountUtil;
-import io.netty.util.ReferenceCounted;
-
-import java.util.List;
-
-import static io.netty.handler.codec.http.HttpResponseStatus.OK;
-import static org.apache.dubbo.rpc.protocol.tri.Compressor.DEFAULT_COMPRESSOR;
-
-public class TripleHttp2FrameServerHandler extends ChannelDuplexHandler {
- private static final Logger LOGGER = LoggerFactory.getLogger(TripleHttp2FrameServerHandler.class);
- private final PathResolver pathResolver;
- private final FrameworkModel frameworkModel;
-
- public TripleHttp2FrameServerHandler(FrameworkModel frameworkModel) {
- this.frameworkModel = frameworkModel;
- this.pathResolver = frameworkModel.getExtensionLoader(PathResolver.class).getDefaultExtension();
- }
-
- @Override
- public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
- if (msg instanceof Http2HeadersFrame) {
- onHeadersRead(ctx, (Http2HeadersFrame) msg);
- } else if (msg instanceof Http2DataFrame) {
- onDataRead(ctx, (Http2DataFrame) msg);
- } else if (msg instanceof ReferenceCounted) {
- // ignored
- ReferenceCountUtil.release(msg);
- }
- }
-
- @Override
- public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
- if (evt instanceof Http2ResetFrame) {
- onResetRead(ctx, (Http2ResetFrame) evt);
- } else {
- super.userEventTriggered(ctx, evt);
- }
- }
-
- public void onResetRead(ChannelHandlerContext ctx, Http2ResetFrame frame) {
- final AbstractServerStream serverStream = ctx.channel().attr(TripleConstant.SERVER_STREAM_KEY).get();
- LOGGER.warn("Triple Server received remote reset errorCode=" + frame.errorCode());
- if (serverStream != null) {
- serverStream.cancelByRemote();
- }
- ctx.close();
- }
-
- @Override
- public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
- if (LOGGER.isWarnEnabled()) {
- LOGGER.warn("Exception in processing triple message", cause);
- }
- GrpcStatus status = GrpcStatus.getStatus(cause, "Provider's error:\n" + cause.getMessage());
- final AbstractServerStream serverStream = ctx.channel().attr(TripleConstant.SERVER_STREAM_KEY).get();
- serverStream.transportError(status, null, true);
- }
-
- public void onDataRead(ChannelHandlerContext ctx, Http2DataFrame msg) throws Exception {
- super.channelRead(ctx, msg.content());
-
- if (msg.isEndStream()) {
- final AbstractServerStream serverStream = ctx.channel().attr(TripleConstant.SERVER_STREAM_KEY).get();
- if (serverStream != null) {
- serverStream.inboundTransportObserver().onComplete();
- }
- }
- }
-
- private Invoker<?> getInvoker(Http2Headers headers, String serviceName) {
- final String version = headers.contains(TripleHeaderEnum.SERVICE_VERSION.getHeader()) ? headers.get(
- TripleHeaderEnum.SERVICE_VERSION.getHeader()).toString() : null;
- final String group = headers.contains(TripleHeaderEnum.SERVICE_GROUP.getHeader()) ? headers.get(TripleHeaderEnum.SERVICE_GROUP.getHeader())
- .toString() : null;
- final String key = URL.buildKey(serviceName, group, version);
- Invoker<?> invoker = pathResolver.resolve(key);
- if (invoker == null) {
- invoker = pathResolver.resolve(serviceName);
- }
- return invoker;
- }
-
- public void onHeadersRead(ChannelHandlerContext ctx, Http2HeadersFrame msg) throws Exception {
- final Http2Headers headers = msg.headers();
- WriteQueue writeQueue = new WriteQueue(ctx.channel());
- ServerOutboundTransportObserver transportObserver = new ServerOutboundTransportObserver(writeQueue);
-
- if (!HttpMethod.POST.asciiName().contentEquals(headers.method())) {
- responsePlainTextError(writeQueue, HttpResponseStatus.METHOD_NOT_ALLOWED.code(),
- GrpcStatus.fromCode(GrpcStatus.Code.INTERNAL)
- .withDescription(String.format("Method '%s' is not supported", headers.method())));
- return;
- }
-
- if (headers.path() == null) {
- responsePlainTextError(writeQueue, HttpResponseStatus.NOT_FOUND.code(),
- GrpcStatus.fromCode(Code.UNIMPLEMENTED.code).withDescription("Expected path but is missing"));
- return;
- }
-
- final String path = headers.path().toString();
- if (path.charAt(0) != '/') {
- responsePlainTextError(writeQueue, HttpResponseStatus.NOT_FOUND.code(),
- GrpcStatus.fromCode(Code.UNIMPLEMENTED.code)
- .withDescription(String.format("Expected path to start with /: %s", path)));
- return;
- }
-
- final CharSequence contentType = HttpUtil.getMimeType(headers.get(HttpHeaderNames.CONTENT_TYPE));
- if (contentType == null) {
- responsePlainTextError(writeQueue, HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE.code(),
- GrpcStatus.fromCode(GrpcStatus.Code.INTERNAL.code)
- .withDescription("Content-Type is missing from the request"));
- return;
- }
-
- final String contentString = contentType.toString();
- if (!supportContentType(contentString)) {
- responsePlainTextError(writeQueue, HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE.code(),
- GrpcStatus.fromCode(Code.INTERNAL.code)
- .withDescription(String.format("Content-Type '%s' is not supported", contentString)));
- return;
- }
-
- String[] parts = path.split("/");
- if (parts.length != 3) {
- responseErr(transportObserver, GrpcStatus.fromCode(Code.UNIMPLEMENTED)
- .withDescription("Bad path format:" + path));
- return;
- }
- String serviceName = parts[1];
- String originalMethodName = parts[2];
- String methodName = Character.toLowerCase(originalMethodName.charAt(0)) + originalMethodName.substring(1);
-
- final Invoker<?> invoker = getInvoker(headers, serviceName);
- if (invoker == null) {
- responseErr(transportObserver, GrpcStatus.fromCode(Code.UNIMPLEMENTED)
- .withDescription("Service not found:" + serviceName));
- return;
- }
- FrameworkServiceRepository repo = frameworkModel.getServiceRepository();
- ProviderModel providerModel = repo.lookupExportedService(invoker.getUrl().getServiceKey());
- if (providerModel == null || providerModel.getServiceModel() == null) {
- responseErr(transportObserver, GrpcStatus.fromCode(Code.UNIMPLEMENTED)
- .withDescription("Service not found:" + serviceName));
- return;
- }
-
- MethodDescriptor methodDescriptor = null;
- List<MethodDescriptor> methodDescriptors = 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
- methodDescriptor = ServiceDescriptorInternalCache.echoService().getMethods(methodName).get(0);
- } else {
- methodDescriptors = providerModel.getServiceModel().getMethods(methodName);
- // try upper-case method
- if (CollectionUtils.isEmpty(methodDescriptors)) {
- methodDescriptors = providerModel.getServiceModel().getMethods(originalMethodName);
- }
- if (CollectionUtils.isEmpty(methodDescriptors)) {
- responseErr(transportObserver, GrpcStatus.fromCode(Code.UNIMPLEMENTED)
- .withDescription("Method :" + methodName + " not found of service:" + serviceName));
- return;
- }
- // In most cases there is only one method
- if (methodDescriptors.size() == 1) {
- methodDescriptor = methodDescriptors.get(0);
- }
- }
-
- Compressor deCompressor = Compressor.NONE;
- CharSequence messageEncoding = headers.get(TripleHeaderEnum.GRPC_ENCODING.getHeader());
- if (null != messageEncoding) {
- String compressorStr = messageEncoding.toString();
- if (!DEFAULT_COMPRESSOR.equals(compressorStr)) {
- Compressor compressor = Compressor.getCompressor(frameworkModel, compressorStr);
- if (null == compressor) {
- responseErr(transportObserver, GrpcStatus.fromCode(Code.UNIMPLEMENTED.code)
- .withDescription(String.format("Grpc-encoding '%s' is not supported", compressorStr)));
- return;
- }
- deCompressor = compressor;
- }
- }
-
- boolean isUnary = methodDescriptor == null || methodDescriptor.isUnary();
- final AbstractServerStream stream = AbstractServerStream.newServerStream(invoker.getUrl(), isUnary);
-
- Channel channel = ctx.channel();
- // You can add listeners to ChannelPromise here if you want to listen for the result of sending a frame
- stream.service(providerModel.getServiceModel())
- .invoker(invoker)
- .methodName(methodName)
- .setDeCompressor(deCompressor)
- .subscribe(transportObserver);
- if (methodDescriptor != null) {
- stream.method(methodDescriptor);
- } else {
- // Then you need to find the corresponding parameter according to the request body
- stream.methods(methodDescriptors);
- }
-
- final TransportObserver observer = stream.inboundTransportObserver();
- observer.onMetadata(new Http2HeaderMeta(headers), false);
- if (msg.isEndStream()) {
- observer.onComplete();
- }
- channel.attr(TripleConstant.SERVER_STREAM_KEY).set(stream);
- }
-
- /**
- * must starts from application/grpc
- */
- private boolean supportContentType(String contentType) {
- if (contentType == null) {
- return false;
- }
- return contentType.startsWith(TripleConstant.APPLICATION_GRPC);
- }
-
- private void responsePlainTextError(WriteQueue writeQueue, int code, GrpcStatus status) {
- Http2Headers headers = new DefaultHttp2Headers(true)
- .status(String.valueOf(code))
- .setInt(TripleHeaderEnum.STATUS_KEY.getHeader(), status.code.code)
- .set(TripleHeaderEnum.MESSAGE_KEY.getHeader(), status.description)
- .set(TripleHeaderEnum.CONTENT_TYPE_KEY.getHeader(), TripleConstant.TEXT_PLAIN_UTF8);
- writeQueue.enqueue(HeaderQueueCommand.createHeaders(headers, false), false);
- writeQueue.enqueue(TextDataQueueCommand.createCommand(status.description, true), true);
- }
-
- private void responseErr(ServerOutboundTransportObserver observer, GrpcStatus status) {
- Http2Headers trailers = new DefaultHttp2Headers()
- .status(OK.codeAsText())
- .set(HttpHeaderNames.CONTENT_TYPE, TripleConstant.CONTENT_PROTO)
- .setInt(TripleHeaderEnum.STATUS_KEY.getHeader(), status.code.code)
- .set(TripleHeaderEnum.MESSAGE_KEY.getHeader(), status.toMessage());
- observer.onMetadata(trailers, true);
- }
-
- private boolean isEcho(String methodName) {
- return CommonConstants.$ECHO.equals(methodName);
- }
-
- private boolean isGeneric(String methodName) {
- return CommonConstants.$INVOKE.equals(methodName) || CommonConstants.$INVOKE_ASYNC.equals(methodName);
- }
-
-}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleHttp2Protocol.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleHttp2Protocol.java
index 27bb9a4..e0e41df 100644
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleHttp2Protocol.java
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleHttp2Protocol.java
@@ -14,16 +14,28 @@
* 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.extension.Activate;
+import org.apache.dubbo.common.serialize.MultipleSerialization;
+import org.apache.dubbo.common.threadpool.manager.ExecutorRepository;
+import org.apache.dubbo.config.Constants;
import org.apache.dubbo.remoting.api.Http2WireProtocol;
+import org.apache.dubbo.rpc.HeaderFilter;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ScopeModelAware;
+import org.apache.dubbo.rpc.protocol.tri.pack.GenericUnpack;
+import org.apache.dubbo.rpc.protocol.tri.transport.TripleClientHandler;
+import org.apache.dubbo.rpc.protocol.tri.transport.TripleCommandOutBoundHandler;
+import org.apache.dubbo.rpc.protocol.tri.transport.TripleHttp2FrameServerHandler;
+import org.apache.dubbo.rpc.protocol.tri.transport.TripleServerConnectionHandler;
+import org.apache.dubbo.rpc.protocol.tri.transport.TripleTailHandler;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
@@ -34,6 +46,10 @@ import io.netty.handler.codec.http2.Http2MultiplexHandler;
import io.netty.handler.codec.http2.Http2Settings;
import io.netty.handler.ssl.SslContext;
+import java.util.List;
+import java.util.concurrent.Executor;
+
+import static org.apache.dubbo.common.constants.CommonConstants.HEADER_FILTER_KEY;
import static org.apache.dubbo.rpc.Constants.H2_SETTINGS_ENABLE_PUSH_KEY;
import static org.apache.dubbo.rpc.Constants.H2_SETTINGS_HEADER_TABLE_SIZE_KEY;
import static org.apache.dubbo.rpc.Constants.H2_SETTINGS_INITIAL_WINDOW_SIZE_KEY;
@@ -63,6 +79,7 @@ public class TripleHttp2Protocol extends Http2WireProtocol implements ScopeModel
@Override
public void configServerPipeline(URL url, ChannelPipeline pipeline, SslContext sslContext) {
+ final List<HeaderFilter> filters = url.getOrDefaultApplicationModel().getExtensionLoader(HeaderFilter.class).getActivateExtension(url, HEADER_FILTER_KEY);
final Configuration config = ConfigurationUtils.getGlobalConfiguration(applicationModel);
final Http2FrameCodec codec = Http2FrameCodecBuilder.forServer()
.gracefulShutdownTimeoutMillis(10000)
@@ -74,23 +91,36 @@ public class TripleHttp2Protocol extends Http2WireProtocol implements ScopeModel
.maxHeaderListSize(config.getInt(H2_SETTINGS_MAX_HEADER_LIST_SIZE_KEY, 8192)))
.frameLogger(SERVER_LOGGER)
.build();
+ final MultipleSerialization serialization = frameworkModel
+ .getExtensionLoader(MultipleSerialization.class)
+ .getExtension(url.getParameter(Constants.MULTI_SERIALIZATION_KEY, CommonConstants.DEFAULT_KEY));
final Http2MultiplexHandler handler = new Http2MultiplexHandler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) {
final ChannelPipeline p = ch.pipeline();
p.addLast(new TripleCommandOutBoundHandler());
- p.addLast(new TripleHttp2FrameServerHandler(frameworkModel));
- // TODO constraint MAX DATA_SIZE
- p.addLast(new GrpcDataDecoder(Integer.MAX_VALUE, false));
- p.addLast(new TripleServerInboundHandler());
+ p.addLast(new TripleHttp2FrameServerHandler(frameworkModel, lookupExecutor(url), filters, new GenericUnpack(serialization, url)));
}
});
pipeline.addLast(codec, new TripleServerConnectionHandler(), handler, new TripleTailHandler());
}
+
+ private Executor lookupExecutor(URL url) {
+ ExecutorRepository executorRepository = url.getOrDefaultApplicationModel()
+ .getExtensionLoader(ExecutorRepository.class)
+ .getDefaultExtension();
+ Executor urlExecutor = executorRepository.getExecutor(url);
+ if (urlExecutor == null) {
+ urlExecutor = executorRepository.createExecutorIfAbsent(url);
+ }
+ return urlExecutor;
+ }
+
@Override
public void configClientPipeline(URL url, ChannelPipeline pipeline, SslContext sslContext) {
+
final Configuration config = ConfigurationUtils.getGlobalConfiguration(applicationModel);
final Http2FrameCodec codec = Http2FrameCodecBuilder.forClient()
.gracefulShutdownTimeoutMillis(10000)
@@ -104,6 +134,6 @@ public class TripleHttp2Protocol extends Http2WireProtocol implements ScopeModel
.frameLogger(CLIENT_LOGGER)
.build();
final Http2MultiplexHandler handler = new Http2MultiplexHandler(new TripleClientHandler(frameworkModel));
- pipeline.addLast(codec, handler, new TripleClientRequestHandler(frameworkModel));
+ pipeline.addLast(codec, handler);
}
}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleInvoker.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleInvoker.java
index d658dac..31b7199 100644
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleInvoker.java
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleInvoker.java
@@ -14,19 +14,15 @@
* 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.Version;
-import org.apache.dubbo.common.utils.StringUtils;
-import org.apache.dubbo.remoting.Constants;
+import org.apache.dubbo.common.serialize.MultipleSerialization;
+import org.apache.dubbo.common.threadpool.manager.ExecutorRepository;
import org.apache.dubbo.remoting.RemotingException;
-import org.apache.dubbo.remoting.TimeoutException;
import org.apache.dubbo.remoting.api.Connection;
import org.apache.dubbo.remoting.api.ConnectionManager;
-import org.apache.dubbo.remoting.exchange.Request;
-import org.apache.dubbo.remoting.exchange.Response;
-import org.apache.dubbo.remoting.exchange.support.DefaultFuture2;
import org.apache.dubbo.rpc.AppResponse;
import org.apache.dubbo.rpc.AsyncRpcResult;
import org.apache.dubbo.rpc.FutureContext;
@@ -34,14 +30,18 @@ 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.RpcInvocation;
import org.apache.dubbo.rpc.TimeoutCountDown;
+import org.apache.dubbo.rpc.model.ConsumerModel;
+import org.apache.dubbo.rpc.model.MethodDescriptor;
import org.apache.dubbo.rpc.protocol.AbstractInvoker;
+import org.apache.dubbo.rpc.protocol.tri.call.ClientCall;
+import org.apache.dubbo.rpc.protocol.tri.call.ClientCallUtil;
+import org.apache.dubbo.rpc.protocol.tri.compressor.Compressor;
+import org.apache.dubbo.rpc.protocol.tri.pack.GenericPack;
+import org.apache.dubbo.rpc.protocol.tri.pack.GenericUnpack;
+import org.apache.dubbo.rpc.protocol.tri.stream.StreamUtils;
import org.apache.dubbo.rpc.support.RpcUtils;
-import io.netty.channel.ChannelFuture;
-
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
@@ -51,10 +51,10 @@ import java.util.concurrent.locks.ReentrantLock;
import static org.apache.dubbo.common.constants.CommonConstants.ENABLE_TIMEOUT_COUNTDOWN_KEY;
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.PATH_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_ATTACHMENT_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.TIME_COUNTDOWN_KEY;
+import static org.apache.dubbo.rpc.Constants.COMPRESSOR_KEY;
import static org.apache.dubbo.rpc.Constants.TOKEN_KEY;
/**
@@ -64,74 +64,68 @@ public class TripleInvoker<T> extends AbstractInvoker<T> {
private final Connection connection;
private final ReentrantLock destroyLock = new ReentrantLock();
-
+ private final Compressor compressor;
+ private final String acceptEncoding;
private final Set<Invoker<?>> invokers;
-
- public TripleInvoker(Class<T> serviceType, URL url, Set<Invoker<?>> invokers) throws RemotingException {
+ private final GenericPack genericPack;
+ private final GenericUnpack genericUnpack;
+
+ public TripleInvoker(Class<T> serviceType,
+ URL url,
+ MultipleSerialization serialization,
+ String serializationName,
+ Compressor defaultCompressor,
+ String acceptEncoding,
+ ConnectionManager connectionManager,
+ Set<Invoker<?>> invokers) throws RemotingException {
super(serviceType, url, new String[]{INTERFACE_KEY, GROUP_KEY, TOKEN_KEY});
+ this.genericPack = new GenericPack(serialization, serializationName, url);
+ this.genericUnpack = new GenericUnpack(serialization, url);
this.invokers = invokers;
- ConnectionManager connectionManager = url.getOrDefaultFrameworkModel().getExtensionLoader(ConnectionManager.class).getExtension("multiple");
+ this.acceptEncoding = acceptEncoding;
this.connection = connectionManager.connect(url);
+ String compressorStr = url.getParameter(COMPRESSOR_KEY);
+ if (compressorStr == null) {
+ compressor = defaultCompressor;
+ } else {
+ compressor = Compressor.getCompressor(url.getOrDefaultFrameworkModel(), compressorStr);
+ }
}
- @Override
- protected Result doInvoke(final Invocation invocation) throws Throwable {
- RpcInvocation inv = (RpcInvocation) invocation;
-
- final String methodName = RpcUtils.getMethodName(invocation);
- inv.setServiceModel(RpcContext.getServiceContext().getConsumerUrl().getServiceModel());
- inv.setAttachment(PATH_KEY, getUrl().getPath());
- inv.setAttachment(Constants.SERIALIZATION_KEY,
- getUrl().getParameter(Constants.SERIALIZATION_KEY, Constants.DEFAULT_REMOTING_SERIALIZATION));
- try {
- int timeout = calculateTimeout(invocation, methodName);
- invocation.setAttachment(TIMEOUT_KEY, timeout);
- ExecutorService executor = getCallbackExecutor(getUrl(), inv);
- // create request.
- Request req = new Request();
- req.setVersion(Version.getProtocolVersion());
- req.setTwoWay(true);
- req.setData(inv);
-
- // try connect
- connection.isAvailable();
-
- DefaultFuture2 future = DefaultFuture2.newFuture(this.connection, req, timeout, executor);
- final CompletableFuture<AppResponse> respFuture = future.thenApply(obj -> (AppResponse) obj);
- // save for 2.6.x compatibility, for example, TraceFilter in Zipkin uses com.alibaba.xxx.FutureAdapter
- FutureContext.getContext().setCompatibleFuture(respFuture);
- AsyncRpcResult result = new AsyncRpcResult(respFuture, inv);
- result.setExecutor(executor);
-
- if (!connection.isAvailable()) {
- Response response = new Response(req.getId(), req.getVersion());
- response.setStatus(Response.CHANNEL_INACTIVE);
- response.setErrorMessage(String.format("Connect to %s failed", this));
- DefaultFuture2.received(connection, response);
- } else {
- final ChannelFuture writeFuture = this.connection.write(req);
- writeFuture.addListener(future1 -> {
- if (future1.isSuccess()) {
- DefaultFuture2.sent(req);
- } else {
- Response response = new Response(req.getId(), req.getVersion());
- response.setStatus(Response.CHANNEL_INACTIVE);
- response.setErrorMessage(StringUtils.toString(future1.cause()));
- DefaultFuture2.received(connection, response);
- }
- });
- }
+ @Override
+ protected Result doInvoke(final Invocation invocation) {
+ URL url = getUrl();
+ ExecutorService callbackExecutor = getCallbackExecutor(url, invocation);
+ int timeout = calculateTimeout(invocation, invocation.getMethodName());
+ invocation.setAttachment(TIMEOUT_KEY, timeout);
+ DefaultFuture2 future = DefaultFuture2.newFuture(this.connection, invocation, timeout, callbackExecutor);
+ final CompletableFuture<AppResponse> respFuture = future.thenApply(obj -> (AppResponse) obj);
+ FutureContext.getContext().setCompatibleFuture(respFuture);
+ AsyncRpcResult result = new AsyncRpcResult(respFuture, invocation);
+ result.setExecutor(callbackExecutor);
+
+ if (!connection.isAvailable()) {
+ final RpcStatus status = RpcStatus.UNAVAILABLE
+ .withDescription(String.format("Connect to %s failed", this));
+ DefaultFuture2.received(future.requestId, status, null);
return result;
- } catch (TimeoutException e) {
- throw new RpcException(RpcException.TIMEOUT_EXCEPTION,
- "Invoke remote method timeout. method: " + invocation.getMethodName() + ", provider: " + getUrl()
- + ", cause: " + e.getMessage(), e);
- } catch (RemotingException e) {
- throw new RpcException(RpcException.NETWORK_EXCEPTION,
- "Failed to invoke remote method: " + invocation.getMethodName() + ", provider: " + getUrl()
- + ", cause: " + e.getMessage(), e);
}
+ ConsumerModel consumerModel = invocation.getServiceModel() != null ?
+ (ConsumerModel) invocation.getServiceModel() : (ConsumerModel) getUrl().getServiceModel();
+ final MethodDescriptor methodDescriptor = consumerModel.getServiceModel()
+ .getMethod(invocation.getMethodName(), invocation.getParameterTypes());
+ final RequestMetadata metadata = StreamUtils.createRequest(getUrl(), methodDescriptor, invocation, future.requestId,
+ compressor, acceptEncoding, timeout, genericPack, genericUnpack);
+ ExecutorService executor = url.getOrDefaultApplicationModel().getExtensionLoader(ExecutorRepository.class)
+ .getDefaultExtension()
+ .getExecutor(url);
+ if (executor == null) {
+ throw new IllegalStateException("No available executor found in " + url);
+ }
+ ClientCall call = new ClientCall(connection, executor, url.getOrDefaultFrameworkModel());
+ ClientCallUtil.call(call, metadata);
+ return result;
}
@Override
@@ -188,4 +182,5 @@ public class TripleInvoker<T> extends AbstractInvoker<T> {
}
return timeout;
}
+
}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TriplePathResolver.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TriplePathResolver.java
index 1de6bc3..6629f84 100644
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TriplePathResolver.java
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TriplePathResolver.java
@@ -14,6 +14,7 @@
* 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;
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleProtocol.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleProtocol.java
index ebf8515..581de02 100644
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleProtocol.java
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleProtocol.java
@@ -14,14 +14,18 @@
* 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.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
+import org.apache.dubbo.common.serialize.MultipleSerialization;
import org.apache.dubbo.common.threadpool.manager.ExecutorRepository;
-import org.apache.dubbo.common.utils.ExecutorUtil;
+import org.apache.dubbo.config.Constants;
import org.apache.dubbo.remoting.RemotingException;
+import org.apache.dubbo.remoting.api.ConnectionManager;
import org.apache.dubbo.remoting.exchange.PortUnificationExchanger;
import org.apache.dubbo.rpc.Exporter;
import org.apache.dubbo.rpc.Invoker;
@@ -29,22 +33,29 @@ import org.apache.dubbo.rpc.RpcException;
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.Compressor;
import org.apache.dubbo.rpc.protocol.tri.service.TriBuiltinService;
import grpc.health.v1.HealthCheckResponse;
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;
public class TripleProtocol extends AbstractProtocol {
+ private static final String CLIENT_THREAD_POOL_NAME = "DubboTriClientHandler";
private static final Logger logger = LoggerFactory.getLogger(TripleProtocol.class);
private final PathResolver pathResolver;
private final TriBuiltinService triBuiltinService;
+ private final ConnectionManager connectionManager;
+ private final FrameworkModel frameworkModel;
public TripleProtocol(FrameworkModel frameworkModel) {
+ this.frameworkModel = frameworkModel;
this.triBuiltinService = new TriBuiltinService(frameworkModel);
this.pathResolver = frameworkModel.getExtensionLoader(PathResolver.class).getDefaultExtension();
+ this.connectionManager = frameworkModel.getExtensionLoader(ConnectionManager.class).getExtension("multiple");
}
@Override
@@ -82,14 +93,26 @@ public class TripleProtocol extends AbstractProtocol {
@Override
public <T> Invoker<T> refer(Class<T> type, URL url) throws RpcException {
+ final MultipleSerialization serialization = frameworkModel
+ .getExtensionLoader(MultipleSerialization.class)
+ .getExtension(url.getParameter(Constants.MULTI_SERIALIZATION_KEY, CommonConstants.DEFAULT_KEY));
+
+ url = url.addParameter(THREAD_NAME_KEY, CLIENT_THREAD_POOL_NAME);
+ url = url.addParameterIfAbsent(THREADPOOL_KEY, DEFAULT_CLIENT_THREADPOOL);
+ url.getOrDefaultApplicationModel()
+ .getExtensionLoader(ExecutorRepository.class)
+ .getDefaultExtension()
+ .createExecutorIfAbsent(url);
+ // TODO support config
+// String compressorStr = ConfigurationUtils.getCachedDynamicProperty(frameworkModel, COMPRESSOR_KEY, Identity.MESSAGE_ENCODING);
+// Compressor defaultCompressor = Compressor.getCompressor(frameworkModel, compressorStr);
+ Compressor defaultCompressor = Compressor.NONE;
+// String acceptEncoding = Compressor.getAcceptEncoding(frameworkModel);
+ String acceptEncoding = Compressor.NONE.getMessageEncoding();
+ final String serializationName = url.getParameter(org.apache.dubbo.remoting.Constants.SERIALIZATION_KEY, org.apache.dubbo.remoting.Constants.DEFAULT_REMOTING_SERIALIZATION);
TripleInvoker<T> invoker;
try {
- url = ExecutorUtil.setThreadName(url, "DubboClientHandler");
- url = url.addParameterIfAbsent(THREADPOOL_KEY, DEFAULT_CLIENT_THREADPOOL);
- ExecutorRepository executorRepository = url.getOrDefaultApplicationModel()
- .getExtensionLoader(ExecutorRepository.class).getDefaultExtension();
- executorRepository.createExecutorIfAbsent(url);
- invoker = new TripleInvoker<>(type, url, invokers);
+ invoker = new TripleInvoker<>(type, url, serialization, serializationName, defaultCompressor, acceptEncoding, connectionManager, invokers);
} catch (RemotingException e) {
throw new RpcException("Fail to create remoting client for service(" + url + "): " + e.getMessage(), e);
}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleServerInboundHandler.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleServerInboundHandler.java
deleted file mode 100644
index 115970e..0000000
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleServerInboundHandler.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * 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.channel.ChannelHandlerContext;
-import io.netty.channel.ChannelInboundHandlerAdapter;
-
-public class TripleServerInboundHandler extends ChannelInboundHandlerAdapter {
- @Override
- public void channelRead(ChannelHandlerContext ctx, Object msg) {
- final AbstractServerStream serverStream = ctx.channel().attr(TripleConstant.SERVER_STREAM_KEY).get();
- final byte[] data = (byte[]) msg;
- if (serverStream != null) {
- serverStream.inboundTransportObserver()
- .onData(data, false);
- }
- }
-}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/UnaryClientStream.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/UnaryClientStream.java
deleted file mode 100644
index 2470b00..0000000
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/UnaryClientStream.java
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * 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.remoting.exchange.Response;
-import org.apache.dubbo.remoting.exchange.support.DefaultFuture2;
-import org.apache.dubbo.rpc.AppResponse;
-
-public class UnaryClientStream extends AbstractClientStream implements Stream {
-
- protected UnaryClientStream(URL url) {
- super(url);
- }
-
- @Override
- protected void doOnStartCall() {
- inboundMessageObserver().onNext(getRpcInvocation());
- inboundMessageObserver().onCompleted();
- }
-
- @Override
- protected InboundTransportObserver createInboundTransportObserver() {
- return new ClientUnaryInboundTransportObserver();
- }
-
-
- private class ClientUnaryInboundTransportObserver extends ServerUnaryInboundTransportObserver {
-
- @Override
- public void onComplete() {
- execute(() -> {
- final GrpcStatus status = extractStatusFromMeta(getHeaders());
- if (GrpcStatus.Code.isOk(status.code.code)) {
- try {
- AppResponse result;
- if (!Void.TYPE.equals(getMethodDescriptor().getReturnClass())) {
- if (getData() == null) {
- final GrpcStatus clientStatus = GrpcStatus.fromCode(GrpcStatus.Code.INTERNAL)
- .withDescription("Missing response data");
- onError(clientStatus);
- return;
- }
- final Object resp = deserializeResponse(getData());
- result = new AppResponse(resp);
- } else {
- result = new AppResponse();
- }
- Response response = new Response(getRequestId(), TripleConstant.TRI_VERSION);
- result.setObjectAttachments(parseMetadataToAttachmentMap(getTrailers()));
- response.setResult(result);
- DefaultFuture2.received(getConnection(), response);
- } catch (Exception e) {
- final GrpcStatus clientStatus = GrpcStatus.fromCode(GrpcStatus.Code.INTERNAL)
- .withCause(e)
- .withDescription("Failed to deserialize response");
- onError(clientStatus);
- }
- } else {
- onError(status);
- }
- });
- }
-
- @Override
- public void onError(GrpcStatus status) {
- Response response = new Response(getRequestId(), TripleConstant.TRI_VERSION);
- response.setErrorMessage(status.description);
- final AppResponse result = new AppResponse();
- final Metadata trailers = getTrailers() == null ? getHeaders() : getTrailers();
- final Throwable trailersException = getThrowableFromTrailers(trailers);
- if (trailersException != null) {
- result.setException(trailersException);
- } else {
- result.setException(status.cause);
- }
- result.setObjectAttachments(UnaryClientStream.this.parseMetadataToAttachmentMap(trailers));
- response.setResult(result);
- if (!result.hasException()) {
- final byte code = GrpcStatus.toDubboStatus(status.code);
- response.setStatus(code);
- }
- DefaultFuture2.received(getConnection(), response);
- }
-
-
- }
-}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/UnaryServerStream.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/UnaryServerStream.java
deleted file mode 100644
index 04412a5..0000000
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/UnaryServerStream.java
+++ /dev/null
@@ -1,112 +0,0 @@
-/*
- * 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.stream.StreamObserver;
-import org.apache.dubbo.rpc.AppResponse;
-import org.apache.dubbo.rpc.Result;
-import org.apache.dubbo.rpc.RpcContext;
-import org.apache.dubbo.rpc.RpcInvocation;
-
-import java.util.concurrent.CompletionStage;
-import java.util.function.Function;
-
-import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY;
-import static org.apache.dubbo.rpc.protocol.tri.GrpcStatus.getStatus;
-
-public class UnaryServerStream extends AbstractServerStream implements Stream {
-
- protected UnaryServerStream(URL url) {
- super(url);
- }
-
- @Override
- protected StreamObserver<Object> createStreamObserver() {
- return null;
- }
-
- @Override
- protected InboundTransportObserver createInboundTransportObserver() {
- return new UnaryServerTransportObserver();
- }
-
- private class UnaryServerTransportObserver extends ServerUnaryInboundTransportObserver {
- @Override
- public void onError(GrpcStatus status) {
- transportError(status);
- }
-
- @Override
- public void onComplete() {
- execute(() -> {
- if (getData() != null) {
- invoke();
- } else {
- onError(GrpcStatus.fromCode(GrpcStatus.Code.INTERNAL)
- .withDescription("Missing request data"));
- }
- });
- }
-
- public void invoke() {
- RpcInvocation invocation = buildUnaryInvocation(getHeaders(), getData());
- if (invocation == null) {
- return;
- }
- final long stInNano = System.nanoTime();
- final Result result = getInvoker().invoke(invocation);
- CompletionStage<Object> future = result.thenApply(Function.identity());
- future.whenComplete((o, throwable) -> {
- if (throwable != null) {
- LOGGER.error("Invoke error", throwable);
- transportError(getStatus(throwable));
- return;
- }
- AppResponse response = (AppResponse) o;
- if (response.hasException()) {
- transportError(getStatus(response.getException()));
- return;
- }
- final Object timeoutVal = invocation.getObjectAttachment(TIMEOUT_KEY);
- final long cost = System.nanoTime() - stInNano;
- if (timeoutVal != null && cost > ((Long) timeoutVal)) {
- LOGGER.error(String.format("Invoke timeout at server side, ignored to send response. service=%s method=%s cost=%s timeout=%s",
- invocation.getTargetServiceUniqueName(),
- invocation.getMethodName(),
- cost, timeoutVal));
- outboundTransportObserver()
- .onError(GrpcStatus.fromCode(GrpcStatus.Code.DEADLINE_EXCEEDED));
- } else {
- Metadata metadata = createResponseMeta();
- outboundTransportObserver().onMetadata(metadata, false);
- final byte[] data = encodeResponse(response.getValue());
- if (data == null) {
- // already handled in encodeResponse()
- return;
- }
- outboundTransportObserver().onData(data, false);
- Metadata trailers = TripleConstant.getSuccessResponseMeta();
- convertAttachment(trailers, response.getObjectAttachments());
- outboundTransportObserver().onMetadata(trailers, true);
- }
- });
- RpcContext.removeContext();
- }
- }
-}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/AbstractServerCallListener.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/AbstractServerCallListener.java
new file mode 100644
index 0000000..489ee6c
--- /dev/null
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/AbstractServerCallListener.java
@@ -0,0 +1,70 @@
+/*
+ * 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.Logger;
+import org.apache.dubbo.common.logger.LoggerFactory;
+import org.apache.dubbo.rpc.CancellationContext;
+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.protocol.tri.RpcStatus;
+import org.apache.dubbo.rpc.protocol.tri.observer.ServerCallToObserverAdapter;
+
+public abstract class AbstractServerCallListener implements ServerCall.Listener {
+ private static final Logger LOGGER = LoggerFactory.getLogger(AbstractServerCallListener.class);
+ public final CancellationContext cancellationContext;
+ final RpcInvocation invocation;
+ final Invoker<?> invoker;
+ final ServerCallToObserverAdapter<Object> responseObserver;
+
+ public AbstractServerCallListener(RpcInvocation invocation, Invoker<?> invoker,
+ ServerCallToObserverAdapter<Object> responseObserver) {
+ this.invocation = invocation;
+ this.invoker = invoker;
+ this.cancellationContext = responseObserver.cancellationContext;
+ this.responseObserver = responseObserver;
+ }
+
+ public Object invoke() throws Throwable {
+ RpcContext.restoreCancellationContext(cancellationContext);
+ final long stInMillis = System.currentTimeMillis();
+ try {
+ final Result response = invoker.invoke(invocation);
+ responseObserver.setResponseAttachments(response.getObjectAttachments());
+ if (response.hasException()) {
+ throw response.getException();
+ }
+ final long cost = System.currentTimeMillis() - stInMillis;
+ if (responseObserver.isTimeout(cost)) {
+ LOGGER.error(String.format("Invoke timeout at server side, ignored to send response. service=%s method=%s cost=%s",
+ invocation.getTargetServiceUniqueName(),
+ invocation.getMethodName(),
+ cost));
+ responseObserver.onCompleted(RpcStatus.DEADLINE_EXCEEDED);
+ return null;
+ } else {
+ return response.getValue();
+ }
+ } finally {
+ RpcContext.removeCancellationContext();
+ RpcContext.removeContext();
+ }
+ }
+}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/BiStreamServerCallListener.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/BiStreamServerCallListener.java
new file mode 100644
index 0000000..50f3ca6
--- /dev/null
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/BiStreamServerCallListener.java
@@ -0,0 +1,58 @@
+/*
+ * 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.Invoker;
+import org.apache.dubbo.rpc.RpcInvocation;
+import org.apache.dubbo.rpc.protocol.tri.RpcStatus;
+import org.apache.dubbo.rpc.protocol.tri.observer.ServerCallToObserverAdapter;
+
+public class BiStreamServerCallListener extends AbstractServerCallListener {
+ private final StreamObserver<Object> requestObserver;
+
+ public BiStreamServerCallListener(RpcInvocation invocation, Invoker<?> invoker, ServerCallToObserverAdapter<Object> responseObserver) throws Throwable {
+ super(invocation, invoker, responseObserver);
+ invocation.setArguments(new Object[]{responseObserver});
+ this.requestObserver = (StreamObserver<Object>) invoke();
+ }
+
+ @Override
+ public void onMessage(Object message) {
+ if (message instanceof Object[]) {
+ message = ((Object[]) message)[0];
+ }
+ requestObserver.onNext(message);
+ if (responseObserver.isAutoRequestN()) {
+ responseObserver.request(1);
+ }
+ }
+
+ @Override
+ public void onCancel(String errorInfo) {
+ requestObserver.onError(RpcStatus.CANCELLED
+ .withDescription(errorInfo).asException());
+ responseObserver.cancel(RpcStatus.CANCELLED.withDescription("Cancel by client:" + errorInfo).asException());
+ }
+
+
+ @Override
+ public void onComplete() {
+ requestObserver.onCompleted();
+ }
+}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/ClientCall.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/ClientCall.java
new file mode 100644
index 0000000..418aa78
--- /dev/null
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/ClientCall.java
@@ -0,0 +1,260 @@
+/*
+ * 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.Logger;
+import org.apache.dubbo.common.logger.LoggerFactory;
+import org.apache.dubbo.remoting.api.Connection;
+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.RequestMetadata;
+import org.apache.dubbo.rpc.protocol.tri.RpcStatus;
+import org.apache.dubbo.rpc.protocol.tri.TripleHeaderEnum;
+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.pack.PbPack;
+import org.apache.dubbo.rpc.protocol.tri.pack.PbUnpack;
+import org.apache.dubbo.rpc.protocol.tri.stream.ClientStream;
+import org.apache.dubbo.rpc.protocol.tri.stream.ClientStreamListener;
+import org.apache.dubbo.rpc.protocol.tri.transport.H2TransportListener;
+
+import com.google.protobuf.Any;
+import com.google.rpc.DebugInfo;
+import com.google.rpc.ErrorInfo;
+import com.google.rpc.Status;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.Executor;
+
+public class ClientCall {
+ private static final Logger LOGGER = LoggerFactory.getLogger(ClientCall.class);
+ private final Connection connection;
+ private final Executor executor;
+ private final FrameworkModel frameworkModel;
+ private RequestMetadata requestMetadata;
+ private ClientStream stream;
+ private boolean canceled;
+ private boolean headerSent;
+
+ public ClientCall(Connection connection,
+ Executor executor,
+ FrameworkModel frameworkModel
+ ) {
+ this.connection = connection;
+ this.executor = executor;
+ this.frameworkModel = frameworkModel;
+ }
+
+ public void sendMessage(Object message) {
+ if (canceled) {
+ throw new IllegalStateException("Call already canceled");
+ }
+ if (!headerSent) {
+ headerSent = true;
+ stream.startCall(requestMetadata);
+ }
+ final byte[] data;
+ try {
+ data = PbPack.INSTANCE.pack(message);
+ int compressed = Identity.MESSAGE_ENCODING.equals(requestMetadata.compressor.getMessageEncoding()) ? 0 : 1;
+ final byte[] compress = requestMetadata.compressor.compress(data);
+ stream.writeMessage(compress, compressed);
+ } catch (IOException e) {
+ cancel("Serialize request failed", e);
+ }
+ }
+
+
+ public void requestN(int n) {
+ stream.requestN(n);
+ }
+
+ public void halfClose() {
+ if (!headerSent) {
+ return;
+ }
+ if (canceled) {
+ return;
+ }
+ stream.halfClose();
+ }
+
+ public void setCompression(String compression) {
+ this.requestMetadata.compressor = Compressor.getCompressor(frameworkModel, compression);
+ }
+
+ public void start(RequestMetadata metadata, ClientCall.StartListener responseListener) {
+ this.requestMetadata = metadata;
+ final PbUnpack<?> unpack = requestMetadata.method.isNeedWrap() ?
+ PbUnpack.RESP_PB_UNPACK : new PbUnpack<>(requestMetadata.method.getReturnClass());
+
+ this.stream = new ClientStream(
+ frameworkModel,
+ metadata.requestId,
+ executor,
+ connection.getChannel(),
+ new ClientStreamListenerImpl(responseListener, unpack));
+ }
+
+ public void cancel(String message, Throwable t) {
+ if (canceled) {
+ return;
+ }
+ // did not create stream
+ if (!headerSent) {
+ return;
+ }
+ canceled = true;
+ if (stream == null) {
+ return;
+ }
+ RpcStatus status = RpcStatus.CANCELLED.withCause(t);
+ if (message != null) {
+ status = status.withDescription(message);
+ } else {
+ status = status.withDescription("Cancel by client without message");
+ }
+ stream.cancelByLocal(status);
+ }
+
+ interface Listener {
+
+ void onMessage(Object message);
+
+ void onClose(RpcStatus status, Map<String, Object> trailers);
+ }
+
+
+ public interface StartListener extends Listener {
+
+ void onStart();
+ }
+
+ class ClientStreamListenerImpl implements ClientStreamListener {
+
+ private final StartListener listener;
+ private final PbUnpack<?> unpack;
+ private boolean done;
+
+ ClientStreamListenerImpl(StartListener listener, PbUnpack<?> unpack) {
+ this.unpack = unpack;
+ this.listener = listener;
+ }
+
+ @Override
+ public void onStart() {
+ listener.onStart();
+ }
+
+ @Override
+ public void onMessage(byte[] message) {
+ if (done) {
+ LOGGER.warn("Received message from closed stream,connection=" + connection
+ + " service=" + requestMetadata.service + " method=" + requestMetadata.method.getMethodName());
+ return;
+ }
+ try {
+ final Object unpacked = unpack.unpack(message);
+ listener.onMessage(unpacked);
+ } catch (IOException e) {
+ cancelByErr(RpcStatus.INTERNAL
+ .withDescription("Deserialize response failed")
+ .withCause(e));
+ }
+ }
+
+ @Override
+ public void complete(RpcStatus status, Map<String, Object> attachments, Map<String, String> excludeHeaders) {
+ done = true;
+ final RpcStatus detailStatus;
+ final RpcStatus statusFromTrailers = getStatusFromTrailers(excludeHeaders);
+ if (statusFromTrailers != null) {
+ detailStatus = statusFromTrailers;
+ } else {
+ detailStatus = status;
+ }
+ try {
+ listener.onClose(detailStatus, attachments);
+ } catch (Throwable t) {
+ cancelByErr(RpcStatus.INTERNAL
+ .withDescription("Close stream error")
+ .withCause(t));
+ }
+ }
+
+ void cancelByErr(RpcStatus status) {
+ stream.cancelByLocal(status);
+ }
+
+ RpcStatus getStatusFromTrailers(Map<String, String> metadata) {
+ if (null == metadata) {
+ return null;
+ }
+ // second get status detail
+ if (!metadata.containsKey(TripleHeaderEnum.STATUS_DETAIL_KEY.getHeader())) {
+ return null;
+ }
+ final String raw = (metadata.remove(TripleHeaderEnum.STATUS_DETAIL_KEY.getHeader()));
+ byte[] statusDetailBin = H2TransportListener.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
+ RpcStatus status = RpcStatus.fromCode(statusDetail.getCode())
+ .withDescription(RpcStatus.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<>();
+ 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("tran from grpc-status-details error", t);
+ }
+ return map;
+ }
+ }
+}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/ClientCallUtil.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/ClientCallUtil.java
new file mode 100644
index 0000000..c8277d3
--- /dev/null
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/ClientCallUtil.java
@@ -0,0 +1,137 @@
+/*
+ * 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.Logger;
+import org.apache.dubbo.common.logger.LoggerFactory;
+import org.apache.dubbo.common.stream.StreamObserver;
+import org.apache.dubbo.rpc.AppResponse;
+import org.apache.dubbo.rpc.CancellationContext;
+import org.apache.dubbo.rpc.model.StreamMethodDescriptor;
+import org.apache.dubbo.rpc.protocol.tri.CancelableStreamObserver;
+import org.apache.dubbo.rpc.protocol.tri.DefaultFuture2;
+import org.apache.dubbo.rpc.protocol.tri.RequestMetadata;
+import org.apache.dubbo.rpc.protocol.tri.RpcStatus;
+import org.apache.dubbo.rpc.protocol.tri.observer.ClientCallToObserverAdapter;
+import org.apache.dubbo.rpc.protocol.tri.observer.WrapperRequestObserver;
+
+public class ClientCallUtil {
+ private static final Logger LOGGER = LoggerFactory.getLogger(ClientCallUtil.class);
+
+ public static void call(ClientCall call, RequestMetadata metadata) {
+ try {
+ if (metadata.method instanceof StreamMethodDescriptor) {
+ streamCall(call, metadata);
+ } else {
+ unaryCall(call, metadata);
+ }
+ } catch (Throwable t) {
+ cancelByThrowable(call, t);
+ final RpcStatus status = RpcStatus.INTERNAL
+ .withCause(t)
+ .withDescription("Call aborted cause client exception");
+ DefaultFuture2.received(metadata.requestId, status, null);
+ }
+ }
+
+ public static void streamCall(ClientCall call,
+ RequestMetadata metadata) {
+ AppResponse appResponse = new AppResponse();
+ StreamMethodDescriptor methodDescriptor = (StreamMethodDescriptor) metadata.method;
+ if (methodDescriptor.isServerStream()) {
+ callServerStream(call, metadata);
+ } else {
+ callBiOrClientStream(call, metadata, appResponse);
+ }
+ DefaultFuture2.sent(metadata.requestId);
+ DefaultFuture2.received(metadata.requestId, RpcStatus.OK, appResponse);
+ }
+
+ private static void callBiOrClientStream(ClientCall call, RequestMetadata metadata, AppResponse appResponse) {
+ StreamObserver<Object> responseObserver = (StreamObserver<Object>) metadata.arguments[0];
+ final StreamObserver<Object> requestObserver = streamCall(call, metadata, responseObserver);
+ appResponse.setValue(requestObserver);
+ }
+
+ private static void callServerStream(ClientCall call, RequestMetadata metadata) {
+ Object request = metadata.arguments[0];
+ StreamObserver<Object> responseObserver = (StreamObserver<Object>) metadata.arguments[1];
+ final StreamObserver<Object> requestObserver = streamCall(call, metadata, responseObserver);
+ requestObserver.onNext(request);
+ requestObserver.onCompleted();
+ }
+
+ public static StreamObserver<Object> streamCall(ClientCall call,
+ RequestMetadata metadata,
+ StreamObserver<Object> responseObserver
+ ) {
+ if (responseObserver instanceof CancelableStreamObserver) {
+ final CancellationContext context = new CancellationContext();
+ ((CancelableStreamObserver<Object>) responseObserver).setCancellationContext(context);
+ context.addListener(context1 -> call.cancel("Canceled by app", null));
+ }
+ ObserverToClientCallListenerAdapter listener = new ObserverToClientCallListenerAdapter(responseObserver, new ClientCallToObserverAdapter<>(call));
+ return call(call, metadata, listener);
+ }
+
+ public static void unaryCall(ClientCall call, RequestMetadata metadata) {
+ final UnaryCallListener listener = new UnaryCallListener(metadata.requestId, call);
+ final StreamObserver<Object> requestObserver = call(call, metadata, listener);
+ Object argument;
+ if (metadata.method.isNeedWrap()) {
+ argument = metadata.arguments;
+ } else {
+ argument = metadata.arguments[0];
+ }
+ requestObserver.onNext(argument);
+ requestObserver.onCompleted();
+ DefaultFuture2.sent(metadata.requestId);
+ }
+
+ public static StreamObserver<Object> call(ClientCall call, RequestMetadata metadata,
+ ClientCall.StartListener responseListener) {
+
+ if (metadata.method.isNeedWrap()) {
+ return wrapperCall(call, metadata, responseListener);
+ }
+ return callDirectly(call, metadata, responseListener);
+ }
+
+ public static StreamObserver<Object> wrapperCall(ClientCall call, RequestMetadata metadata,
+ ClientCall.StartListener responseListener) {
+ final StreamObserver<Object> requestObserver = WrapperRequestObserver.wrap(new ClientCallToObserverAdapter<>(call),
+ metadata.method.getCompatibleParamSignatures(), metadata.genericPack);
+ final ClientCall.StartListener wrapResponseListener = WrapResponseCallListener.wrap(responseListener, metadata.genericUnpack);
+ call.start(metadata, wrapResponseListener);
+ return requestObserver;
+ }
+
+ public static StreamObserver<Object> callDirectly(ClientCall call, RequestMetadata metadata, ClientCall.StartListener responseListener) {
+ final ClientCallToObserverAdapter<Object> requestObserver = new ClientCallToObserverAdapter<>(call);
+ call.start(metadata, responseListener);
+ return requestObserver;
+ }
+
+ static void cancelByThrowable(ClientCall call, Throwable t) {
+ try {
+ call.cancel("Canceled by error", t);
+ } catch (Throwable t1) {
+ LOGGER.error("Cancel triple request failed", t1);
+ }
+ }
+}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/ObserverToClientCallListenerAdapter.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/ObserverToClientCallListenerAdapter.java
new file mode 100644
index 0000000..f3d20ae
--- /dev/null
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/ObserverToClientCallListenerAdapter.java
@@ -0,0 +1,56 @@
+/*
+ * 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.protocol.tri.RpcStatus;
+import org.apache.dubbo.rpc.protocol.tri.observer.ClientCallToObserverAdapter;
+
+import java.util.Map;
+
+public class ObserverToClientCallListenerAdapter implements ClientCall.StartListener {
+ private final StreamObserver<Object> delegate;
+ private final ClientCallToObserverAdapter<Object> adapter;
+
+ public ObserverToClientCallListenerAdapter(StreamObserver<Object> delegate, ClientCallToObserverAdapter<Object> adapter) {
+ this.delegate = delegate;
+ this.adapter = adapter;
+ }
+
+ @Override
+ public void onMessage(Object message) {
+ delegate.onNext(message);
+ if (adapter.isAutoRequestEnabled()) {
+ adapter.request(1);
+ }
+ }
+
+ @Override
+ public void onClose(RpcStatus status, Map<String, Object> trailers) {
+ if (status.isOk()) {
+ delegate.onCompleted();
+ } else {
+ delegate.onError(status.asException());
+ }
+ }
+
+ @Override
+ public void onStart() {
+ adapter.request(1);
+ }
+}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/ServerCall.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/ServerCall.java
new file mode 100644
index 0000000..2693589
--- /dev/null
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/ServerCall.java
@@ -0,0 +1,455 @@
+/*
+ * 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.URL;
+import org.apache.dubbo.common.constants.CommonConstants;
+import org.apache.dubbo.common.logger.Logger;
+import org.apache.dubbo.common.logger.LoggerFactory;
+import org.apache.dubbo.common.threadpool.serial.SerializingExecutor;
+import org.apache.dubbo.common.utils.CollectionUtils;
+import org.apache.dubbo.common.utils.StringUtils;
+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.FrameworkServiceRepository;
+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.model.StreamMethodDescriptor;
+import org.apache.dubbo.rpc.protocol.tri.ClassLoadUtil;
+import org.apache.dubbo.rpc.protocol.tri.PathResolver;
+import org.apache.dubbo.rpc.protocol.tri.RpcStatus;
+import org.apache.dubbo.rpc.protocol.tri.TripleConstant;
+import org.apache.dubbo.rpc.protocol.tri.TripleHeaderEnum;
+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.pack.GenericUnpack;
+import org.apache.dubbo.rpc.protocol.tri.pack.PbPack;
+import org.apache.dubbo.rpc.protocol.tri.pack.PbUnpack;
+import org.apache.dubbo.rpc.protocol.tri.stream.ServerStream;
+import org.apache.dubbo.rpc.protocol.tri.stream.ServerStreamListener;
+import org.apache.dubbo.rpc.service.ServiceDescriptorInternalCache;
+import org.apache.dubbo.triple.TripleWrapper;
+
+import com.google.protobuf.InvalidProtocolBufferException;
+import io.netty.handler.codec.http.HttpHeaderNames;
+import io.netty.handler.codec.http2.DefaultHttp2Headers;
+import io.netty.handler.codec.http2.Http2Headers;
+
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.concurrent.Executor;
+import java.util.concurrent.TimeUnit;
+
+import static io.netty.handler.codec.http.HttpResponseStatus.OK;
+
+public class ServerCall {
+ private static final Logger LOGGER = LoggerFactory.getLogger(ServerCall.class);
+
+ public final ServerStreamListener streamListener = new ServerStreamListenerImpl();
+ private final List<HeaderFilter> headerFilters;
+ private final GenericUnpack genericUnpack;
+ private final FrameworkModel frameworkModel;
+ private final ServerStream serverStream;
+ private final Executor executor;
+ private final String methodName;
+ private final String serviceName;
+ private final PathResolver pathResolver;
+ public String serializerType;
+ public boolean autoRequestN = true;
+ public Long timeout;
+ private Invoker<?> invoker;
+ private ServiceDescriptor serviceDescriptor;
+ private PbUnpack<?> unpack;
+ private PbPack pack;
+ private ProviderModel providerModel;
+ private List<MethodDescriptor> methodDescriptors;
+ private RpcInvocation invocation;
+ private Listener listener;
+ private boolean headerSent;
+ private Compressor compressor;
+
+ public ServerCall(ServerStream serverStream,
+ FrameworkModel frameworkModel,
+ String serviceName,
+ String methodName,
+ Executor executor,
+ List<HeaderFilter> headerFilters,
+ GenericUnpack genericUnpack,
+ PathResolver pathResolver
+ ) {
+ this.executor = new SerializingExecutor(executor);
+ this.frameworkModel = frameworkModel;
+ this.methodName = methodName;
+ this.serviceName = serviceName;
+ this.serverStream = serverStream;
+ this.headerFilters = headerFilters;
+ this.genericUnpack = genericUnpack;
+ this.pathResolver = pathResolver;
+ }
+
+ private void sendHeader() {
+ if (headerSent) {
+ throw new IllegalStateException("Header has already sent");
+ }
+ headerSent = true;
+ final DefaultHttp2Headers headers = TripleConstant.createSuccessHttp2Headers();
+ if (compressor != null) {
+ headers.set(TripleHeaderEnum.GRPC_ENCODING.getHeader(), compressor.getMessageEncoding());
+ }
+ serverStream.sendHeader(headers);
+ }
+
+ public void requestN(int n) {
+ serverStream.requestN(n);
+ }
+
+ public void setCompression(String compression) {
+ if (headerSent) {
+ throw new IllegalStateException("Can not set compression after header sent");
+ }
+ this.compressor = Compressor.getCompressor(frameworkModel, compression);
+ }
+
+ public void disableAutoRequestN() {
+ autoRequestN = false;
+ }
+
+
+ public boolean isAutoRequestN() {
+ return autoRequestN;
+ }
+
+ public void writeMessage(Object message) {
+ final Runnable writeMessage = () -> {
+ if (!headerSent) {
+ sendHeader();
+ }
+ final byte[] data;
+ try {
+ data = pack.pack(message);
+ } catch (IOException e) {
+ close(RpcStatus.INTERNAL
+ .withDescription("Serialize response failed")
+ .withCause(e), null);
+ return;
+ }
+ if (data == null) {
+ close(RpcStatus.INTERNAL
+ .withDescription("Missing response"), null);
+ return;
+ }
+ if (compressor != null) {
+ int compressedFlag = Identity.MESSAGE_ENCODING.equals(compressor.getMessageEncoding()) ? 0 : 1;
+ final byte[] compressed = compressor.compress(data);
+ serverStream.writeMessage(compressed, compressedFlag);
+ } else {
+ serverStream.writeMessage(data, 0);
+ }
+ };
+ executor.execute(writeMessage);
+ }
+
+
+ public void close(RpcStatus status, Map<String, Object> trailers) {
+ executor.execute(() -> serverStream.close(status, trailers));
+ }
+
+ private Invoker<?> getInvoker(Map<String, Object> headers, String serviceName) {
+ final String version = headers.containsKey(TripleHeaderEnum.SERVICE_VERSION.getHeader()) ? headers.get(
+ TripleHeaderEnum.SERVICE_VERSION.getHeader()).toString() : null;
+ final String group = headers.containsKey(TripleHeaderEnum.SERVICE_GROUP.getHeader()) ? headers.get(TripleHeaderEnum.SERVICE_GROUP.getHeader())
+ .toString() : null;
+ final String key = URL.buildKey(serviceName, group, version);
+ Invoker<?> invoker = pathResolver.resolve(key);
+ if (invoker == null) {
+ invoker = pathResolver.resolve(URL.buildKey(serviceName, group, "1.0.0"));
+ }
+ if (invoker == null) {
+ invoker = pathResolver.resolve(serviceName);
+ }
+ return invoker;
+ }
+
+
+ private boolean isEcho(String methodName) {
+ return CommonConstants.$ECHO.equals(methodName);
+ }
+
+ private boolean isGeneric(String methodName) {
+ return CommonConstants.$INVOKE.equals(methodName) || CommonConstants.$INVOKE_ASYNC.equals(methodName);
+ }
+
+ protected Long parseTimeoutToMills(String timeoutVal) {
+ if (StringUtils.isEmpty(timeoutVal) || StringUtils.isContains(timeoutVal, "null")) {
+ return null;
+ }
+ long value = Long.parseLong(timeoutVal.substring(0, timeoutVal.length() - 1));
+ char unit = timeoutVal.charAt(timeoutVal.length() - 1);
+ switch (unit) {
+ case 'n':
+ return TimeUnit.NANOSECONDS.toMillis(value);
+ case 'u':
+ return TimeUnit.MICROSECONDS.toMillis(value);
+ case 'm':
+ return value;
+ case 'S':
+ return TimeUnit.SECONDS.toMillis(value);
+ case 'M':
+ return TimeUnit.MINUTES.toMillis(value);
+ case 'H':
+ return TimeUnit.HOURS.toMillis(value);
+ default:
+ // invalid timeout config
+ return null;
+ }
+ }
+
+
+ interface Listener {
+
+ void onMessage(Object message);
+
+ void onCancel(String errorInfo);
+
+ void onComplete();
+ }
+
+ class ServerStreamListenerImpl implements ServerStreamListener {
+
+ private MethodDescriptor methodDescriptor;
+ private Map<String, Object> headers;
+ private boolean closed;
+
+
+ @Override
+ public void onHeaders(Map<String, Object> headers) {
+ this.headers = headers;
+ try {
+ doOnHeaders(headers);
+ } catch (Throwable t) {
+ responseErr(RpcStatus.UNKNOWN
+ .withDescription("Server exception")
+ .withCause(t));
+ }
+ }
+
+ private void doOnHeaders(Map<String, Object> headers) {
+ invoker = getInvoker(headers, serviceName);
+ if (invoker == null) {
+ responseErr(RpcStatus.UNIMPLEMENTED
+ .withDescription("Service not found:" + serviceName));
+ return;
+ }
+ FrameworkServiceRepository repo = frameworkModel.getServiceRepository();
+ providerModel = repo.lookupExportedService(invoker.getUrl().getServiceKey());
+ if (providerModel == null || providerModel.getServiceModel() == null) {
+ responseErr(RpcStatus.UNIMPLEMENTED
+ .withDescription("Service not found:" + serviceName));
+ return;
+ }
+ serviceDescriptor = providerModel.getServiceModel();
+
+ 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
+ methodDescriptor = ServiceDescriptorInternalCache.echoService().getMethods(methodName).get(0);
+ } else {
+ methodDescriptors = providerModel.getServiceModel().getMethods(methodName);
+ // try upper-case method
+ if (CollectionUtils.isEmpty(methodDescriptors)) {
+ final String upperMethod = Character.toUpperCase(methodName.charAt(0)) + methodName.substring(1);
+ methodDescriptors = providerModel.getServiceModel().getMethods(upperMethod);
+ }
+ if (CollectionUtils.isEmpty(methodDescriptors)) {
+ responseErr(RpcStatus.UNIMPLEMENTED
+ .withDescription("Method : " + methodName + " not found of service:" + serviceName));
+ return;
+ }
+ // In most cases there is only one method
+ if (methodDescriptors.size() == 1) {
+ methodDescriptor = methodDescriptors.get(0);
+ }
+ }
+ trySetUnpack();
+ pack = PbPack.INSTANCE;
+ trySetListener();
+ if (listener == null) {
+ // wrap request , need one message
+ requestN(1);
+ }
+ }
+
+ private void trySetUnpack() {
+ if (methodDescriptor == null) {
+ return;
+ }
+ if (unpack != null) {
+ return;
+ }
+ if (methodDescriptor.isNeedWrap()) {
+ unpack = PbUnpack.REQ_PB_UNPACK;
+ } else {
+ if (methodDescriptor instanceof StreamMethodDescriptor) {
+ unpack = new PbUnpack<>(((StreamMethodDescriptor) methodDescriptor).requestType);
+ } else {
+ unpack = new PbUnpack<>(methodDescriptor.getParameterClasses()[0]);
+ }
+ }
+ }
+
+ private void trySetMethodDescriptor(byte[] data) throws InvalidProtocolBufferException {
+ if (methodDescriptor != null) {
+ return;
+ }
+ final TripleWrapper.TripleRequestWrapper request;
+ request = TripleWrapper.TripleRequestWrapper.parseFrom(data);
+
+ final String[] paramTypes = request.getArgTypesList().toArray(new String[request.getArgsCount()]);
+ // 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) {
+ close(RpcStatus.UNIMPLEMENTED
+ .withDescription("Method :" + methodName + "[" + Arrays.toString(paramTypes) + "] " +
+ "not found of service:" + serviceDescriptor.getInterfaceName()), null);
+ }
+ }
+
+ private void trySetListener() {
+ if (listener != null) {
+ return;
+ }
+ if (methodDescriptor == null) {
+ return;
+ }
+ if (closed) {
+ return;
+ }
+ invocation = buildInvocation(headers);
+ if (closed) {
+ return;
+ }
+ headerFilters.forEach(f -> f.invoke(invoker, invocation));
+ if (closed) {
+ return;
+ }
+ listener = ServerCallUtil.startCall(ServerCall.this, invocation, methodDescriptor, genericUnpack, invoker);
+ if (listener == null) {
+ closed = true;
+ }
+ }
+
+ /**
+ * Error in create stream, unsupported config or triple protocol error.
+ *
+ * @param status response status
+ */
+ private void responseErr(RpcStatus status) {
+ if (closed) {
+ return;
+ }
+ closed = true;
+ Http2Headers trailers = new DefaultHttp2Headers()
+ .status(OK.codeAsText())
+ .set(HttpHeaderNames.CONTENT_TYPE, TripleConstant.CONTENT_PROTO)
+ .setInt(TripleHeaderEnum.STATUS_KEY.getHeader(), status.code.code)
+ .set(TripleHeaderEnum.MESSAGE_KEY.getHeader(), status.toEncodedMessage());
+ serverStream.sendHeaderWithEos(trailers);
+ LOGGER.error("Triple request error: service=" + serviceName + " method" + methodName, status.asException());
+ }
+
+ @Override
+ public void complete() {
+ if (listener != null) {
+ listener.onComplete();
+ }
+ }
+
+ @Override
+ public void cancel(RpcStatus status) {
+ listener.onCancel(status.description);
+ }
+
+ @Override
+ public void onMessage(byte[] message) {
+ if (closed) {
+ return;
+ }
+ ClassLoader tccl = Thread.currentThread().getContextClassLoader();
+ try {
+ trySetMethodDescriptor(message);
+ trySetUnpack();
+ trySetListener();
+ if (providerModel != null) {
+ ClassLoadUtil.switchContextLoader(providerModel.getServiceInterfaceClass().getClassLoader());
+ }
+ final Object obj = unpack.unpack(message);
+ listener.onMessage(obj);
+ } catch (Throwable t) {
+ final RpcStatus status = RpcStatus.INTERNAL.withDescription("Server error")
+ .withCause(t);
+ close(status, null);
+ LOGGER.error("Process request failed. service=" + serviceName + " method=" + methodName, t);
+ } finally {
+ ClassLoadUtil.switchContextLoader(tccl);
+ }
+ }
+
+ /**
+ * Build the RpcInvocation with metadata and execute headerFilter
+ *
+ * @param headers request header
+ * @return RpcInvocation
+ */
+ protected RpcInvocation buildInvocation(Map<String, Object> headers) {
+ final URL url = invoker.getUrl();
+ RpcInvocation inv = new RpcInvocation(url.getServiceModel(),
+ methodName, serviceDescriptor.getInterfaceName(),
+ url.getProtocolServiceKey(), methodDescriptor.getParameterClasses(), new Object[0]);
+ inv.setTargetServiceUniqueName(url.getServiceKey());
+ inv.setReturnTypes(methodDescriptor.getReturnTypes());
+
+ inv.setObjectAttachments(headers);
+ // handle timeout
+ String timeout = (String) headers.get(TripleHeaderEnum.TIMEOUT.getHeader());
+ try {
+ if (Objects.nonNull(timeout)) {
+ ServerCall.this.timeout = parseTimeoutToMills(timeout);
+ }
+ } catch (Throwable t) {
+ LOGGER.warn(String.format("Failed to parse request timeout set from:%s, service=%s method=%s",
+ timeout, serviceDescriptor.getInterfaceName(), methodName));
+ }
+ return inv;
+ }
+ }
+
+}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/ServerCallUtil.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/ServerCallUtil.java
new file mode 100644
index 0000000..e2426b9
--- /dev/null
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/ServerCallUtil.java
@@ -0,0 +1,95 @@
+/*
+ * 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.rpc.CancellationContext;
+import org.apache.dubbo.rpc.Invoker;
+import org.apache.dubbo.rpc.RpcContext;
+import org.apache.dubbo.rpc.RpcInvocation;
+import org.apache.dubbo.rpc.model.MethodDescriptor;
+import org.apache.dubbo.rpc.model.StreamMethodDescriptor;
+import org.apache.dubbo.rpc.protocol.tri.RpcStatus;
+import org.apache.dubbo.rpc.protocol.tri.observer.ServerCallToObserverAdapter;
+import org.apache.dubbo.rpc.protocol.tri.observer.WrapperResponseObserver;
+import org.apache.dubbo.rpc.protocol.tri.pack.GenericUnpack;
+
+public class ServerCallUtil {
+
+ public static ServerCall.Listener startCall(ServerCall call,
+ RpcInvocation invocation,
+ MethodDescriptor methodDescriptor,
+ GenericUnpack genericUnpack,
+ Invoker<?> invoker) {
+ if (methodDescriptor.isNeedWrap()) {
+ return startWrapCall(call, invocation, methodDescriptor, genericUnpack, invoker);
+ } else {
+ return startDirectCall(call, invocation, methodDescriptor, invoker);
+ }
+ }
+
+ public static ServerCall.Listener startDirectCall(ServerCall call,
+ RpcInvocation invocation,
+ MethodDescriptor methodDescriptor,
+ Invoker<?> invoker) {
+ CancellationContext cancellationContext = RpcContext.getCancellationContext();
+ ServerCallToObserverAdapter<Object> responseObserver = new ServerCallToObserverAdapter<>(call, cancellationContext);
+ return startCall(call, methodDescriptor, invocation, invoker, responseObserver);
+ }
+
+
+ public static ServerCall.Listener startWrapCall(ServerCall call,
+ RpcInvocation invocation,
+ MethodDescriptor methodDescriptor,
+ GenericUnpack genericUnpack,
+ Invoker<?> invoker) {
+ CancellationContext cancellationContext = RpcContext.getCancellationContext();
+ final String returnClass = methodDescriptor.getReturnClass().getName();
+ ServerCallToObserverAdapter<Object> responseObserver = new WrapperResponseObserver<>(call,
+ cancellationContext, returnClass, genericUnpack.serialization, invoker.getUrl());
+ final ServerCall.Listener listener = startCall(call, methodDescriptor, invocation, invoker, responseObserver);
+ return new WrapRequestServerCallListener(call, listener, genericUnpack);
+ }
+
+ public static ServerCall.Listener startCall(ServerCall call,
+ MethodDescriptor methodDescriptor,
+ RpcInvocation invocation,
+ Invoker<?> invoker,
+ ServerCallToObserverAdapter<Object> responseObserver) {
+ try {
+ ServerCall.Listener listener;
+ if (methodDescriptor instanceof StreamMethodDescriptor) {
+ if (((StreamMethodDescriptor) methodDescriptor).isServerStream()) {
+ listener = new ServerStreamServerCallListener(invocation, invoker, responseObserver);
+ } else {
+ listener = new BiStreamServerCallListener(invocation, invoker, responseObserver);
+ }
+ call.requestN(1);
+ } else {
+ listener = new UnaryServerCallListener(invocation, invoker, responseObserver);
+ call.requestN(2);
+ }
+ return listener;
+ } catch (Throwable t) {
+ responseObserver.onError(RpcStatus.INTERNAL.withDescription("Create stream failed")
+ .withCause(t)
+ .asException());
+ }
+ return null;
+ }
+}
+
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/ServerStreamServerCallListener.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/ServerStreamServerCallListener.java
new file mode 100644
index 0000000..06ff167
--- /dev/null
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/ServerStreamServerCallListener.java
@@ -0,0 +1,55 @@
+/*
+ * 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.rpc.Invoker;
+import org.apache.dubbo.rpc.RpcInvocation;
+import org.apache.dubbo.rpc.protocol.tri.RpcStatus;
+import org.apache.dubbo.rpc.protocol.tri.observer.ServerCallToObserverAdapter;
+
+public class ServerStreamServerCallListener extends AbstractServerCallListener {
+
+ public ServerStreamServerCallListener(RpcInvocation invocation, Invoker<?> invoker,
+ ServerCallToObserverAdapter<Object> responseObserver) {
+ super(invocation, invoker, responseObserver);
+ }
+
+ @Override
+ public void onMessage(Object message) {
+ if (message instanceof Object[]) {
+ message = ((Object[]) message)[0];
+ }
+ invocation.setArguments(new Object[]{message, responseObserver});
+ }
+
+
+ @Override
+ public void onCancel(String errorInfo) {
+ responseObserver.cancel(RpcStatus.CANCELLED.withDescription(errorInfo).asException());
+ }
+
+
+ @Override
+ public void onComplete() {
+ try {
+ invoke();
+ } catch (Throwable e) {
+ responseObserver.onCompleted(RpcStatus.getStatus(e));
+ }
+ }
+}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/UnaryCallListener.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/UnaryCallListener.java
new file mode 100644
index 0000000..e0224cf
--- /dev/null
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/UnaryCallListener.java
@@ -0,0 +1,57 @@
+/*
+ * 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.rpc.AppResponse;
+import org.apache.dubbo.rpc.protocol.tri.DefaultFuture2;
+import org.apache.dubbo.rpc.protocol.tri.RpcStatus;
+
+import java.util.Map;
+
+public class UnaryCallListener implements ClientCall.StartListener {
+ private final long requestId;
+ private final ClientCall call;
+ private Object appResponse;
+
+ public UnaryCallListener(long requestId, ClientCall call) {
+ this.requestId = requestId;
+ this.call = call;
+ }
+
+ @Override
+ public void onMessage(Object message) {
+ this.appResponse = message;
+ }
+
+ @Override
+ public void onClose(RpcStatus status, Map<String, Object> trailers) {
+ AppResponse result = new AppResponse();
+ result.setObjectAttachments(trailers);
+ if (status.isOk()) {
+ result.setValue(appResponse);
+ } else {
+ result.setException(status.asException());
+ }
+ DefaultFuture2.received(requestId, status, result);
+ }
+
+ @Override
+ public void onStart() {
+ call.requestN(2);
+ }
+}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/UnaryServerCallListener.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/UnaryServerCallListener.java
new file mode 100644
index 0000000..7f8e794
--- /dev/null
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/UnaryServerCallListener.java
@@ -0,0 +1,62 @@
+/*
+ * 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.Logger;
+import org.apache.dubbo.common.logger.LoggerFactory;
+import org.apache.dubbo.rpc.Invoker;
+import org.apache.dubbo.rpc.RpcInvocation;
+import org.apache.dubbo.rpc.protocol.tri.RpcStatus;
+import org.apache.dubbo.rpc.protocol.tri.observer.ServerCallToObserverAdapter;
+
+public class UnaryServerCallListener extends AbstractServerCallListener implements ServerCall.Listener {
+ private static final Logger LOGGER = LoggerFactory.getLogger(ServerCall.class);
+
+ public UnaryServerCallListener(RpcInvocation invocation, Invoker<?> invoker,
+ ServerCallToObserverAdapter<Object> responseObserver) {
+ super(invocation, invoker, responseObserver);
+ }
+
+ @Override
+ public void onMessage(Object message) {
+ if (message instanceof Object[]) {
+ invocation.setArguments((Object[]) message);
+ } else {
+ invocation.setArguments(new Object[]{message});
+ }
+ }
+
+
+ @Override
+ public void onCancel(String errorInfo) {
+ // ignored
+ }
+
+ @Override
+ public void onComplete() {
+ try {
+ responseObserver.onNext(invoke());
+ responseObserver.onCompleted(RpcStatus.OK);
+ } catch (Throwable e) {
+ responseObserver.onCompleted(RpcStatus.getStatus(e));
+ LOGGER.error("Invoke service=" + invocation.getTargetServiceUniqueName() + " method= "
+ + invocation.getMethodName() + "failed. Internal error", e);
+ }
+ }
+
+}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/WrapRequestServerCallListener.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/WrapRequestServerCallListener.java
new file mode 100644
index 0000000..2f7a827
--- /dev/null
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/WrapRequestServerCallListener.java
@@ -0,0 +1,51 @@
+/*
+ * 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.rpc.protocol.tri.pack.GenericUnpack;
+import org.apache.dubbo.rpc.protocol.tri.pack.WrapRequestUnpack;
+import org.apache.dubbo.triple.TripleWrapper;
+
+public class WrapRequestServerCallListener implements ServerCall.Listener {
+ private final ServerCall.Listener delegate;
+ private final WrapRequestUnpack unpack;
+ private final ServerCall call;
+
+ public WrapRequestServerCallListener(ServerCall call, ServerCall.Listener delegate, GenericUnpack unpack) {
+ this.delegate = delegate;
+ this.call = call;
+ this.unpack = new WrapRequestUnpack(unpack);
+ }
+
+ @Override
+ public void onMessage(Object message) {
+ final Object args = this.unpack.unpack((TripleWrapper.TripleRequestWrapper) message);
+ call.serializerType = ((TripleWrapper.TripleRequestWrapper) message).getSerializeType();
+ delegate.onMessage(args);
+ }
+
+ @Override
+ public void onCancel(String errorInfo) {
+ delegate.onCancel(errorInfo);
+ }
+
+ @Override
+ public void onComplete() {
+ delegate.onComplete();
+ }
+}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/WrapResponseCallListener.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/WrapResponseCallListener.java
new file mode 100644
index 0000000..2c46222
--- /dev/null
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/WrapResponseCallListener.java
@@ -0,0 +1,62 @@
+/*
+ * 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.rpc.protocol.tri.RpcStatus;
+import org.apache.dubbo.rpc.protocol.tri.pack.GenericUnpack;
+import org.apache.dubbo.rpc.protocol.tri.pack.WrapResponseUnpack;
+import org.apache.dubbo.triple.TripleWrapper;
+
+import java.util.Map;
+
+public class WrapResponseCallListener implements ClientCall.StartListener {
+ private final ClientCall.StartListener delegate;
+ private final WrapResponseUnpack responseUnpack;
+
+ protected WrapResponseCallListener(ClientCall.StartListener delegate, GenericUnpack genericUnpack) {
+ this.delegate = delegate;
+ this.responseUnpack = new WrapResponseUnpack(genericUnpack);
+ }
+
+ public static ClientCall.StartListener wrap(ClientCall.StartListener listener, GenericUnpack genericUnpack) {
+ return new WrapResponseCallListener(listener, genericUnpack);
+ }
+
+ @Override
+ public void onMessage(Object message) {
+ try {
+ final Object unpack = responseUnpack.unpack((TripleWrapper.TripleResponseWrapper) message);
+ delegate.onMessage(unpack);
+ } catch (Throwable t) {
+ final RpcStatus status = RpcStatus.INTERNAL
+ .withDescription("Failed deserialize response")
+ .withCause(t);
+ onClose(status, null);
+ }
+ }
+
+ @Override
+ public void onClose(RpcStatus status, Map<String, Object> trailers) {
+ delegate.onClose(status, trailers);
+ }
+
+ @Override
+ public void onStart() {
+ delegate.onStart();
+ }
+}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/CancelQueueCommand.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/CancelQueueCommand.java
index b7d89f7..0c64ff1 100644
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/CancelQueueCommand.java
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/CancelQueueCommand.java
@@ -17,23 +17,15 @@
package org.apache.dubbo.rpc.protocol.tri.command;
-import org.apache.dubbo.rpc.protocol.tri.GrpcStatus;
-
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 QueuedCommand.AbstractQueuedCommand {
-
- private final GrpcStatus status;
-
- private CancelQueueCommand(GrpcStatus status) {
- this.status = status;
- }
+public class CancelQueueCommand extends QueuedCommand {
- public static CancelQueueCommand createCommand(GrpcStatus status) {
- return new CancelQueueCommand(status);
+ public static CancelQueueCommand createCommand() {
+ return new CancelQueueCommand();
}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/DataQueueCommand.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/DataQueueCommand.java
index b054af2..6ab6834 100644
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/DataQueueCommand.java
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/DataQueueCommand.java
@@ -17,44 +17,27 @@
package org.apache.dubbo.rpc.protocol.tri.command;
-import org.apache.dubbo.rpc.protocol.tri.AbstractStream;
-import org.apache.dubbo.rpc.protocol.tri.Compressor;
-import org.apache.dubbo.rpc.protocol.tri.IdentityCompressor;
-import org.apache.dubbo.rpc.protocol.tri.TripleConstant;
-
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 QueuedCommand.AbstractQueuedCommand {
+public class DataQueueCommand extends QueuedCommand {
private final byte[] data;
- private final boolean endStream;
+ private final int compressFlag;
- private final boolean client;
+ private final boolean endStream;
- private DataQueueCommand(byte[] data, boolean endStream, boolean client) {
+ private DataQueueCommand(byte[] data, int compressFlag, boolean endStream) {
this.data = data;
+ this.compressFlag = compressFlag;
this.endStream = endStream;
- this.client = client;
- }
-
- private DataQueueCommand(boolean endStream, boolean client) {
- this(null, endStream, client);
- }
-
- private DataQueueCommand(boolean endStream) {
- this(null, endStream, false);
}
- public static DataQueueCommand createGrpcCommand(byte[] data, boolean endStream, boolean client) {
- return new DataQueueCommand(data, endStream, client);
- }
-
- public static DataQueueCommand createGrpcCommand(boolean endStream) {
- return new DataQueueCommand(endStream);
+ public static DataQueueCommand createGrpcCommand(byte[] data, boolean endStream, int compressFlag) {
+ return new DataQueueCommand(data, compressFlag, endStream);
}
@Override
@@ -63,7 +46,7 @@ public class DataQueueCommand extends QueuedCommand.AbstractQueuedCommand {
ctx.write(new DefaultHttp2DataFrame(endStream), promise);
} else {
ByteBuf buf = ctx.alloc().buffer();
- buf.writeByte(getCompressFlag(ctx));
+ buf.writeByte(compressFlag);
buf.writeInt(data.length);
buf.writeBytes(data);
ctx.write(new DefaultHttp2DataFrame(buf, endStream), promise);
@@ -71,17 +54,18 @@ public class DataQueueCommand extends QueuedCommand.AbstractQueuedCommand {
}
private int getCompressFlag(ChannelHandlerContext ctx) {
- AbstractStream stream = client ? ctx.channel().attr(TripleConstant.CLIENT_STREAM_KEY).get() : ctx.channel().attr(TripleConstant.SERVER_STREAM_KEY).get();
- return calcCompressFlag(stream.getCompressor());
- }
+// AbstractStream stream = client ? ctx.channel().attr(TripleConstant.CLIENT_STREAM_KEY).get() : ctx.channel().attr(TripleConstant.SERVER_STREAM_KEY).get();
+// return calcCompressFlag(stream.getCompressor());
+ // todo
- protected int calcCompressFlag(Compressor compressor) {
- if (null == compressor || IdentityCompressor.NONE.getMessageEncoding().equals(compressor.getMessageEncoding())) {
- return 0;
- }
- return 1;
+ return 0;
}
+// protected int calcCompressFlag(Compressor compressor) {
+//
+// return 1;
+// }
+
// for test
public byte[] getData() {
return data;
@@ -93,7 +77,7 @@ public class DataQueueCommand extends QueuedCommand.AbstractQueuedCommand {
}
// for test
- public boolean isClient() {
- return client;
- }
+// public boolean isClient() {
+// return client;
+// }
}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/FlushQueueCommand.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/EndStreamQueueCommand.java
similarity index 79%
copy from dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/FlushQueueCommand.java
copy to dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/EndStreamQueueCommand.java
index 9563056..77713cf 100644
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/FlushQueueCommand.java
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/EndStreamQueueCommand.java
@@ -19,11 +19,16 @@ package org.apache.dubbo.rpc.protocol.tri.command;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
+import io.netty.handler.codec.http2.DefaultHttp2DataFrame;
-public class FlushQueueCommand extends QueuedCommand.AbstractQueuedCommand {
+public class EndStreamQueueCommand extends QueuedCommand {
+
+ public static EndStreamQueueCommand create() {
+ return new EndStreamQueueCommand();
+ }
@Override
public void doSend(ChannelHandlerContext ctx, ChannelPromise promise) {
- ctx.flush();
+ ctx.write(new DefaultHttp2DataFrame(true));
}
}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/FlushQueueCommand.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/FlushQueueCommand.java
index 9563056..a260ae0 100644
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/FlushQueueCommand.java
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/FlushQueueCommand.java
@@ -20,7 +20,7 @@ package org.apache.dubbo.rpc.protocol.tri.command;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
-public class FlushQueueCommand extends QueuedCommand.AbstractQueuedCommand {
+public class FlushQueueCommand extends QueuedCommand {
@Override
public void doSend(ChannelHandlerContext ctx, ChannelPromise promise) {
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/HeaderQueueCommand.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/HeaderQueueCommand.java
index 4936a28..1b5b14d 100644
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/HeaderQueueCommand.java
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/HeaderQueueCommand.java
@@ -17,37 +17,22 @@
package org.apache.dubbo.rpc.protocol.tri.command;
-import org.apache.dubbo.rpc.protocol.tri.Metadata;
-
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
-import io.netty.handler.codec.http2.DefaultHttp2Headers;
import io.netty.handler.codec.http2.DefaultHttp2HeadersFrame;
import io.netty.handler.codec.http2.Http2Headers;
-public class HeaderQueueCommand extends QueuedCommand.AbstractQueuedCommand {
+public class HeaderQueueCommand extends QueuedCommand {
private final Http2Headers headers;
private final boolean endStream;
- private HeaderQueueCommand(Metadata headers, boolean endStream) {
- this(getHttp2Headers(headers), endStream);
- }
-
private HeaderQueueCommand(Http2Headers headers, boolean endStream) {
this.headers = headers;
this.endStream = endStream;
}
- public static HeaderQueueCommand createHeaders(Metadata headers, boolean endStream) {
- return new HeaderQueueCommand(getHttp2Headers(headers), endStream);
- }
-
- public static HeaderQueueCommand createHeaders(Metadata headers) {
- return new HeaderQueueCommand(headers, false);
- }
-
public static HeaderQueueCommand createHeaders(Http2Headers headers) {
return new HeaderQueueCommand(headers, false);
}
@@ -56,10 +41,6 @@ public class HeaderQueueCommand extends QueuedCommand.AbstractQueuedCommand {
return new HeaderQueueCommand(headers, endStream);
}
- public static HeaderQueueCommand createTrailers(Metadata headers) {
- return new HeaderQueueCommand(headers, true);
- }
-
public Http2Headers getHeaders() {
return headers;
}
@@ -68,12 +49,6 @@ public class HeaderQueueCommand extends QueuedCommand.AbstractQueuedCommand {
return endStream;
}
- private static Http2Headers getHttp2Headers(Metadata metadata) {
- Http2Headers http2Headers = new DefaultHttp2Headers(true);
- metadata.forEach((kv) -> http2Headers.set(kv.getKey(), kv.getValue()));
- return http2Headers;
- }
-
@Override
public void doSend(ChannelHandlerContext ctx, ChannelPromise promise) {
ctx.write(new DefaultHttp2HeadersFrame(headers, endStream), promise);
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/QueuedCommand.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/QueuedCommand.java
index 7fb44de..a3dcb0b 100644
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/QueuedCommand.java
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/QueuedCommand.java
@@ -21,54 +21,33 @@ import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
-public interface QueuedCommand {
+public abstract class QueuedCommand {
- void setFlush(boolean flush);
+ private ChannelPromise promise;
- ChannelPromise promise();
-
- void promise(ChannelPromise promise);
-
- void run(Channel channel);
-
- abstract class AbstractQueuedCommand implements QueuedCommand {
-
- protected boolean flush = false;
- private ChannelPromise promise;
-
- @Override
- public ChannelPromise promise() {
- return promise;
- }
-
- public void setFlush(boolean flush) {
- this.flush = flush;
- }
+ public ChannelPromise promise() {
+ return promise;
+ }
- @Override
- public void promise(ChannelPromise promise) {
- this.promise = promise;
- }
+ public void promise(ChannelPromise promise) {
+ this.promise = promise;
+ }
- @Override
- public void run(Channel channel) {
- if (channel.isActive()) {
- channel.write(this, promise);
- } else {
- promise.trySuccess();
- }
+ public void run(Channel channel) {
+ if (channel.isActive()) {
+ channel.write(this, promise);
+ } else {
+ promise.trySuccess();
}
+ }
- public final void send(ChannelHandlerContext ctx, ChannelPromise promise) {
- if (ctx.channel().isActive()) {
- doSend(ctx, promise);
- if (flush) {
- ctx.flush();
- }
- }
+ public final void send(ChannelHandlerContext ctx, ChannelPromise promise) {
+ if (ctx.channel().isActive()) {
+ doSend(ctx, promise);
+ ctx.flush();
}
-
- public abstract void doSend(ChannelHandlerContext ctx, ChannelPromise promise);
}
+ public abstract void doSend(ChannelHandlerContext ctx, ChannelPromise promise);
}
+
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/TextDataQueueCommand.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/TextDataQueueCommand.java
index 547c747..4befbe6 100644
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/TextDataQueueCommand.java
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/TextDataQueueCommand.java
@@ -23,7 +23,7 @@ import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http2.DefaultHttp2DataFrame;
-public class TextDataQueueCommand extends QueuedCommand.AbstractQueuedCommand {
+public class TextDataQueueCommand extends QueuedCommand {
private final String data;
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/Compressor.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/compressor/Compressor.java
similarity index 76%
copy from dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/Compressor.java
copy to dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/compressor/Compressor.java
index 8410f75..1f4dc75 100644
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/Compressor.java
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/compressor/Compressor.java
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-package org.apache.dubbo.rpc.protocol.tri;
+package org.apache.dubbo.rpc.protocol.tri.compressor;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
@@ -25,25 +25,21 @@ import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.Set;
import java.util.stream.Collectors;
-import static org.apache.dubbo.rpc.protocol.tri.Compressor.DEFAULT_COMPRESSOR;
-
/**
* compress payload for grpc request, and decompress response payload
* Configure it in files, pictures or other configurations that exist in the system properties
* Configure {@link Constants#COMPRESSOR_KEY} in dubbo.properties、dubbo.yml or other configuration that exist in the system property
*/
-@SPI(value = DEFAULT_COMPRESSOR, scope = ExtensionScope.FRAMEWORK)
-public interface Compressor {
-
- Compressor NONE = new IdentityCompressor();
+@SPI(scope = ExtensionScope.FRAMEWORK)
+public interface Compressor extends MessageEncoding {
- String DEFAULT_COMPRESSOR = "identity";
+ Compressor NONE = Identity.IDENTITY;
static Compressor getCompressor(FrameworkModel frameworkModel, String compressorStr) {
if (null == compressorStr) {
return null;
}
- if (compressorStr.equals(DEFAULT_COMPRESSOR)) {
+ if (compressorStr.equals(Identity.MESSAGE_ENCODING)) {
return NONE;
}
return frameworkModel.getExtensionLoader(Compressor.class).getExtension(compressorStr);
@@ -58,13 +54,6 @@ public interface Compressor {
}
/**
- * message encoding of current compressor
- *
- * @return return message encoding
- */
- String getMessageEncoding();
-
- /**
* compress payload
*
* @param payloadByteArr payload byte array
@@ -72,11 +61,4 @@ public interface Compressor {
*/
byte[] compress(byte[] payloadByteArr);
- /**
- * decompress payload
- *
- * @param payloadByteArr payload byte array
- * @return decompressed payload byte array
- */
- byte[] decompress(byte[] payloadByteArr);
}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/Compressor.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/compressor/DeCompressor.java
similarity index 50%
rename from dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/Compressor.java
rename to dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/compressor/DeCompressor.java
index 8410f75..30ac539 100644
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/Compressor.java
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/compressor/DeCompressor.java
@@ -15,68 +15,45 @@
* limitations under the License.
*/
-package org.apache.dubbo.rpc.protocol.tri;
+package org.apache.dubbo.rpc.protocol.tri.compressor;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
-import org.apache.dubbo.rpc.Constants;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.Set;
import java.util.stream.Collectors;
-import static org.apache.dubbo.rpc.protocol.tri.Compressor.DEFAULT_COMPRESSOR;
+@SPI(scope = ExtensionScope.FRAMEWORK)
+public interface DeCompressor extends MessageEncoding {
-/**
- * compress payload for grpc request, and decompress response payload
- * Configure it in files, pictures or other configurations that exist in the system properties
- * Configure {@link Constants#COMPRESSOR_KEY} in dubbo.properties、dubbo.yml or other configuration that exist in the system property
- */
-@SPI(value = DEFAULT_COMPRESSOR, scope = ExtensionScope.FRAMEWORK)
-public interface Compressor {
-
- Compressor NONE = new IdentityCompressor();
+ DeCompressor NONE = Identity.IDENTITY;
- String DEFAULT_COMPRESSOR = "identity";
-
- static Compressor getCompressor(FrameworkModel frameworkModel, String compressorStr) {
+ static DeCompressor getCompressor(FrameworkModel frameworkModel, String compressorStr) {
if (null == compressorStr) {
return null;
}
- if (compressorStr.equals(DEFAULT_COMPRESSOR)) {
+ if (compressorStr.equals(Identity.MESSAGE_ENCODING)) {
return NONE;
}
- return frameworkModel.getExtensionLoader(Compressor.class).getExtension(compressorStr);
+ return frameworkModel.getExtensionLoader(DeCompressor.class).getExtension(compressorStr);
}
static String getAcceptEncoding(FrameworkModel frameworkModel) {
- Set<Compressor> supportedEncodingSet = frameworkModel.getExtensionLoader(Compressor.class).getSupportedExtensionInstances();
+ Set<DeCompressor> supportedEncodingSet = frameworkModel.getExtensionLoader(DeCompressor.class).getSupportedExtensionInstances();
if (supportedEncodingSet.isEmpty()) {
return null;
}
- return supportedEncodingSet.stream().map(Compressor::getMessageEncoding).collect(Collectors.joining(","));
+ return supportedEncodingSet.stream().map(DeCompressor::getMessageEncoding).collect(Collectors.joining(","));
}
/**
- * message encoding of current compressor
- *
- * @return return message encoding
- */
- String getMessageEncoding();
-
- /**
- * compress payload
- *
- * @param payloadByteArr payload byte array
- * @return compressed payload byte array
- */
- byte[] compress(byte[] payloadByteArr);
-
- /**
* decompress payload
*
* @param payloadByteArr payload byte array
* @return decompressed payload byte array
*/
byte[] decompress(byte[] payloadByteArr);
+
+
}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/GzipCompressor.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/compressor/Gzip.java
similarity index 89%
rename from dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/GzipCompressor.java
rename to dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/compressor/Gzip.java
index 546b76f..371b650 100644
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/GzipCompressor.java
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/compressor/Gzip.java
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-package org.apache.dubbo.rpc.protocol.tri;
+package org.apache.dubbo.rpc.protocol.tri.compressor;
import org.apache.dubbo.rpc.RpcException;
@@ -27,11 +27,13 @@ import java.util.zip.GZIPOutputStream;
/**
* gzip compressor
*/
-public class GzipCompressor implements Compressor {
+public class Gzip implements Compressor, DeCompressor {
+
+ public static final String GZIP = "gzip";
@Override
public String getMessageEncoding() {
- return "gzip";
+ return GZIP;
}
@Override
@@ -44,7 +46,7 @@ public class GzipCompressor implements Compressor {
try (GZIPOutputStream gzipOutputStream = new GZIPOutputStream(byteOutStream)) {
gzipOutputStream.write(payloadByteArr);
} catch (Exception exception) {
- throw new RpcException(exception);
+ throw new IllegalStateException(exception);
}
return byteOutStream.toByteArray();
@@ -65,7 +67,7 @@ public class GzipCompressor implements Compressor {
byteOutStream.write(bufferArr, 0, readByteNum);
}
} catch (Exception exception) {
- throw new RpcException(exception);
+ throw new IllegalStateException(exception);
}
return byteOutStream.toByteArray();
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/IdentityCompressor.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/compressor/Identity.java
similarity index 80%
copy from dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/IdentityCompressor.java
copy to dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/compressor/Identity.java
index 624d6b9..3d3d32d 100644
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/IdentityCompressor.java
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/compressor/Identity.java
@@ -15,18 +15,22 @@
* limitations under the License.
*/
-package org.apache.dubbo.rpc.protocol.tri;
+package org.apache.dubbo.rpc.protocol.tri.compressor;
/**
* Default compressor
* <p>
* Do not use the spi
*/
-public class IdentityCompressor implements Compressor {
+public class Identity implements Compressor, DeCompressor {
+
+ public static final String MESSAGE_ENCODING = "identity";
+
+ public static final Identity IDENTITY = new Identity();
@Override
public String getMessageEncoding() {
- return "identity";
+ return MESSAGE_ENCODING;
}
@Override
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/FlushQueueCommand.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/compressor/MessageEncoding.java
similarity index 70%
copy from dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/FlushQueueCommand.java
copy to dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/compressor/MessageEncoding.java
index 9563056..cdf2e09 100644
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/FlushQueueCommand.java
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/compressor/MessageEncoding.java
@@ -15,15 +15,14 @@
* limitations under the License.
*/
-package org.apache.dubbo.rpc.protocol.tri.command;
+package org.apache.dubbo.rpc.protocol.tri.compressor;
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.channel.ChannelPromise;
+public interface MessageEncoding {
-public class FlushQueueCommand extends QueuedCommand.AbstractQueuedCommand {
-
- @Override
- public void doSend(ChannelHandlerContext ctx, ChannelPromise promise) {
- ctx.flush();
- }
+ /**
+ * message encoding of current compressor
+ *
+ * @return return message encoding
+ */
+ String getMessageEncoding();
}
diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/stream/StreamObserver.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/frame/Deframer.java
similarity index 52%
copy from dubbo-common/src/main/java/org/apache/dubbo/common/stream/StreamObserver.java
copy to dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/frame/Deframer.java
index 7ef12ea..66bb9e7 100644
--- a/dubbo-common/src/main/java/org/apache/dubbo/common/stream/StreamObserver.java
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/frame/Deframer.java
@@ -15,31 +15,32 @@
* limitations under the License.
*/
-package org.apache.dubbo.common.stream;
+package org.apache.dubbo.rpc.protocol.tri.frame;
+
+import io.netty.buffer.ByteBuf;
+
+public interface Deframer {
-/**
- * StreamObserver is a common streaming API. It is an observer for receiving messages.
- * Implementations are NOT required to be thread-safe.
- *
- * @param <T> type of message
- */
-public interface StreamObserver<T> {
/**
- * onNext
+ * Adds the given data to this deframer and attempts delivery to the listener.
*
- * @param data to process
+ * @param data the raw data read from the remote endpoint. Must be non-null.
*/
- void onNext(T data);
+ void deframe(ByteBuf data);
/**
- * onError
+ * Requests up to the given number of messages from the call. No additional messages will be
+ * delivered.
+ *
+ * <p>If {@link #close()} has been called, this method will have no effect.
*
- * @param throwable error
+ * @param numMessages the requested number of messages to be delivered to the listener.
*/
- void onError(Throwable throwable);
+ void request(int numMessages);
/**
- * onCompleted
+ * Closes this deframer and frees any resources. After this method is called, additional calls
+ * will have no effect.
*/
- void onCompleted();
+ void close();
}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/frame/TriDecoder.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/frame/TriDecoder.java
new file mode 100644
index 0000000..18cf171
--- /dev/null
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/frame/TriDecoder.java
@@ -0,0 +1,167 @@
+/*
+ * 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.RpcException;
+import org.apache.dubbo.rpc.protocol.tri.compressor.DeCompressor;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.buffer.CompositeByteBuf;
+import io.netty.buffer.Unpooled;
+
+public class TriDecoder implements Deframer {
+ private static final int HEADER_LENGTH = 5;
+ private static final int COMPRESSED_FLAG_MASK = 1;
+ private static final int RESERVED_MASK = 0xFE;
+ private final CompositeByteBuf accumulate = Unpooled.compositeBuffer();
+ private final Listener listener;
+ private final DeCompressor decompressor;
+ private boolean compressedFlag;
+ private long pendingDeliveries;
+ private boolean inDelivery = false;
+ private boolean closing;
+ private boolean closed;
+
+ private int requiredLength = HEADER_LENGTH;
+
+ private GrpcDecodeState state = GrpcDecodeState.HEADER;
+
+ public TriDecoder(DeCompressor decompressor, Listener listener) {
+ this.decompressor = decompressor;
+ this.listener = listener;
+ }
+
+ @Override
+ public void deframe(ByteBuf data) {
+ accumulate.addComponent(true, data);
+ deliver();
+ }
+
+ public void request(int numMessages) {
+ pendingDeliveries += numMessages;
+ deliver();
+ }
+
+ @Override
+ public void close() {
+ closing = true;
+ deliver();
+ }
+
+ private void deliver() {
+ // We can have reentrancy here when using a direct executor, triggered by calls to
+ // request more messages. This is safe as we simply loop until pendingDelivers = 0
+ if (inDelivery) {
+ return;
+ }
+ inDelivery = true;
+ try {
+ // Process the uncompressed bytes.
+ while (pendingDeliveries > 0 && hasEnoughBytes()) {
+ switch (state) {
+ case HEADER:
+ processHeader();
+ break;
+ case PAYLOAD:
+ // Read the body and deliver the message.
+ processBody();
+
+ // Since we've delivered a message, decrement the number of pending
+ // deliveries remaining.
+ pendingDeliveries--;
+ break;
+ default:
+ throw new AssertionError("Invalid state: " + state);
+ }
+ }
+ if (closing) {
+ if (!closed) {
+ closed = true;
+ accumulate.clear();
+ accumulate.release();
+ listener.close();
+ }
+ }
+ } finally {
+ inDelivery = false;
+ }
+ }
+
+ private boolean hasEnoughBytes() {
+ return requiredLength - accumulate.readableBytes() <= 0;
+ }
+
+ /**
+ * Processes the GRPC compression header which is composed of the compression flag and the outer
+ * frame length.
+ */
+ private void processHeader() {
+ int type = accumulate.readUnsignedByte();
+ if ((type & RESERVED_MASK) != 0) {
+ throw new RpcException("gRPC frame header malformed: reserved bits not zero");
+ }
+ compressedFlag = (type & COMPRESSED_FLAG_MASK) != 0;
+
+ requiredLength = accumulate.readInt();
+
+ // Continue reading the frame body.
+ state = GrpcDecodeState.PAYLOAD;
+ }
+
+ /**
+ * Processes the GRPC message body, which depending on frame header flags may be compressed.
+ */
+ private void processBody() {
+ // There is no reliable way to get the uncompressed size per message when it's compressed,
+ // because the uncompressed bytes are provided through an InputStream whose total size is
+ // unknown until all bytes are read, and we don't know when it happens.
+ byte[] stream = compressedFlag ? getCompressedBody() : getUncompressedBody();
+
+ listener.onRawMessage(stream);
+
+ // Done with this frame, begin processing the next header.
+ state = GrpcDecodeState.HEADER;
+ requiredLength = HEADER_LENGTH;
+ }
+
+ private byte[] getCompressedBody() {
+ final byte[] compressedBody = getUncompressedBody();
+ return decompressor.decompress(compressedBody);
+ }
+
+ private byte[] getUncompressedBody() {
+ byte[] data = new byte[requiredLength];
+ accumulate.readBytes(data);
+ return data;
+ }
+
+
+ private enum GrpcDecodeState {
+ HEADER,
+ PAYLOAD
+ }
+
+ public interface Listener {
+
+ void onRawMessage(byte[] data);
+
+ void close();
+
+ }
+
+}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/support/MockAbstractStreamImpl.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/observer/CallStreamObserver.java
similarity index 51%
rename from dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/support/MockAbstractStreamImpl.java
rename to dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/observer/CallStreamObserver.java
index 4270e05..67d187a 100644
--- a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/support/MockAbstractStreamImpl.java
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/observer/CallStreamObserver.java
@@ -14,35 +14,33 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.dubbo.rpc.protocol.tri.support;
-import org.apache.dubbo.common.URL;
-import org.apache.dubbo.common.stream.StreamObserver;
-import org.apache.dubbo.rpc.protocol.tri.AbstractStream;
-import org.apache.dubbo.rpc.protocol.tri.InboundTransportObserver;
+package org.apache.dubbo.rpc.protocol.tri.observer;
-public class MockAbstractStreamImpl extends AbstractStream {
- public MockAbstractStreamImpl(URL url) {
- super(url);
- }
+import org.apache.dubbo.common.stream.StreamObserver;
+import org.apache.dubbo.rpc.protocol.tri.compressor.Compressor;
- @Override
- protected void cancelByRemoteReset() {
+public interface CallStreamObserver<T> extends StreamObserver<T> {
- }
- @Override
- protected void cancelByLocal(Throwable throwable) {
+ /**
+ * 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);
- @Override
- protected StreamObserver<Object> createStreamObserver() {
- return null;
- }
- @Override
- protected InboundTransportObserver createInboundTransportObserver() {
- return null;
- }
}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/observer/ClientCallToObserverAdapter.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/observer/ClientCallToObserverAdapter.java
new file mode 100644
index 0000000..4e16391
--- /dev/null
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/observer/ClientCallToObserverAdapter.java
@@ -0,0 +1,80 @@
+/*
+ * 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;
+ private boolean autoRequestEnabled = true;
+
+ public ClientCallToObserverAdapter(ClientCall call) {
+ this.call = call;
+ }
+
+ public boolean isAutoRequestEnabled() {
+ return autoRequestEnabled;
+ }
+
+ @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.cancel(null, throwable);
+ this.terminated = true;
+ }
+
+ @Override
+ public void onCompleted() {
+ if (terminated) {
+ return;
+ }
+ call.halfClose();
+ this.terminated = true;
+ }
+
+ @Override
+ public void cancel(Throwable throwable) {
+ call.cancel("Canceled by app ", throwable);
+ this.terminated = true;
+ }
+
+ @Override
+ public void setCompression(String compression) {
+ call.setCompression(compression);
+ }
+
+ @Override
+ public void request(int count) {
+ call.requestN(count);
+ }
+
+ @Override
+ public void disableAutoRequest() {
+ autoRequestEnabled = false;
+ }
+}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/observer/ServerCallToObserverAdapter.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/observer/ServerCallToObserverAdapter.java
new file mode 100644
index 0000000..18dccd3
--- /dev/null
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/observer/ServerCallToObserverAdapter.java
@@ -0,0 +1,118 @@
+/*
+ * 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.logger.Logger;
+import org.apache.dubbo.common.logger.LoggerFactory;
+import org.apache.dubbo.rpc.CancellationContext;
+import org.apache.dubbo.rpc.protocol.tri.CancelableStreamObserver;
+import org.apache.dubbo.rpc.protocol.tri.RpcStatus;
+import org.apache.dubbo.rpc.protocol.tri.ServerStreamObserver;
+import org.apache.dubbo.rpc.protocol.tri.call.ServerCall;
+
+import java.util.Map;
+
+public class ServerCallToObserverAdapter<T> extends CancelableStreamObserver<T> implements ServerStreamObserver<T> {
+ private static final Logger LOGGER = LoggerFactory.getLogger(CancelableStreamObserver.class);
+ public final CancellationContext cancellationContext;
+ private final ServerCall call;
+ private Map<String, Object> attachments;
+ private boolean terminated = false;
+
+ public ServerCallToObserverAdapter(ServerCall call,
+ CancellationContext cancellationContext) {
+ this.call = call;
+ this.cancellationContext = cancellationContext;
+ }
+
+ public boolean isAutoRequestN() {
+ return call.isAutoRequestN();
+ }
+
+
+ private boolean isTerminated() {
+ return terminated;
+ }
+
+ private void setTerminated(boolean terminated) {
+ this.terminated = terminated;
+ }
+
+ @Override
+ public void onNext(Object data) {
+ if (isTerminated()) {
+ throw new IllegalStateException("Stream observer has been terminated, no more data is allowed");
+ }
+ call.writeMessage(data);
+ }
+
+ @Override
+ public void onError(Throwable throwable) {
+ if (isTerminated()) {
+ return;
+ }
+ final RpcStatus status = RpcStatus.getStatus(throwable);
+ call.close(status, null);
+ setTerminated(true);
+ }
+
+ public void onCompleted(RpcStatus status) {
+ if (isTerminated()) {
+ return;
+ }
+ call.close(status, attachments);
+ setTerminated(true);
+
+ }
+
+ @Override
+ public void onCompleted() {
+ if (isTerminated()) {
+ return;
+ }
+ call.close(RpcStatus.OK, null);
+ setTerminated(true);
+ }
+
+ public void setResponseAttachments(Map<String, Object> attachments) {
+ this.attachments = attachments;
+ }
+
+ @Override
+ public void setCompression(String compression) {
+ call.setCompression(compression);
+ }
+
+ public void cancel(Throwable throwable) {
+ cancellationContext.cancel(throwable);
+ }
+
+ public boolean isTimeout(long cost) {
+ return call.timeout != null && call.timeout < cost;
+ }
+
+ @Override
+ public void disableAutoInboundFlowControl() {
+ call.disableAutoRequestN();
+ }
+
+ @Override
+ public void request(int count) {
+ call.requestN(count);
+ }
+}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/observer/WrapperRequestObserver.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/observer/WrapperRequestObserver.java
new file mode 100644
index 0000000..d33fda4
--- /dev/null
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/observer/WrapperRequestObserver.java
@@ -0,0 +1,82 @@
+/*
+ * 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.RpcStatus;
+import org.apache.dubbo.rpc.protocol.tri.pack.GenericPack;
+import org.apache.dubbo.triple.TripleWrapper;
+
+import com.google.protobuf.ByteString;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+
+public class WrapperRequestObserver implements StreamObserver<Object> {
+ private final StreamObserver<Object> delegate;
+ private final String[] argumentsType;
+ private final GenericPack genericPack;
+
+ private WrapperRequestObserver(StreamObserver<Object> delegate, String[] argumentsType, GenericPack genericPack) {
+ this.delegate = delegate;
+ this.argumentsType = argumentsType;
+ this.genericPack = genericPack;
+ }
+
+ public static StreamObserver<Object> wrap(StreamObserver<Object> delegate, String[] argumentsType, GenericPack genericPack) {
+ return new WrapperRequestObserver(delegate, argumentsType, genericPack);
+ }
+
+ @Override
+ public void onNext(Object data) {
+ final Object[] arguments;
+ if (data instanceof Object[]) {
+ arguments = (Object[]) data;
+ } else {
+ arguments = new Object[]{data};
+ }
+ final TripleWrapper.TripleRequestWrapper.Builder builder = TripleWrapper.TripleRequestWrapper.newBuilder()
+ .setSerializeType(genericPack.serializationName);
+ for (String type : argumentsType) {
+ builder.addArgTypes(type);
+ }
+ try {
+ for (Object argument : arguments) {
+ ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ bos.write(genericPack.pack(argument));
+ builder.addArgs(ByteString.copyFrom(bos.toByteArray()));
+ }
+ } catch (IOException e) {
+ throw RpcStatus.INTERNAL
+ .withDescription("Serialize request failed")
+ .withCause(e)
+ .asException();
+ }
+ delegate.onNext(builder.build());
+ }
+
+ @Override
+ public void onError(Throwable throwable) {
+ delegate.onError(throwable);
+ }
+
+ @Override
+ public void onCompleted() {
+ delegate.onCompleted();
+ }
+}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/observer/WrapperResponseObserver.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/observer/WrapperResponseObserver.java
new file mode 100644
index 0000000..a7137cc
--- /dev/null
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/observer/WrapperResponseObserver.java
@@ -0,0 +1,66 @@
+/*
+ * 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.URL;
+import org.apache.dubbo.common.serialize.MultipleSerialization;
+import org.apache.dubbo.rpc.CancellationContext;
+import org.apache.dubbo.rpc.protocol.tri.RpcStatus;
+import org.apache.dubbo.rpc.protocol.tri.call.ServerCall;
+import org.apache.dubbo.rpc.protocol.tri.pack.GenericPack;
+import org.apache.dubbo.triple.TripleWrapper;
+
+import com.google.protobuf.ByteString;
+
+import java.io.IOException;
+
+public class WrapperResponseObserver<T> extends ServerCallToObserverAdapter<T> {
+ private final ServerCall call;
+ private final String returnType;
+ private final MultipleSerialization multipleSerialization;
+ private final URL url;
+
+ public WrapperResponseObserver(ServerCall call, CancellationContext cancellationContext,
+ String returnType, MultipleSerialization multipleSerialization,
+ URL url) {
+ super(call, cancellationContext);
+ this.url = url;
+ this.call = call;
+ this.returnType = returnType;
+ this.multipleSerialization = multipleSerialization;
+ }
+
+ @Override
+ public void onNext(Object data) {
+ GenericPack pack = new GenericPack(multipleSerialization, call.serializerType, url);
+ try {
+ data = TripleWrapper.TripleResponseWrapper.newBuilder()
+ .setSerializeType(call.serializerType)
+ .setType(returnType)
+ .setData(ByteString.copyFrom(pack.pack(data)))
+ .build();
+ } catch (IOException e) {
+ throw RpcStatus.INTERNAL
+ .withDescription("Serialize response failed")
+ .withCause(e)
+ .asException();
+ }
+ super.onNext(data);
+ }
+
+}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/pack/GenericPack.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/pack/GenericPack.java
new file mode 100644
index 0000000..5495eb8
--- /dev/null
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/pack/GenericPack.java
@@ -0,0 +1,67 @@
+/*
+ * 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.pack;
+
+import org.apache.dubbo.common.URL;
+import org.apache.dubbo.common.serialize.MultipleSerialization;
+import org.apache.dubbo.rpc.protocol.tri.TripleConstant;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+
+public class GenericPack implements Pack {
+ public final String serializationName;
+ private final MultipleSerialization serialization;
+ private final String innerSerializationName;
+ private final URL url;
+
+ public GenericPack(MultipleSerialization serialization, String serializationName, URL url) {
+ this.serialization = serialization;
+ this.serializationName = convertHessianToWrapper(serializationName);
+ this.innerSerializationName = convertHessianFromWrapper(serializationName);
+ this.url = url;
+ }
+
+ @Override
+ public byte[] pack(Object obj) throws IOException {
+ final ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ serialization.serialize(url, innerSerializationName, null, obj, baos);
+ return baos.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 (TripleConstant.HESSIAN2.equals(serializeType)) {
+ return TripleConstant.HESSIAN4;
+ }
+ return serializeType;
+ }
+
+ protected String convertHessianFromWrapper(String serializeType) {
+ if (TripleConstant.HESSIAN4.equals(serializeType)) {
+ return TripleConstant.HESSIAN2;
+ }
+ return serializeType;
+ }
+}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/pack/GenericUnpack.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/pack/GenericUnpack.java
new file mode 100644
index 0000000..324e68d
--- /dev/null
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/pack/GenericUnpack.java
@@ -0,0 +1,47 @@
+/*
+ * 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.pack;
+
+import org.apache.dubbo.common.URL;
+import org.apache.dubbo.common.serialize.MultipleSerialization;
+import org.apache.dubbo.rpc.protocol.tri.TripleConstant;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+
+public class GenericUnpack {
+ public final MultipleSerialization serialization;
+ private final URL url;
+
+ public GenericUnpack(MultipleSerialization serialization, URL url) {
+ this.serialization = serialization;
+ this.url = url;
+ }
+
+ public Object unpack(byte[] data, String serializeType, String clz) throws ClassNotFoundException, IOException {
+ final ByteArrayInputStream bais = new ByteArrayInputStream(data);
+ return serialization.deserialize(url, convertHessianFromWrapper(serializeType), clz, bais);
+ }
+
+ protected String convertHessianFromWrapper(String serializeType) {
+ if (TripleConstant.HESSIAN4.equals(serializeType)) {
+ return TripleConstant.HESSIAN2;
+ }
+ return serializeType;
+ }
+}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/FlushQueueCommand.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/pack/Pack.java
similarity index 70%
copy from dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/FlushQueueCommand.java
copy to dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/pack/Pack.java
index 9563056..e54402b 100644
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/FlushQueueCommand.java
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/pack/Pack.java
@@ -15,15 +15,10 @@
* limitations under the License.
*/
-package org.apache.dubbo.rpc.protocol.tri.command;
+package org.apache.dubbo.rpc.protocol.tri.pack;
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.channel.ChannelPromise;
+import java.io.IOException;
-public class FlushQueueCommand extends QueuedCommand.AbstractQueuedCommand {
-
- @Override
- public void doSend(ChannelHandlerContext ctx, ChannelPromise promise) {
- ctx.flush();
- }
+public interface Pack {
+ byte[] pack(Object obj) throws IOException;
}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/IdentityCompressor.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/pack/PbPack.java
similarity index 63%
rename from dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/IdentityCompressor.java
rename to dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/pack/PbPack.java
index 624d6b9..ed4d398 100644
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/IdentityCompressor.java
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/pack/PbPack.java
@@ -15,27 +15,21 @@
* limitations under the License.
*/
-package org.apache.dubbo.rpc.protocol.tri;
+package org.apache.dubbo.rpc.protocol.tri.pack;
-/**
- * Default compressor
- * <p>
- * Do not use the spi
- */
-public class IdentityCompressor implements Compressor {
+import org.apache.dubbo.rpc.protocol.tri.SingleProtobufUtils;
- @Override
- public String getMessageEncoding() {
- return "identity";
- }
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
- @Override
- public byte[] compress(byte[] payloadByteArr) {
- return payloadByteArr;
- }
+public class PbPack implements Pack {
+ public static final PbPack INSTANCE = new PbPack();
@Override
- public byte[] decompress(byte[] payloadByteArr) {
- return payloadByteArr;
+ public byte[] pack(Object obj) throws IOException {
+ final ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ SingleProtobufUtils.serialize(obj, baos);
+ return baos.toByteArray();
}
+
}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/Metadata.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/pack/PbUnpack.java
similarity index 50%
copy from dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/Metadata.java
copy to dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/pack/PbUnpack.java
index f7c49f7..f9f45d9 100644
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/Metadata.java
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/pack/PbUnpack.java
@@ -15,31 +15,25 @@
* limitations under the License.
*/
-package org.apache.dubbo.rpc.protocol.tri;
+package org.apache.dubbo.rpc.protocol.tri.pack;
-import java.util.Map;
-import java.util.Optional;
+import org.apache.dubbo.rpc.protocol.tri.SingleProtobufUtils;
+import org.apache.dubbo.triple.TripleWrapper;
-public interface Metadata extends Iterable<Map.Entry<CharSequence, CharSequence>> {
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
- Metadata put(CharSequence key, CharSequence value);
+public class PbUnpack<T> {
+ public static PbUnpack<TripleWrapper.TripleResponseWrapper> RESP_PB_UNPACK = new PbUnpack<>(TripleWrapper.TripleResponseWrapper.class);
+ public static PbUnpack<TripleWrapper.TripleRequestWrapper> REQ_PB_UNPACK = new PbUnpack<>(TripleWrapper.TripleRequestWrapper.class);
+ private final Class<?> clz;
- default Metadata putIfNotNull(CharSequence key, CharSequence value) {
- if (value != null) {
- put(key, value);
- }
- return this;
+ public PbUnpack(Class<?> clz) {
+ this.clz = clz;
}
- CharSequence get(CharSequence key);
-
-
- default CharSequence getOrDefault(CharSequence key, CharSequence val) {
- return Optional.ofNullable(get(key)).orElse(val);
+ public T unpack(byte[] data) throws IOException {
+ final ByteArrayInputStream bais = new ByteArrayInputStream(data);
+ return (T) SingleProtobufUtils.deserialize(bais, clz);
}
-
- boolean contains(CharSequence key);
-
- boolean remove(CharSequence key);
-
}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/pack/WrapRequestUnpack.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/pack/WrapRequestUnpack.java
new file mode 100644
index 0000000..d0ef38b
--- /dev/null
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/pack/WrapRequestUnpack.java
@@ -0,0 +1,47 @@
+/*
+ * 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.pack;
+
+import org.apache.dubbo.rpc.protocol.tri.RpcStatus;
+import org.apache.dubbo.triple.TripleWrapper;
+
+import java.io.IOException;
+
+public class WrapRequestUnpack {
+ private final GenericUnpack genericUnpack;
+
+ public WrapRequestUnpack(GenericUnpack genericUnpack) {
+ this.genericUnpack = genericUnpack;
+ }
+
+ public Object unpack(TripleWrapper.TripleRequestWrapper wrapper) {
+ try {
+ Object[] ret = new Object[wrapper.getArgsCount()];
+ final String serializeType = wrapper.getSerializeType();
+ for (int i = 0; i < wrapper.getArgsList().size(); i++) {
+ ret[i] = genericUnpack.unpack(wrapper.getArgs(i).toByteArray(), serializeType, wrapper.getArgTypes(i));
+ }
+ return ret;
+ } catch (ClassNotFoundException | IOException e) {
+ throw RpcStatus.INTERNAL
+ .withDescription("Deserialize response failed")
+ .withCause(e)
+ .asException();
+ }
+ }
+}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ClassLoadUtil.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/pack/WrapResponseUnpack.java
similarity index 51%
copy from dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ClassLoadUtil.java
copy to dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/pack/WrapResponseUnpack.java
index d4a790a..da2e963 100644
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ClassLoadUtil.java
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/pack/WrapResponseUnpack.java
@@ -14,16 +14,29 @@
* 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) {
+package org.apache.dubbo.rpc.protocol.tri.pack;
+
+import org.apache.dubbo.rpc.protocol.tri.RpcStatus;
+import org.apache.dubbo.triple.TripleWrapper;
+
+import java.io.IOException;
+
+public class WrapResponseUnpack {
+ private final GenericUnpack genericUnpack;
+
+ public WrapResponseUnpack(GenericUnpack genericUnpack) {
+ this.genericUnpack = genericUnpack;
+ }
+
+ public Object unpack(TripleWrapper.TripleResponseWrapper wrapper) {
try {
- if (loader != null && loader != Thread.currentThread().getContextClassLoader()) {
- Thread.currentThread().setContextClassLoader(loader);
- }
- } catch (SecurityException e) {
- // ignore , ForkJoinPool & jdk8 & securityManager will cause this
+ return genericUnpack.unpack(wrapper.getData().toByteArray(), wrapper.getSerializeType(), wrapper.getType());
+ } catch (ClassNotFoundException | IOException e) {
+ throw RpcStatus.INTERNAL
+ .withDescription("Deserialize response failed")
+ .withCause(e)
+ .asException();
}
}
}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleClientHandler.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/AbstractStream.java
similarity index 53%
copy from dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleClientHandler.java
copy to dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/AbstractStream.java
index 96c8097..5943f0c 100644
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleClientHandler.java
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/AbstractStream.java
@@ -14,30 +14,33 @@
* 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.ConnectionHandler;
+package org.apache.dubbo.rpc.protocol.tri.stream;
+
+import org.apache.dubbo.common.threadpool.serial.SerializingExecutor;
import org.apache.dubbo.rpc.model.FrameworkModel;
-import io.netty.channel.ChannelDuplexHandler;
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.handler.codec.http2.Http2GoAwayFrame;
-import io.netty.util.ReferenceCountUtil;
+import io.netty.channel.EventLoop;
+
+import java.util.concurrent.Executor;
-public class TripleClientHandler extends ChannelDuplexHandler {
+public abstract class AbstractStream implements Stream {
- private final FrameworkModel frameworkModel;
+ protected final Executor executor;
+ protected final FrameworkModel frameworkModel;
- public TripleClientHandler(FrameworkModel frameworkModel) {
+ public AbstractStream(Executor executor, FrameworkModel frameworkModel) {
+ this.executor = new SerializingExecutor(executor);
this.frameworkModel = frameworkModel;
}
- @Override
- public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
- if (msg instanceof Http2GoAwayFrame) {
- final ConnectionHandler connectionHandler = ctx.pipeline().get(ConnectionHandler.class);
- connectionHandler.onGoAway(ctx.channel());
+ abstract EventLoop getEventLoop();
+
+ void runOnEventLoop(final Runnable r) {
+ if (getEventLoop().inEventLoop()) {
+ r.run();
+ return;
}
- ReferenceCountUtil.release(msg);
+ getEventLoop().execute(r);
}
}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/ClientStream.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/ClientStream.java
new file mode 100644
index 0000000..b881a31
--- /dev/null
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/ClientStream.java
@@ -0,0 +1,342 @@
+/*
+ * 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.model.FrameworkModel;
+import org.apache.dubbo.rpc.protocol.tri.DefaultFuture2;
+import org.apache.dubbo.rpc.protocol.tri.RequestMetadata;
+import org.apache.dubbo.rpc.protocol.tri.RpcStatus;
+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.transport.AbstractH2TransportListener;
+import org.apache.dubbo.rpc.protocol.tri.transport.H2TransportListener;
+import org.apache.dubbo.rpc.protocol.tri.transport.TripleCommandOutBoundHandler;
+import org.apache.dubbo.rpc.protocol.tri.transport.TripleHttp2ClientResponseHandler;
+import org.apache.dubbo.rpc.protocol.tri.transport.WriteQueue;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.channel.Channel;
+import io.netty.channel.EventLoop;
+import io.netty.handler.codec.http2.DefaultHttp2Headers;
+import io.netty.handler.codec.http2.Http2Headers;
+import io.netty.handler.codec.http2.Http2StreamChannel;
+import io.netty.handler.codec.http2.Http2StreamChannelBootstrap;
+import io.netty.util.ReferenceCountUtil;
+import io.netty.util.concurrent.Future;
+
+import java.nio.charset.StandardCharsets;
+import java.util.Map;
+import java.util.concurrent.Executor;
+
+
+/**
+ * ClientStream is an abstraction for bi-directional messaging.
+ * It maintains a {@link WriteQueue} 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 class ClientStream extends AbstractStream implements Stream {
+ public final ClientStreamListener listener;
+ private final WriteQueue writeQueue;
+ private final long requestId;
+ private EventLoop eventLoop;
+ private Deframer deframer;
+
+ // for test
+ ClientStream(FrameworkModel frameworkModel,
+ long requestId,
+ Executor executor,
+ WriteQueue writeQueue,
+ ClientStreamListener listener) {
+
+ super(executor, frameworkModel);
+ this.requestId = requestId;
+ this.listener = listener;
+ this.writeQueue = writeQueue;
+ }
+
+ public ClientStream(FrameworkModel frameworkModel,
+ long requestId,
+ Executor executor,
+ Channel parent,
+ ClientStreamListener listener) {
+ super(executor, frameworkModel);
+ this.requestId = requestId;
+ this.listener = listener;
+ this.writeQueue = createWriteQueue(parent);
+ }
+
+ private WriteQueue createWriteQueue(Channel parent) {
+ final Http2StreamChannelBootstrap bootstrap = new Http2StreamChannelBootstrap(parent);
+ final Future<Http2StreamChannel> future = bootstrap.open().syncUninterruptibly();
+ if (!future.isSuccess()) {
+ throw new IllegalStateException("Create remote stream failed. channel:" + parent);
+ }
+ final Http2StreamChannel channel = future.getNow();
+ eventLoop = channel.eventLoop();
+ channel.pipeline()
+ .addLast(new TripleCommandOutBoundHandler())
+ .addLast(new TripleHttp2ClientResponseHandler(createTransportListener()));
+ DefaultFuture2.addTimeoutListener(requestId, channel::close);
+ return new WriteQueue(channel);
+ }
+
+
+ public void startCall(RequestMetadata metadata) {
+ if (this.writeQueue == null) {
+ // already processed at createStream()
+ return;
+ }
+ DefaultHttp2Headers headers = StreamUtils.metadataToHeaders(metadata);
+
+ final HeaderQueueCommand headerCmd = HeaderQueueCommand.createHeaders(headers);
+ this.writeQueue.enqueue(headerCmd).addListener(future -> {
+ if (!future.isSuccess()) {
+ transportException(future.cause());
+ }
+ });
+ }
+
+ private void transportException(Throwable cause) {
+ final RpcStatus status = RpcStatus.INTERNAL
+ .withDescription("Http2 exception")
+ .withCause(cause);
+ listener.complete(status);
+ }
+
+ public void cancelByLocal(RpcStatus status) {
+ final CancelQueueCommand cmd = CancelQueueCommand.createCommand();
+ this.writeQueue.enqueue(cmd);
+ }
+
+
+ @Override
+ public void writeMessage(byte[] message, int compressed) {
+ try {
+ final DataQueueCommand cmd = DataQueueCommand.createGrpcCommand(message, false, compressed);
+ this.writeQueue.enqueue(cmd);
+ } catch (Throwable t) {
+ cancelByLocal(RpcStatus.INTERNAL
+ .withDescription("Client write message failed")
+ .withCause(t));
+ }
+ }
+
+ @Override
+ public void requestN(int n) {
+ deframer.request(n);
+ }
+
+ public void halfClose() {
+ final EndStreamQueueCommand cmd = EndStreamQueueCommand.create();
+ this.writeQueue.enqueue(cmd);
+ }
+
+ @Override
+ EventLoop getEventLoop() {
+ return eventLoop;
+ }
+
+ /**
+ * @return transport listener
+ */
+ H2TransportListener createTransportListener() {
+ return new ClientTransportListener();
+ }
+
+ class ClientTransportListener extends AbstractH2TransportListener implements H2TransportListener {
+ private RpcStatus transportError;
+ private DeCompressor decompressor;
+ private boolean remoteClosed;
+ private boolean headerReceived;
+ private Http2Headers trailers;
+
+ void handleH2TransportError(RpcStatus status) {
+ writeQueue.enqueue(CancelQueueCommand.createCommand());
+ finishProcess(status, null);
+ }
+
+ void finishProcess(RpcStatus status, Http2Headers trailers) {
+ if (remoteClosed) {
+ return;
+ }
+ remoteClosed = true;
+
+ final Map<String, String> reserved = filterReservedHeaders(trailers);
+ final Map<String, Object> attachments = headersToMap(trailers);
+ listener.complete(status, attachments, reserved);
+ }
+
+ private RpcStatus validateHeaderStatus(Http2Headers headers) {
+ Integer httpStatus = headers.status() == null ? null : Integer.parseInt(headers.status().toString());
+ if (httpStatus == null) {
+ return RpcStatus.INTERNAL.withDescription("Missing HTTP status code");
+ }
+ final CharSequence contentType = headers.get(TripleHeaderEnum.CONTENT_TYPE_KEY.getHeader());
+ if (contentType == null || !contentType.toString().startsWith(TripleHeaderEnum.APPLICATION_GRPC.getHeader())) {
+ return RpcStatus.fromCode(RpcStatus.httpStatusToGrpcCode(httpStatus))
+ .withDescription("invalid content-type: " + contentType);
+ }
+ return null;
+ }
+
+ void onHeaderReceived(Http2Headers headers) {
+ if (transportError != null) {
+ transportError.appendDescription("headers:" + headers);
+ return;
+ }
+ if (headerReceived) {
+ transportError = RpcStatus.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.getHeader());
+ if (null != messageEncoding) {
+ String compressorStr = messageEncoding.toString();
+ if (!Identity.IDENTITY.getMessageEncoding().equals(compressorStr)) {
+ DeCompressor compressor = DeCompressor.getCompressor(frameworkModel, compressorStr);
+ if (null == compressor) {
+ throw RpcStatus.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) {
+ ClientStream.this.listener.onMessage(data);
+ }
+
+ public void close() {
+ finishProcess(statusFromTrailers(trailers), trailers);
+ }
+ };
+ deframer = new TriDecoder(decompressor, listener);
+ ClientStream.this.listener.onStart();
+ }
+
+ void onTrailersReceived(Http2Headers trailers) {
+ if (transportError == null && !headerReceived) {
+ transportError = validateHeaderStatus(trailers);
+ }
+ if (transportError != null) {
+ transportError = transportError.appendDescription("trailers: " + trailers);
+ } else {
+ this.trailers = trailers;
+ RpcStatus status = statusFromTrailers(trailers);
+ if (deframer == null) {
+ finishProcess(status, trailers);
+ }
+ if (deframer != null) {
+ deframer.close();
+ }
+ }
+ }
+
+ /**
+ * Extract the response status from trailers.
+ */
+ private RpcStatus statusFromTrailers(Http2Headers trailers) {
+ final Integer intStatus = trailers.getInt(TripleHeaderEnum.STATUS_KEY.getHeader());
+ RpcStatus status = intStatus == null ? null : RpcStatus.fromCode(intStatus);
+ if (status != null) {
+ final CharSequence message = trailers.get(TripleHeaderEnum.MESSAGE_KEY.getHeader());
+ if (message != null) {
+ final String description = RpcStatus.decodeMessage(message.toString());
+ status = status.withDescription(description);
+ }
+ return status;
+ }
+ // No status; something is broken. Try to provide a rational error.
+ if (headerReceived) {
+ return RpcStatus.UNKNOWN.withDescription("missing GRPC status in response");
+ }
+ Integer httpStatus = trailers.status() == null ? null : Integer.parseInt(trailers.status().toString());
+ if (httpStatus != null) {
+ status = RpcStatus.fromCode(RpcStatus.httpStatusToGrpcCode(httpStatus));
+ } else {
+ status = RpcStatus.INTERNAL.withDescription("missing HTTP status code");
+ }
+ return status.appendDescription("missing GRPC status, inferred error from HTTP status code");
+ }
+
+ @Override
+ public void onHeader(Http2Headers headers, boolean endStream) {
+ executor.execute(() -> {
+ if (endStream) {
+ if (!remoteClosed) {
+ writeQueue.enqueue(CancelQueueCommand.createCommand());
+ }
+ onTrailersReceived(headers);
+ } else {
+ onHeaderReceived(headers);
+ }
+ });
+
+ }
+
+ @Override
+ public void onData(ByteBuf data, boolean endStream) {
+ executor.execute(() -> {
+ 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(RpcStatus.INTERNAL
+ .withDescription("headers not received before payload"));
+ return;
+ }
+ deframer.deframe(data);
+ });
+ }
+
+ @Override
+ public void cancelByRemote(RpcStatus status) {
+ executor.execute(() -> {
+ transportError = status;
+ finishProcess(status, null);
+ });
+ }
+ }
+}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleClientInboundHandler.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/ClientStreamListener.java
similarity index 55%
rename from dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleClientInboundHandler.java
rename to dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/ClientStreamListener.java
index 007f235..f04becd 100644
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleClientInboundHandler.java
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/ClientStreamListener.java
@@ -14,20 +14,31 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.dubbo.rpc.protocol.tri;
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.channel.ChannelInboundHandlerAdapter;
+package org.apache.dubbo.rpc.protocol.tri.stream;
-public class TripleClientInboundHandler extends ChannelInboundHandlerAdapter {
- @Override
- public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
- final AbstractClientStream clientStream = ctx.channel().attr(TripleConstant.CLIENT_STREAM_KEY).get();
+import org.apache.dubbo.rpc.protocol.tri.RpcStatus;
- final byte[] data = (byte[]) msg;
- if (clientStream != null) {
- clientStream.inboundTransportObserver()
- .onData(data, false);
- }
+import java.util.Collections;
+import java.util.Map;
+
+public interface ClientStreamListener extends StreamListener {
+
+ void onStart();
+
+ /**
+ * Indicate the stream is closed . Will be called exactly once
+ *
+ * @param rpcStatus
+ * @param attachments
+ */
+ void complete(RpcStatus rpcStatus, Map<String, Object> attachments, Map<String, String> excludeHeaders);
+
+ default void complete(RpcStatus rpcStatus, Map<String, Object> attachments) {
+ complete(rpcStatus, attachments, Collections.emptyMap());
+ }
+
+ default void complete(RpcStatus rpcStatus) {
+ complete(rpcStatus, Collections.emptyMap(), Collections.emptyMap());
}
}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/ServerStream.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/ServerStream.java
new file mode 100644
index 0000000..3448577
--- /dev/null
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/ServerStream.java
@@ -0,0 +1,349 @@
+/*
+ * 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.Logger;
+import org.apache.dubbo.common.logger.LoggerFactory;
+import org.apache.dubbo.common.utils.StringUtils;
+import org.apache.dubbo.rpc.HeaderFilter;
+import org.apache.dubbo.rpc.model.FrameworkModel;
+import org.apache.dubbo.rpc.protocol.tri.ExceptionUtils;
+import org.apache.dubbo.rpc.protocol.tri.PathResolver;
+import org.apache.dubbo.rpc.protocol.tri.RpcStatus;
+import org.apache.dubbo.rpc.protocol.tri.TripleConstant;
+import org.apache.dubbo.rpc.protocol.tri.TripleHeaderEnum;
+import org.apache.dubbo.rpc.protocol.tri.call.ServerCall;
+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.TextDataQueueCommand;
+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.pack.GenericUnpack;
+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.WriteQueue;
+
+import com.google.protobuf.Any;
+import com.google.rpc.DebugInfo;
+import com.google.rpc.Status;
+import io.netty.buffer.ByteBuf;
+import io.netty.channel.Channel;
+import io.netty.channel.EventLoop;
+import io.netty.handler.codec.http.HttpHeaderNames;
+import io.netty.handler.codec.http.HttpMethod;
+import io.netty.handler.codec.http.HttpResponseStatus;
+import io.netty.handler.codec.http.HttpUtil;
+import io.netty.handler.codec.http2.DefaultHttp2Headers;
+import io.netty.handler.codec.http2.Http2Headers;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.Executor;
+
+import static io.netty.handler.codec.http.HttpResponseStatus.OK;
+
+public class ServerStream extends AbstractStream {
+ private static final Logger LOGGER = LoggerFactory.getLogger(ServerStream.class);
+ public final ServerTransportObserver transportObserver = new ServerTransportObserver();
+ private final WriteQueue writeQueue;
+ private final PathResolver pathResolver;
+ private final List<HeaderFilter> filters;
+ private final GenericUnpack genericUnpack;
+ private final EventLoop eventLoop;
+ private boolean headerSent;
+ private boolean trailersSent;
+ private ServerStreamListener listener;
+ private boolean closed;
+ private Deframer deframer;
+
+ public ServerStream(Channel channel,
+ FrameworkModel frameworkModel,
+ Executor executor,
+ PathResolver pathResolver,
+ List<HeaderFilter> filters,
+ GenericUnpack genericUnpack) {
+ super(executor,frameworkModel);
+ this.eventLoop = channel.eventLoop();
+ this.pathResolver = pathResolver;
+ this.filters = filters;
+ this.genericUnpack = genericUnpack;
+ this.writeQueue = new WriteQueue(channel);
+ }
+
+
+ private String getGrpcMessage(RpcStatus status) {
+ if (StringUtils.isNotEmpty(status.description)) {
+ return status.description;
+ }
+ return Optional.ofNullable(status.cause)
+ .map(Throwable::getMessage)
+ .orElse("unknown");
+ }
+
+ public void sendHeader(Http2Headers headers) {
+ if (headerSent && trailersSent) {
+ // todo handle this state
+ return;
+ }
+ if (headerSent) {
+ trailersSent = true;
+ writeQueue.enqueue(HeaderQueueCommand.createHeaders(headers, true));
+ } else {
+ headerSent = true;
+ writeQueue.enqueue(HeaderQueueCommand.createHeaders(headers, false));
+ }
+ }
+
+ public void sendHeaderWithEos(Http2Headers headers) {
+ headerSent = true;
+ sendHeader(headers);
+ }
+
+ public void close(RpcStatus status, Map<String, Object> attachments) {
+ if (closed) {
+ return;
+ }
+ closed = true;
+ final Http2Headers headers = getTrailers(status, attachments);
+ sendHeaderWithEos(headers);
+ }
+
+ private Http2Headers getTrailers(RpcStatus rpcStatus, Map<String, Object> attachments) {
+ DefaultHttp2Headers headers = new DefaultHttp2Headers();
+ if (!headerSent) {
+ headers.status(HttpResponseStatus.OK.codeAsText());
+ headers.set(HttpHeaderNames.CONTENT_TYPE, TripleConstant.CONTENT_PROTO);
+ }
+ StreamUtils.convertAttachment(headers, attachments);
+ headers.set(TripleHeaderEnum.STATUS_KEY.getHeader(), String.valueOf(rpcStatus.code.code));
+ if (rpcStatus.isOk()) {
+ return headers;
+ }
+ String grpcMessage = getGrpcMessage(rpcStatus);
+ grpcMessage = RpcStatus.encodeMessage(grpcMessage);
+ headers.set(TripleHeaderEnum.MESSAGE_KEY.getHeader(), grpcMessage);
+ Status.Builder builder = Status.newBuilder()
+ .setCode(rpcStatus.code.code)
+ .setMessage(grpcMessage);
+ Throwable throwable = rpcStatus.cause;
+ if (throwable == null) {
+ Status status = builder.build();
+ headers.set(TripleHeaderEnum.STATUS_DETAIL_KEY.getHeader(),
+ H2TransportListener.encodeBase64ASCII(status.toByteArray()));
+ return headers;
+ }
+ DebugInfo debugInfo = DebugInfo.newBuilder()
+ .addAllStackEntries(ExceptionUtils.getStackFrameList(throwable, 10))
+ // can not use now
+ // .setDetail(throwable.getMessage())
+ .build();
+ builder.addDetails(Any.pack(debugInfo));
+ Status status = builder.build();
+ headers.set(TripleHeaderEnum.STATUS_DETAIL_KEY.getHeader(),
+ H2TransportListener.encodeBase64ASCII(status.toByteArray()));
+ return headers;
+ }
+
+ @Override
+ public void writeMessage(byte[] message, int compressed) {
+ writeQueue.enqueue(DataQueueCommand.createGrpcCommand(message, false, compressed));
+ }
+
+ @Override
+ public void requestN(int n) {
+ deframer.request(n);
+ }
+
+ /**
+ * Error before create server stream, http plain text will be returned
+ *
+ * @param code
+ * @param status
+ */
+ private void responsePlainTextError(int code, RpcStatus status) {
+ Http2Headers headers = new DefaultHttp2Headers(true)
+ .status(String.valueOf(code))
+ .setInt(TripleHeaderEnum.STATUS_KEY.getHeader(), status.code.code)
+ .set(TripleHeaderEnum.MESSAGE_KEY.getHeader(), status.description)
+ .set(TripleHeaderEnum.CONTENT_TYPE_KEY.getHeader(), TripleConstant.TEXT_PLAIN_UTF8);
+ writeQueue.enqueue(HeaderQueueCommand.createHeaders(headers, false));
+ writeQueue.enqueue(TextDataQueueCommand.createCommand(status.description, true));
+ }
+
+ /**
+ * Error in create stream, unsupported config or triple protocol error.
+ *
+ * @param status
+ */
+ private void responseErr(RpcStatus status) {
+ Http2Headers trailers = new DefaultHttp2Headers()
+ .status(OK.codeAsText())
+ .set(HttpHeaderNames.CONTENT_TYPE, TripleConstant.CONTENT_PROTO)
+ .setInt(TripleHeaderEnum.STATUS_KEY.getHeader(), status.code.code)
+ .set(TripleHeaderEnum.MESSAGE_KEY.getHeader(), status.toEncodedMessage());
+ writeQueue.enqueue(HeaderQueueCommand.createHeaders(trailers, true));
+ }
+
+ @Override
+ EventLoop getEventLoop() {
+ return eventLoop;
+ }
+
+ public class ServerTransportObserver extends AbstractH2TransportListener implements H2TransportListener {
+
+
+ /**
+ * must starts from application/grpc
+ */
+ private boolean supportContentType(String contentType) {
+ if (contentType == null) {
+ return false;
+ }
+ return contentType.startsWith(TripleConstant.APPLICATION_GRPC);
+ }
+
+ @Override
+ public void onHeader(Http2Headers headers, boolean endStream) {
+ executor.execute(() -> {
+ if (!HttpMethod.POST.asciiName().contentEquals(headers.method())) {
+ responsePlainTextError(HttpResponseStatus.METHOD_NOT_ALLOWED.code(),
+ RpcStatus.INTERNAL
+ .withDescription(String.format("Method '%s' is not supported", headers.method())));
+ return;
+ }
+
+ if (headers.path() == null) {
+ responsePlainTextError(HttpResponseStatus.NOT_FOUND.code(),
+ RpcStatus.fromCode(RpcStatus.Code.UNIMPLEMENTED.code).withDescription("Expected path but is missing"));
+ return;
+ }
+
+ final String path = headers.path().toString();
+ if (path.charAt(0) != '/') {
+ responsePlainTextError(HttpResponseStatus.NOT_FOUND.code(),
+ RpcStatus.fromCode(RpcStatus.Code.UNIMPLEMENTED.code)
+ .withDescription(String.format("Expected path to start with /: %s", path)));
+ return;
+ }
+
+ final CharSequence contentType = HttpUtil.getMimeType(headers.get(HttpHeaderNames.CONTENT_TYPE));
+ if (contentType == null) {
+ responsePlainTextError(HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE.code(),
+ RpcStatus.fromCode(RpcStatus.Code.INTERNAL.code)
+ .withDescription("Content-Type is missing from the request"));
+ return;
+ }
+
+ final String contentString = contentType.toString();
+ if (!supportContentType(contentString)) {
+ responsePlainTextError(HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE.code(),
+ RpcStatus.fromCode(RpcStatus.Code.INTERNAL.code)
+ .withDescription(String.format("Content-Type '%s' is not supported", contentString)));
+ return;
+ }
+
+ if (path.charAt(0) != '/') {
+ responseErr(RpcStatus.UNIMPLEMENTED
+ .withDescription("Path must start with '/'. Request path: " + path));
+ return;
+ }
+
+ String[] parts = path.split("/");
+ if (parts.length != 3) {
+ responseErr(RpcStatus.UNIMPLEMENTED
+ .withDescription("Bad path format:" + path));
+ return;
+ }
+ String serviceName = parts[1];
+ String originalMethodName = parts[2];
+ String methodName = Character.toLowerCase(originalMethodName.charAt(0)) + originalMethodName.substring(1);
+
+ DeCompressor deCompressor = DeCompressor.NONE;
+ CharSequence messageEncoding = headers.get(TripleHeaderEnum.GRPC_ENCODING.getHeader());
+ if (null != messageEncoding) {
+ String compressorStr = messageEncoding.toString();
+ if (!Identity.MESSAGE_ENCODING.equals(compressorStr)) {
+ DeCompressor compressor = DeCompressor.getCompressor(frameworkModel, compressorStr);
+ if (null == compressor) {
+ responseErr(RpcStatus.fromCode(RpcStatus.Code.UNIMPLEMENTED.code)
+ .withDescription(String.format("Grpc-encoding '%s' is not supported", compressorStr)));
+ return;
+ }
+ deCompressor = compressor;
+ }
+ }
+
+ try {
+ final TriDecoder.Listener listener = new ServerDecoderListener();
+ ServerStream.this.deframer = new TriDecoder(deCompressor, listener);
+ } catch (Throwable t) {
+ close(RpcStatus.INTERNAL
+ .withCause(t), null);
+ }
+ ServerCall call = new ServerCall(ServerStream.this, frameworkModel,
+ serviceName,
+ methodName,
+ executor,
+ filters,
+ genericUnpack,
+ pathResolver);
+ ServerStream.this.listener = call.streamListener;
+ listener.onHeaders(headersToMap(headers));
+ if (endStream) {
+ deframer.close();
+ }
+ });
+ }
+
+
+ @Override
+ public void onData(ByteBuf data, boolean endStream) {
+ executor.execute(() -> {
+ deframer.deframe(data);
+ if (endStream) {
+ deframer.close();
+ }
+ });
+ }
+
+
+ @Override
+ public void cancelByRemote(RpcStatus status) {
+ executor.execute(() -> {
+ listener.cancel(status);
+ });
+ }
+
+
+ private class ServerDecoderListener implements TriDecoder.Listener {
+
+ @Override
+ public void onRawMessage(byte[] data) {
+ ServerStream.this.listener.onMessage(data);
+ }
+
+ @Override
+ public void close() {
+ ServerStream.this.listener.complete();
+ }
+ }
+ }
+}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/UnaryServerStreamTest.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/ServerStreamListener.java
similarity index 65%
copy from dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/UnaryServerStreamTest.java
copy to dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/ServerStreamListener.java
index ce26f7a..4665358 100644
--- a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/UnaryServerStreamTest.java
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/ServerStreamListener.java
@@ -15,18 +15,24 @@
* limitations under the License.
*/
-package org.apache.dubbo.rpc.protocol.tri;
+package org.apache.dubbo.rpc.protocol.tri.stream;
-import org.apache.dubbo.common.URL;
-import org.apache.dubbo.common.url.component.ServiceConfigURL;
+import org.apache.dubbo.rpc.protocol.tri.RpcStatus;
-import org.junit.jupiter.api.Test;
+import java.util.Map;
-class UnaryServerStreamTest {
+public interface ServerStreamListener extends StreamListener {
+
+ void onHeaders(Map<String, Object> headers);
+
+ /**
+ * Indicate the stream is closed . Will be called exactly once
+ *
+ * @param grpcStatus
+ * @param attachments
+ */
+ void complete();
+
+ void cancel(RpcStatus status);
- @Test
- @SuppressWarnings("all")
- public void testInit() {
- URL url = new ServiceConfigURL("test", "1.2.3.4", 8080);
- }
}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/PathResolver.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/Stream.java
similarity index 57%
copy from dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/PathResolver.java
copy to dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/Stream.java
index 54f8415..3e85b40 100644
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/PathResolver.java
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/Stream.java
@@ -14,24 +14,21 @@
* 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.common.extension.ExtensionScope;
-import org.apache.dubbo.common.extension.SPI;
-import org.apache.dubbo.rpc.Invoker;
+package org.apache.dubbo.rpc.protocol.tri.stream;
-/**
- * PathResolver maintains a mapping between request path and Invoker for multiple protocols.
- */
-@SPI(value = CommonConstants.TRIPLE, scope = ExtensionScope.FRAMEWORK)
-public interface PathResolver {
- void add(String path, Invoker<?> invoker);
+import org.apache.dubbo.rpc.protocol.tri.transport.H2TransportListener;
+import org.apache.dubbo.rpc.protocol.tri.transport.WriteQueue;
- Invoker<?> resolve(String path);
+/**
+ * Stream is a bi-directional intermediate layer for processing streaming data. It serializes business object instance to
+ * byte[] then send to remote, and deserializes byte[] to object instance from remote.
+ * {@link H2TransportListener} to receive data from remote and {@link WriteQueue} to write data.
+ */
+public interface Stream {
- void remove(String path);
+ void writeMessage(byte[] message, int compressed);
- void destroy();
+ void requestN(int n);
}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/FlushQueueCommand.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/StreamListener.java
similarity index 70%
copy from dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/FlushQueueCommand.java
copy to dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/StreamListener.java
index 9563056..0946936 100644
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/FlushQueueCommand.java
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/StreamListener.java
@@ -15,15 +15,10 @@
* limitations under the License.
*/
-package org.apache.dubbo.rpc.protocol.tri.command;
+package org.apache.dubbo.rpc.protocol.tri.stream;
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.channel.ChannelPromise;
+public interface StreamListener {
-public class FlushQueueCommand extends QueuedCommand.AbstractQueuedCommand {
+ void onMessage(byte[] message);
- @Override
- public void doSend(ChannelHandlerContext ctx, ChannelPromise promise) {
- ctx.flush();
- }
}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/StreamUtils.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/StreamUtils.java
new file mode 100644
index 0000000..449215c
--- /dev/null
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/StreamUtils.java
@@ -0,0 +1,164 @@
+/*
+ * 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.URL;
+import org.apache.dubbo.common.constants.CommonConstants;
+import org.apache.dubbo.common.logger.Logger;
+import org.apache.dubbo.common.logger.LoggerFactory;
+import org.apache.dubbo.rpc.Invocation;
+import org.apache.dubbo.rpc.model.MethodDescriptor;
+import org.apache.dubbo.rpc.protocol.tri.RequestMetadata;
+import org.apache.dubbo.rpc.protocol.tri.TripleConstant;
+import org.apache.dubbo.rpc.protocol.tri.TripleHeaderEnum;
+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.pack.GenericPack;
+import org.apache.dubbo.rpc.protocol.tri.pack.GenericUnpack;
+import org.apache.dubbo.rpc.protocol.tri.transport.H2TransportListener;
+import org.apache.dubbo.rpc.support.RpcUtils;
+
+import io.netty.handler.codec.http.HttpHeaderNames;
+import io.netty.handler.codec.http.HttpHeaderValues;
+import io.netty.handler.codec.http.HttpMethod;
+import io.netty.handler.codec.http2.DefaultHttp2Headers;
+import io.netty.handler.codec.http2.Http2Headers;
+import io.netty.util.AsciiString;
+
+import java.util.Arrays;
+import java.util.Locale;
+import java.util.Map;
+
+public class StreamUtils {
+ protected static final Logger LOGGER = LoggerFactory.getLogger(StreamUtils.class);
+
+ public static RequestMetadata createRequest(URL url, MethodDescriptor methodDescriptor, Invocation invocation,
+ long requestId, Compressor compressor, String acceptEncoding,
+ int timeout, GenericPack genericPack, GenericUnpack genericUnpack) {
+ final String methodName = RpcUtils.getMethodName(invocation);
+ final RequestMetadata meta = new RequestMetadata();
+ meta.scheme = getSchemeFromUrl(url);
+ meta.requestId = requestId;
+ final Map<String, Object> objectAttachments = invocation.getObjectAttachments();
+ if (objectAttachments != null) {
+ String application = (String) objectAttachments.get(CommonConstants.APPLICATION_KEY);
+ if (application == null) {
+ application = (String) objectAttachments.get(CommonConstants.REMOTE_APPLICATION_KEY);
+ }
+ meta.application = application;
+ meta.attachments = objectAttachments;
+ }
+ meta.method = methodDescriptor;
+ if (meta.method == null) {
+ throw new IllegalStateException("MethodDescriptor not found for" + methodName + " params:" + Arrays.toString(invocation.getCompatibleParamSignatures()));
+ }
+ meta.compressor = compressor;
+ meta.acceptEncoding = acceptEncoding;
+ meta.address = url.getAddress();
+ meta.service = url.getPath();
+ meta.group = url.getGroup();
+ meta.version = url.getVersion();
+ meta.timeout = timeout + "m";
+ meta.genericPack = genericPack;
+ meta.genericUnpack = genericUnpack;
+ meta.arguments = invocation.getArguments();
+ return meta;
+ }
+
+ public static DefaultHttp2Headers metadataToHeaders(RequestMetadata metadata) {
+ DefaultHttp2Headers header = new DefaultHttp2Headers(false);
+ header.scheme(metadata.scheme)
+ .authority(metadata.address)
+ .method(HttpMethod.POST.asciiName())
+ .path("/" + metadata.service + "/" + metadata.method.getMethodName())
+ .set(TripleHeaderEnum.CONTENT_TYPE_KEY.getHeader(), TripleConstant.CONTENT_PROTO)
+ .set(HttpHeaderNames.TE, HttpHeaderValues.TRAILERS);
+ setIfNotNull(header, TripleHeaderEnum.TIMEOUT.getHeader(), metadata.timeout);
+ if (!"1.0.0".equals(metadata.version)) {
+ setIfNotNull(header, TripleHeaderEnum.SERVICE_VERSION.getHeader(), metadata.version);
+ }
+ setIfNotNull(header, TripleHeaderEnum.SERVICE_GROUP.getHeader(), metadata.group);
+ setIfNotNull(header, TripleHeaderEnum.CONSUMER_APP_NAME_KEY.getHeader(), metadata.application);
+ setIfNotNull(header, TripleHeaderEnum.GRPC_ACCEPT_ENCODING.getHeader(), metadata.acceptEncoding);
+ if (!Identity.MESSAGE_ENCODING.equals(metadata.compressor.getMessageEncoding())) {
+ setIfNotNull(header, TripleHeaderEnum.GRPC_ENCODING.getHeader(), metadata.compressor.getMessageEncoding());
+ }
+ StreamUtils.convertAttachment(header, metadata.attachments);
+ return header;
+ }
+
+ private static void setIfNotNull(DefaultHttp2Headers headers, CharSequence key, CharSequence value) {
+ if (value == null) {
+ return;
+ }
+ headers.set(key, value);
+ }
+
+ private static AsciiString getSchemeFromUrl(URL url) {
+ boolean ssl = url.getParameter(CommonConstants.SSL_ENABLED_KEY, false);
+ return ssl ? TripleConstant.HTTPS_SCHEME : TripleConstant.HTTP_SCHEME;
+ }
+
+ /**
+ * Parse and put the KV pairs into metadata. Ignore Http2 PseudoHeaderName and internal name.
+ * Only raw byte array or string value will be put.
+ *
+ * @param headers the metadata holder
+ * @param attachments KV pairs
+ */
+ public static void convertAttachment(DefaultHttp2Headers headers, Map<String, Object> attachments) {
+ if (attachments == null) {
+ return;
+ }
+ for (Map.Entry<String, Object> entry : attachments.entrySet()) {
+ final String key = entry.getKey().toLowerCase(Locale.ROOT);
+ if (Http2Headers.PseudoHeaderName.isPseudoHeader(key)) {
+ continue;
+ }
+ if (TripleHeaderEnum.containsExcludeAttachments(key)) {
+ continue;
+ }
+ final Object v = entry.getValue();
+ convertSingleAttachment(headers, key, v);
+ }
+ }
+
+ /**
+ * Convert each user's attach value to metadata
+ *
+ * @param headers outbound headers
+ * @param key metadata key
+ * @param v metadata value (Metadata Only string and byte arrays are allowed)
+ */
+ private static void convertSingleAttachment(DefaultHttp2Headers headers, String key, Object v) {
+ try {
+ // todo Support boolean/ numbers
+ if (v instanceof String) {
+ String str = (String) v;
+ headers.set(key, str);
+ } else if (v instanceof byte[]) {
+ String str = H2TransportListener.encodeBase64ASCII((byte[]) v);
+ headers.set(key + TripleConstant.GRPC_BIN_SUFFIX, str);
+ }
+ } catch (Throwable t) {
+ LOGGER.warn("Meet exception when convert single attachment key:" + key + " value=" + v, t);
+ }
+ }
+
+
+}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/AbstractH2TransportListener.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/AbstractH2TransportListener.java
new file mode 100644
index 0000000..44870a2
--- /dev/null
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/AbstractH2TransportListener.java
@@ -0,0 +1,81 @@
+/*
+ * 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.common.logger.Logger;
+import org.apache.dubbo.common.logger.LoggerFactory;
+import org.apache.dubbo.rpc.protocol.tri.TripleConstant;
+import org.apache.dubbo.rpc.protocol.tri.TripleHeaderEnum;
+
+import io.netty.handler.codec.http2.Http2Headers;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+
+public abstract class AbstractH2TransportListener implements H2TransportListener {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(AbstractH2TransportListener.class);
+
+ /**
+ * Parse metadata to a KV pairs map.
+ *
+ * @param trailers the metadata from remote
+ * @return KV pairs map
+ */
+ protected Map<String, Object> headersToMap(Http2Headers trailers) {
+ if (trailers == null) {
+ return Collections.emptyMap();
+ }
+ Map<String, Object> attachments = new HashMap<>();
+ for (Map.Entry<CharSequence, CharSequence> header : trailers) {
+ String key = header.getKey().toString();
+ if (key.endsWith(TripleConstant.GRPC_BIN_SUFFIX) && key.length() > TripleConstant.GRPC_BIN_SUFFIX.length()) {
+ try {
+ String realKey = key.substring(0, key.length() - TripleConstant.GRPC_BIN_SUFFIX.length());
+ byte[] value = H2TransportListener.decodeASCIIByte(header.getValue());
+ attachments.put(realKey, value);
+ } catch (Exception e) {
+ LOGGER.error("Failed to parse response attachment key=" + key, e);
+ }
+ } else {
+ attachments.put(key, header.getValue().toString());
+ }
+ }
+ return attachments;
+ }
+
+
+ protected Map<String, String> filterReservedHeaders(Http2Headers trailers) {
+ if (trailers == null) {
+ return Collections.emptyMap();
+ }
+ Map<String, String> excludeHeaders = new HashMap<>();
+ for (Map.Entry<CharSequence, CharSequence> header : trailers) {
+ String key = header.getKey().toString();
+ if (Http2Headers.PseudoHeaderName.isPseudoHeader(key)) {
+ excludeHeaders.put(key, trailers.getAndRemove(key).toString());
+ }
+ if (TripleHeaderEnum.containsExcludeAttachments(key)) {
+ excludeHeaders.put(key, trailers.getAndRemove(key).toString());
+ }
+ }
+ return excludeHeaders;
+ }
+
+}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/GracefulShutdown.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/GracefulShutdown.java
similarity index 98%
rename from dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/GracefulShutdown.java
rename to dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/GracefulShutdown.java
index f526969..43852a9 100644
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/GracefulShutdown.java
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/GracefulShutdown.java
@@ -14,7 +14,8 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.dubbo.rpc.protocol.tri;
+
+package org.apache.dubbo.rpc.protocol.tri.transport;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TransportObserver.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/H2TransportListener.java
similarity index 54%
rename from dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TransportObserver.java
rename to dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/H2TransportListener.java
index 5beebb7..68ce827 100644
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TransportObserver.java
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/H2TransportListener.java
@@ -15,23 +15,44 @@
* limitations under the License.
*/
-package org.apache.dubbo.rpc.protocol.tri;
+package org.apache.dubbo.rpc.protocol.tri.transport;
+
+import org.apache.dubbo.rpc.protocol.tri.RpcStatus;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.handler.codec.http2.Http2Headers;
+
+import java.nio.charset.StandardCharsets;
+import java.util.Base64;
/**
* An observer used for transport messaging which provides full streaming support.
* A TransportObserver receives raw data or control messages from local/remote.
- * Implementations should prefer to extend {@link OutboundTransportObserver} and {@link InboundTransportObserver}
- * instead of this interface.
*/
-public interface TransportObserver {
+public interface H2TransportListener {
+ Base64.Decoder BASE64_DECODER = Base64.getDecoder();
+ Base64.Encoder BASE64_ENCODER = Base64.getEncoder().withoutPadding();
+
+ static String encodeBase64ASCII(byte[] in) {
+ byte[] bytes = encodeBase64(in);
+ return new String(bytes, StandardCharsets.US_ASCII);
+ }
+
+ static byte[] encodeBase64(byte[] in) {
+ return BASE64_ENCODER.encode(in);
+ }
+
+ static byte[] decodeASCIIByte(CharSequence value) {
+ return BASE64_DECODER.decode(value.toString().getBytes(StandardCharsets.US_ASCII));
+ }
/**
* Transport metadata
*
- * @param metadata metadata KV paris
+ * @param headers metadata KV paris
* @param endStream whether this data should terminate the stream
*/
- void onMetadata(Metadata metadata, boolean endStream);
+ void onHeader(Http2Headers headers, boolean endStream);
/**
* Transport data
@@ -39,18 +60,9 @@ public interface TransportObserver {
* @param data raw byte array
* @param endStream whether this data should terminate the stream
*/
- void onData(byte[] data, boolean endStream);
+ void onData(ByteBuf data, boolean endStream);
- /**
- * Error
- *
- * @param status error status
- */
- void onError(GrpcStatus status);
- /**
- * Set stream completed
- */
- void onComplete();
+ void cancelByRemote(RpcStatus status);
}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleClientHandler.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleClientHandler.java
similarity index 96%
rename from dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleClientHandler.java
rename to dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleClientHandler.java
index 96c8097..798d040 100644
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleClientHandler.java
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleClientHandler.java
@@ -14,7 +14,8 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.dubbo.rpc.protocol.tri;
+
+package org.apache.dubbo.rpc.protocol.tri.transport;
import org.apache.dubbo.remoting.api.ConnectionHandler;
import org.apache.dubbo.rpc.model.FrameworkModel;
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleCommandOutBoundHandler.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleCommandOutBoundHandler.java
similarity index 86%
rename from dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleCommandOutBoundHandler.java
rename to dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleCommandOutBoundHandler.java
index 7a0f5ea..741b3db 100644
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleCommandOutBoundHandler.java
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleCommandOutBoundHandler.java
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-package org.apache.dubbo.rpc.protocol.tri;
+package org.apache.dubbo.rpc.protocol.tri.transport;
import org.apache.dubbo.rpc.protocol.tri.command.QueuedCommand;
@@ -27,8 +27,8 @@ public class TripleCommandOutBoundHandler extends ChannelOutboundHandlerAdapter
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
- if (msg instanceof QueuedCommand.AbstractQueuedCommand) {
- QueuedCommand.AbstractQueuedCommand command = (QueuedCommand.AbstractQueuedCommand) msg;
+ if (msg instanceof QueuedCommand) {
+ QueuedCommand command = (QueuedCommand) msg;
command.send(ctx, promise);
} else {
super.write(ctx, msg, promise);
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleHttp2ClientResponseHandler.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleHttp2ClientResponseHandler.java
similarity index 51%
rename from dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleHttp2ClientResponseHandler.java
rename to dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleHttp2ClientResponseHandler.java
index eb14bee..105a732 100644
--- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleHttp2ClientResponseHandler.java
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleHttp2ClientResponseHandler.java
@@ -14,27 +14,28 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.dubbo.rpc.protocol.tri;
+
+package org.apache.dubbo.rpc.protocol.tri.transport;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
+import org.apache.dubbo.rpc.protocol.tri.RpcStatus;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http2.Http2DataFrame;
import io.netty.handler.codec.http2.Http2GoAwayFrame;
-import io.netty.handler.codec.http2.Http2Headers;
import io.netty.handler.codec.http2.Http2HeadersFrame;
import io.netty.handler.codec.http2.Http2ResetFrame;
import io.netty.handler.codec.http2.Http2StreamFrame;
-import static org.apache.dubbo.rpc.protocol.tri.Compressor.DEFAULT_COMPRESSOR;
-
public final class TripleHttp2ClientResponseHandler extends SimpleChannelInboundHandler<Http2StreamFrame> {
private static final Logger LOGGER = LoggerFactory.getLogger(TripleHttp2ClientResponseHandler.class);
+ private final H2TransportListener transportListener;
- public TripleHttp2ClientResponseHandler() {
+ public TripleHttp2ClientResponseHandler(H2TransportListener listener) {
super(false);
+ this.transportListener = listener;
}
@Override
@@ -53,66 +54,29 @@ public final class TripleHttp2ClientResponseHandler extends SimpleChannelInbound
@Override
protected void channelRead0(ChannelHandlerContext ctx, Http2StreamFrame msg) throws Exception {
if (msg instanceof Http2HeadersFrame) {
- onHeadersRead(ctx, (Http2HeadersFrame) msg);
+ final Http2HeadersFrame headers = (Http2HeadersFrame) msg;
+ transportListener.onHeader(headers.headers(), headers.isEndStream());
} else if (msg instanceof Http2DataFrame) {
- onDataRead(ctx, (Http2DataFrame) msg);
+ final Http2DataFrame data = (Http2DataFrame) msg;
+ transportListener.onData(data.content(), data.isEndStream());
} else {
super.channelRead(ctx, msg);
}
}
private void onResetRead(ChannelHandlerContext ctx, Http2ResetFrame resetFrame) {
- final AbstractClientStream clientStream = ctx.channel().attr(TripleConstant.CLIENT_STREAM_KEY).get();
LOGGER.warn("Triple Client received remote reset errorCode=" + resetFrame.errorCode());
- clientStream.cancelByRemote();
+ transportListener.cancelByRemote(RpcStatus.CANCELLED);
ctx.close();
}
- private void onHeadersRead(ChannelHandlerContext ctx, Http2HeadersFrame msg) {
- Http2Headers headers = msg.headers();
- final AbstractClientStream clientStream = ctx.channel().attr(TripleConstant.CLIENT_STREAM_KEY).get();
- CharSequence messageEncoding = headers.get(TripleHeaderEnum.GRPC_ENCODING.getHeader());
- if (null != messageEncoding) {
- String compressorStr = messageEncoding.toString();
- if (!DEFAULT_COMPRESSOR.equals(compressorStr)) {
- Compressor compressor = Compressor.getCompressor(clientStream.getUrl().getOrDefaultFrameworkModel(), compressorStr);
- if (null == compressor) {
- throw GrpcStatus.fromCode(GrpcStatus.Code.UNIMPLEMENTED)
- .withDescription(String.format("Grpc-encoding '%s' is not supported", compressorStr))
- .asException();
- } else {
- clientStream.setDeCompressor(compressor);
- }
- }
- }
- final TransportObserver observer = clientStream.inboundTransportObserver();
- observer.onMetadata(new Http2HeaderMeta(headers), false);
- if (msg.isEndStream()) {
- observer.onComplete();
- }
- }
-
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
- final AbstractClientStream clientStream = ctx.channel().attr(TripleConstant.CLIENT_STREAM_KEY).get();
- final GrpcStatus status = GrpcStatus.fromCode(GrpcStatus.Code.INTERNAL)
+ final RpcStatus status = RpcStatus.INTERNAL
.withCause(cause);
- Metadata metadata = new DefaultMetadata();
- metadata.put(TripleHeaderEnum.STATUS_KEY.getHeader(), Integer.toString(status.code.code));
- metadata.put(TripleHeaderEnum.MESSAGE_KEY.getHeader(), status.toMessage());
LOGGER.warn("Meet Exception on ClientResponseHandler, status code is: " + status.code, cause);
- clientStream.inboundMessageObserver().onError(status.asException());
+ transportListener.cancelByRemote(status);
ctx.close();
}
- public void onDataRead(ChannelHandlerContext ctx, Http2DataFrame msg) throws Exception {
- super.channelRead(ctx, msg.content());
- if (msg.isEndStream()) {
- final AbstractClientStream clientStream = ctx.channel().attr(TripleConstant.CLIENT_STREAM_KEY).get();
- // stream already closed;
- if (clientStream != null) {
- clientStream.inboundTransportObserver().onComplete();
- }
- }
- }
}
diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleHttp2FrameServerHandler.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleHttp2FrameServerHandler.java
new file mode 100644
index 0000000..5384fc1
--- /dev/null
+++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleHttp2FrameServerHandler.java
@@ -0,0 +1,115 @@
+/*
+ * 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.common.logger.Logger;
+import org.apache.dubbo.common.logger.LoggerFactory;
+import org.apache.dubbo.rpc.HeaderFilter;
+import org.apache.dubbo.rpc.model.FrameworkModel;
+import org.apache.dubbo.rpc.protocol.tri.PathResolver;
+import org.apache.dubbo.rpc.protocol.tri.RpcStatus;
+import org.apache.dubbo.rpc.protocol.tri.TripleConstant;
+import org.apache.dubbo.rpc.protocol.tri.pack.GenericUnpack;
+import org.apache.dubbo.rpc.protocol.tri.stream.ServerStream;
+
+import io.netty.channel.ChannelDuplexHandler;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.handler.codec.http2.Http2DataFrame;
+import io.netty.handler.codec.http2.Http2HeadersFrame;
+import io.netty.handler.codec.http2.Http2ResetFrame;
+import io.netty.util.ReferenceCountUtil;
+import io.netty.util.ReferenceCounted;
+
+import java.util.List;
+import java.util.concurrent.Executor;
+
+public class TripleHttp2FrameServerHandler extends ChannelDuplexHandler {
... 2183 lines suppressed ...