repo stringclasses 1k
values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 6
values | commit_sha stringclasses 1k
values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/EchoFilterTest.java | dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/EchoFilterTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.filter;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.AppResponse;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.support.DemoService;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
class EchoFilterTest {
Filter echoFilter = new EchoFilter();
@SuppressWarnings("unchecked")
@Test
void testEcho() {
Invocation invocation = createMockRpcInvocation();
Invoker<DemoService> invoker = createMockInvoker(invocation);
given(invocation.getMethodName()).willReturn("$echo");
Result filterResult = echoFilter.invoke(invoker, invocation);
assertEquals("hello", filterResult.getValue());
}
@SuppressWarnings("unchecked")
@Test
void testNonEcho() {
Invocation invocation = createMockRpcInvocation();
Invoker<DemoService> invoker = createMockInvoker(invocation);
given(invocation.getMethodName()).willReturn("echo");
Result filterResult = echoFilter.invoke(invoker, invocation);
assertEquals("High", filterResult.getValue());
}
Invocation createMockRpcInvocation() {
Invocation invocation = mock(RpcInvocation.class);
given(invocation.getParameterTypes()).willReturn(new Class<?>[] {Enum.class});
given(invocation.getArguments()).willReturn(new Object[] {"hello"});
given(invocation.getObjectAttachments()).willReturn(null);
return invocation;
}
Invoker<DemoService> createMockInvoker(Invocation invocation) {
Invoker<DemoService> invoker = mock(Invoker.class);
given(invoker.isAvailable()).willReturn(true);
given(invoker.getInterface()).willReturn(DemoService.class);
AppResponse result = new AppResponse();
result.setValue("High");
given(invoker.invoke(invocation)).willReturn(result);
URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1");
given(invoker.getUrl()).willReturn(url);
return invoker;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ExecuteLimitFilterTest.java | dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ExecuteLimitFilterTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.filter;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.AppResponse;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.RpcStatus;
import org.apache.dubbo.rpc.support.BlockMyInvoker;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.when;
class ExecuteLimitFilterTest {
private ExecuteLimitFilter executeLimitFilter = new ExecuteLimitFilter();
@Test
void testNoExecuteLimitInvoke() {
Invoker invoker = Mockito.mock(Invoker.class);
when(invoker.invoke(any(Invocation.class))).thenReturn(new AppResponse("result"));
when(invoker.getUrl()).thenReturn(URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1"));
Invocation invocation = Mockito.mock(Invocation.class);
when(invocation.getMethodName()).thenReturn("testNoExecuteLimitInvoke");
Result result = executeLimitFilter.invoke(invoker, invocation);
Assertions.assertEquals("result", result.getValue());
}
@Test
void testExecuteLimitInvoke() {
Invoker invoker = Mockito.mock(Invoker.class);
when(invoker.invoke(any(Invocation.class))).thenReturn(new AppResponse("result"));
when(invoker.getUrl())
.thenReturn(URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&executes=10"));
Invocation invocation = Mockito.mock(Invocation.class);
when(invocation.getMethodName()).thenReturn("testExecuteLimitInvoke");
Result result = executeLimitFilter.invoke(invoker, invocation);
Assertions.assertEquals("result", result.getValue());
}
@Test
void testExecuteLimitInvokeWithException() {
Invoker invoker = Mockito.mock(Invoker.class);
doThrow(new RpcException()).when(invoker).invoke(any(Invocation.class));
URL url = URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&executes=10");
when(invoker.getUrl()).thenReturn(url);
Invocation invocation = Mockito.mock(Invocation.class);
when(invocation.getMethodName()).thenReturn("testExecuteLimitInvokeWitException");
try {
executeLimitFilter.invoke(invoker, invocation);
} catch (Exception e) {
Assertions.assertTrue(e instanceof RpcException);
executeLimitFilter.onError(e, invoker, invocation);
}
Assertions.assertEquals(
1, RpcStatus.getStatus(url, invocation.getMethodName()).getFailed());
RpcStatus.removeStatus(url, invocation.getMethodName());
}
@Test
void testMoreThanExecuteLimitInvoke() {
int maxExecute = 10;
int totalExecute = 20;
final AtomicInteger failed = new AtomicInteger(0);
final Invocation invocation = Mockito.mock(RpcInvocation.class);
when(invocation.getMethodName()).thenReturn("testMoreThanExecuteLimitInvoke");
URL url = URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&executes=" + maxExecute);
final Invoker<ExecuteLimitFilter> invoker = new BlockMyInvoker<>(url, 1000);
final CountDownLatch latchThatWaitsAllThreadStarted = new CountDownLatch(1);
final CountDownLatch latchThatWaitsAllThreadFinished = new CountDownLatch(totalExecute);
for (int i = 0; i < totalExecute; i++) {
Thread thread = new Thread(() -> {
try {
latchThatWaitsAllThreadStarted.await();
executeLimitFilter.invoke(invoker, invocation);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (RpcException expected) {
failed.incrementAndGet();
} finally {
latchThatWaitsAllThreadFinished.countDown();
}
});
thread.start();
}
latchThatWaitsAllThreadStarted.countDown();
try {
latchThatWaitsAllThreadFinished.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
Assertions.assertEquals(totalExecute - maxExecute, failed.get());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/TimeoutFilterTest.java | dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/TimeoutFilterTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.filter;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.AppResponse;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.support.BlockMyInvoker;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.when;
class TimeoutFilterTest {
private TimeoutFilter timeoutFilter = new TimeoutFilter();
@Test
void testInvokeWithoutTimeout() {
int timeout = 3000;
Invoker invoker = Mockito.mock(Invoker.class);
when(invoker.invoke(any(Invocation.class))).thenReturn(new AppResponse("result"));
when(invoker.getUrl())
.thenReturn(
URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&timeout=" + timeout));
Invocation invocation = Mockito.mock(Invocation.class);
when(invocation.getMethodName()).thenReturn("testInvokeWithoutTimeout");
Result result = timeoutFilter.invoke(invoker, invocation);
Assertions.assertEquals("result", result.getValue());
}
@Test
void testInvokeWithTimeout() {
int timeout = 100;
URL url = URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&timeout=" + timeout);
Invoker invoker = new BlockMyInvoker(url, (timeout + 100));
Invocation invocation = Mockito.mock(RpcInvocation.class);
when(invocation.getMethodName()).thenReturn("testInvokeWithTimeout");
Result result = timeoutFilter.invoke(invoker, invocation);
Assertions.assertEquals("Dubbo", result.getValue());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/DeprecatedFilterTest.java | dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/DeprecatedFilterTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.filter;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.LogUtil;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.support.DemoService;
import org.apache.dubbo.rpc.support.MockInvocation;
import org.apache.dubbo.rpc.support.MyInvoker;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.rpc.Constants.DEPRECATED_KEY;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* DeprecatedFilterTest.java
*/
class DeprecatedFilterTest {
Filter deprecatedFilter = new DeprecatedFilter();
@Test
void testDeprecatedFilter() {
URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1&echo." + DEPRECATED_KEY + "=true");
LogUtil.start();
deprecatedFilter.invoke(new MyInvoker<DemoService>(url), new MockInvocation());
assertEquals(
1,
LogUtil.findMessage(
"The service method org.apache.dubbo.rpc.support.DemoService.echo(String) is DEPRECATED"));
LogUtil.stop();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ActiveLimitFilterTest.java | dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ActiveLimitFilterTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.filter;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.RpcStatus;
import org.apache.dubbo.rpc.support.BlockMyInvoker;
import org.apache.dubbo.rpc.support.MockInvocation;
import org.apache.dubbo.rpc.support.MyInvoker;
import org.apache.dubbo.rpc.support.RuntimeExceptionInvoker;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.fail;
/**
* ActiveLimitFilterTest.java
*/
class ActiveLimitFilterTest {
ActiveLimitFilter activeLimitFilter = new ActiveLimitFilter();
@Test
void testInvokeNoActives() {
URL url = URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&actives=0");
Invoker<ActiveLimitFilterTest> invoker = new MyInvoker<ActiveLimitFilterTest>(url);
Invocation invocation = new MockInvocation();
activeLimitFilter.invoke(invoker, invocation);
}
@Test
void testInvokeLessActives() {
URL url = URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&actives=10");
Invoker<ActiveLimitFilterTest> invoker = new MyInvoker<ActiveLimitFilterTest>(url);
Invocation invocation = new MockInvocation();
activeLimitFilter.invoke(invoker, invocation);
}
@Test
void testInvokeGreaterActives() {
AtomicInteger count = new AtomicInteger(0);
URL url = URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&actives=1&timeout=1");
final Invoker<ActiveLimitFilterTest> invoker = new BlockMyInvoker<ActiveLimitFilterTest>(url, 100);
final Invocation invocation = new MockInvocation();
final CountDownLatch latch = new CountDownLatch(1);
for (int i = 0; i < 100; i++) {
Thread thread = new Thread(new Runnable() {
public void run() {
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 0; i < 100; i++) {
try {
activeLimitFilter.invoke(invoker, invocation);
} catch (RpcException expected) {
count.incrementAndGet();
}
}
}
});
thread.start();
}
latch.countDown();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
assertNotSame(0, count.intValue());
}
@Test
void testInvokeTimeOut() {
int totalThread = 100;
int maxActives = 10;
long timeout = 1;
long blockTime = 100;
AtomicInteger count = new AtomicInteger(0);
final CountDownLatch latch = new CountDownLatch(1);
final CountDownLatch latchBlocking = new CountDownLatch(totalThread);
URL url = URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&actives=" + maxActives
+ "&timeout=" + timeout);
final Invoker<ActiveLimitFilterTest> invoker = new BlockMyInvoker<ActiveLimitFilterTest>(url, blockTime);
final Invocation invocation = new MockInvocation();
RpcStatus.removeStatus(url);
RpcStatus.removeStatus(url, invocation.getMethodName());
for (int i = 0; i < totalThread; i++) {
Thread thread = new Thread(new Runnable() {
public void run() {
try {
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
Result asyncResult = activeLimitFilter.invoke(invoker, invocation);
Result result = asyncResult.get();
activeLimitFilter.onResponse(result, invoker, invocation);
} catch (RpcException expected) {
count.incrementAndGet();
} catch (Exception e) {
fail();
}
} finally {
latchBlocking.countDown();
}
}
});
thread.start();
}
latch.countDown();
try {
latchBlocking.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
assertEquals(90, count.intValue());
}
@Test
void testInvokeNotTimeOut() {
int totalThread = 100;
int maxActives = 10;
long timeout = 100000;
long blockTime = 0;
AtomicInteger count = new AtomicInteger(0);
final CountDownLatch latch = new CountDownLatch(1);
final CountDownLatch latchBlocking = new CountDownLatch(totalThread);
URL url = URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&actives=" + maxActives
+ "&timeout=" + timeout);
final Invoker<ActiveLimitFilterTest> invoker = new BlockMyInvoker<ActiveLimitFilterTest>(url, blockTime);
final Invocation invocation = new MockInvocation();
for (int i = 0; i < totalThread; i++) {
Thread thread = new Thread(new Runnable() {
public void run() {
try {
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
Result asyncResult = activeLimitFilter.invoke(invoker, invocation);
Result result = asyncResult.get();
activeLimitFilter.onResponse(result, invoker, invocation);
} catch (RpcException expected) {
count.incrementAndGet();
activeLimitFilter.onError(expected, invoker, invocation);
} catch (Exception e) {
fail();
}
} finally {
latchBlocking.countDown();
}
}
});
thread.start();
}
latch.countDown();
try {
latchBlocking.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
assertEquals(0, count.intValue());
}
@Test
void testInvokeRuntimeException() {
Assertions.assertThrows(RuntimeException.class, () -> {
URL url = URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&actives=0");
Invoker<ActiveLimitFilterTest> invoker = new RuntimeExceptionInvoker(url);
Invocation invocation = new MockInvocation();
RpcStatus count = RpcStatus.getStatus(invoker.getUrl(), invocation.getMethodName());
int beforeExceptionActiveCount = count.getActive();
activeLimitFilter.invoke(invoker, invocation);
int afterExceptionActiveCount = count.getActive();
assertEquals(
beforeExceptionActiveCount,
afterExceptionActiveCount,
"After exception active count should be same");
});
}
@Test
void testInvokeRuntimeExceptionWithActiveCountMatch() {
URL url = URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&actives=0");
Invoker<ActiveLimitFilterTest> invoker = new RuntimeExceptionInvoker(url);
Invocation invocation = new MockInvocation();
RpcStatus count = RpcStatus.getStatus(invoker.getUrl(), invocation.getMethodName());
int beforeExceptionActiveCount = count.getActive();
try {
activeLimitFilter.invoke(invoker, invocation);
} catch (RuntimeException ex) {
activeLimitFilter.onError(ex, invoker, invocation);
int afterExceptionActiveCount = count.getActive();
assertEquals(
beforeExceptionActiveCount,
afterExceptionActiveCount,
"After exception active count should be same");
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ClassLoaderFilterTest.java | dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ClassLoaderFilterTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.filter;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.model.ServiceModel;
import org.apache.dubbo.rpc.support.DemoService;
import org.apache.dubbo.rpc.support.MyInvoker;
import java.net.URLClassLoader;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
class ClassLoaderFilterTest {
private ClassLoaderFilter classLoaderFilter = new ClassLoaderFilter();
@Test
void testInvoke() throws Exception {
URL url = URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1");
String path = DemoService.class.getResource("/").getPath();
final URLClassLoader cl = new URLClassLoader(new java.net.URL[] {new java.net.URL("file:" + path)}) {
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
try {
return findClass(name);
} catch (ClassNotFoundException e) {
return super.loadClass(name);
}
}
};
final Class<?> clazz = cl.loadClass(DemoService.class.getCanonicalName());
Invoker invoker = new MyInvoker(url) {
@Override
public Class getInterface() {
return clazz;
}
@Override
public Result invoke(Invocation invocation) throws RpcException {
Assertions.assertEquals(cl, Thread.currentThread().getContextClassLoader());
return null;
}
};
Invocation invocation = Mockito.mock(Invocation.class);
ServiceModel serviceModel = Mockito.mock(ServiceModel.class);
Mockito.when(serviceModel.getClassLoader()).thenReturn(cl);
Mockito.when(invocation.getServiceModel()).thenReturn(serviceModel);
classLoaderFilter.invoke(invoker, invocation);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/tps/TpsLimitFilterTest.java | dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/tps/TpsLimitFilterTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.filter.tps;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.filter.TpsLimitFilter;
import org.apache.dubbo.rpc.support.MockInvocation;
import org.apache.dubbo.rpc.support.MyInvoker;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY;
import static org.apache.dubbo.rpc.Constants.TPS_LIMIT_RATE_KEY;
import static org.junit.jupiter.api.Assertions.assertTrue;
class TpsLimitFilterTest {
private TpsLimitFilter filter = new TpsLimitFilter();
@Test
void testWithoutCount() throws Exception {
URL url = URL.valueOf("test://test");
url = url.addParameter(INTERFACE_KEY, "org.apache.dubbo.rpc.file.TpsService");
url = url.addParameter(TPS_LIMIT_RATE_KEY, 5);
Invoker<TpsLimitFilterTest> invoker = new MyInvoker<TpsLimitFilterTest>(url);
Invocation invocation = new MockInvocation();
filter.invoke(invoker, invocation);
}
@Test
void testFail() throws Exception {
Assertions.assertThrows(RpcException.class, () -> {
URL url = URL.valueOf("test://test");
url = url.addParameter(INTERFACE_KEY, "org.apache.dubbo.rpc.file.TpsService");
url = url.addParameter(TPS_LIMIT_RATE_KEY, 5);
Invoker<TpsLimitFilterTest> invoker = new MyInvoker<TpsLimitFilterTest>(url);
Invocation invocation = new MockInvocation();
for (int i = 0; i < 10; i++) {
Result re = filter.invoke(invoker, invocation);
if (i >= 5) {
assertTrue(re.hasException());
throw re.getException();
}
}
});
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/tps/DefaultTPSLimiterTest.java | dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/tps/DefaultTPSLimiterTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.filter.tps;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.support.MockInvocation;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY;
import static org.apache.dubbo.rpc.Constants.TPS_LIMIT_INTERVAL_KEY;
import static org.apache.dubbo.rpc.Constants.TPS_LIMIT_RATE_KEY;
class DefaultTPSLimiterTest {
private static final int TEST_LIMIT_RATE = 2;
private final DefaultTPSLimiter defaultTPSLimiter = new DefaultTPSLimiter();
@Test
void testIsAllowable() {
Invocation invocation = new MockInvocation();
URL url = URL.valueOf("test://test");
url = url.addParameter(INTERFACE_KEY, "org.apache.dubbo.rpc.file.TpsService");
url = url.addParameter(TPS_LIMIT_RATE_KEY, TEST_LIMIT_RATE);
url = url.addParameter(TPS_LIMIT_INTERVAL_KEY, 1000);
for (int i = 1; i <= TEST_LIMIT_RATE; i++) {
Assertions.assertTrue(defaultTPSLimiter.isAllowable(url, invocation));
}
}
@Test
void testIsNotAllowable() {
Invocation invocation = new MockInvocation();
URL url = URL.valueOf("test://test");
url = url.addParameter(INTERFACE_KEY, "org.apache.dubbo.rpc.file.TpsService");
url = url.addParameter(TPS_LIMIT_RATE_KEY, TEST_LIMIT_RATE);
url = url.addParameter(TPS_LIMIT_INTERVAL_KEY, 1000);
for (int i = 1; i <= TEST_LIMIT_RATE + 1; i++) {
if (i == TEST_LIMIT_RATE + 1) {
Assertions.assertFalse(defaultTPSLimiter.isAllowable(url, invocation));
} else {
Assertions.assertTrue(defaultTPSLimiter.isAllowable(url, invocation));
}
}
}
@Test
void testMethodLevelTpsOverridesServiceLevel() {
Invocation invocation = new MockInvocation();
URL url = URL.valueOf("test://test");
url = url.addParameter(INTERFACE_KEY, "org.apache.dubbo.rpc.file.TpsService");
url = url.addParameter(TPS_LIMIT_RATE_KEY, TEST_LIMIT_RATE);
int tpsConfigForMethodLevel = 3;
url = url.addParameter("tps", 1);
url = url.addParameter("echo.tps", tpsConfigForMethodLevel);
url = url.addParameter(TPS_LIMIT_INTERVAL_KEY, 1000);
for (int i = 1; i <= tpsConfigForMethodLevel + 1; i++) {
if (i == tpsConfigForMethodLevel + 1) {
Assertions.assertFalse(defaultTPSLimiter.isAllowable(url, invocation));
} else {
Assertions.assertTrue(defaultTPSLimiter.isAllowable(url, invocation));
}
}
}
@Test
void testServiceLevelTpsWhenOtherMethodsHaveTps() {
Invocation invocation = new MockInvocation();
URL url = URL.valueOf("test://test");
url = url.addParameter(INTERFACE_KEY, "org.apache.dubbo.rpc.file.TpsService");
url = url.addParameter(TPS_LIMIT_RATE_KEY, TEST_LIMIT_RATE);
int tpsConfigForServiceLevel = 3;
url = url.addParameter("tps", tpsConfigForServiceLevel);
url = url.addParameter("otherMethod.tps", 1);
url = url.addParameter(TPS_LIMIT_INTERVAL_KEY, 1000);
for (int i = 1; i <= tpsConfigForServiceLevel + 1; i++) {
if (i == tpsConfigForServiceLevel + 1) {
Assertions.assertFalse(defaultTPSLimiter.isAllowable(url, invocation));
} else {
Assertions.assertTrue(defaultTPSLimiter.isAllowable(url, invocation));
}
}
}
@Test
void testMethodLevelTpsIsolation() {
Invocation invocation = new MockInvocation();
URL url = URL.valueOf("test://test");
url = url.addParameter(INTERFACE_KEY, "org.apache.dubbo.rpc.file.TpsService");
url = url.addParameter(TPS_LIMIT_RATE_KEY, TEST_LIMIT_RATE);
int tpsConfigForMethodLevel = 3;
url = url.addParameter("tps", 1);
url = url.addParameter("otherMethod.tps", 2);
url = url.addParameter("echo.tps", tpsConfigForMethodLevel);
url = url.addParameter(TPS_LIMIT_INTERVAL_KEY, 1000);
for (int i = 1; i <= tpsConfigForMethodLevel + 1; i++) {
if (i == tpsConfigForMethodLevel + 1) {
Assertions.assertFalse(defaultTPSLimiter.isAllowable(url, invocation));
} else {
Assertions.assertTrue(defaultTPSLimiter.isAllowable(url, invocation));
}
}
}
@Test
void testConfigChange() {
Invocation invocation = new MockInvocation();
URL url = URL.valueOf("test://test");
url = url.addParameter(INTERFACE_KEY, "org.apache.dubbo.rpc.file.TpsService");
url = url.addParameter(TPS_LIMIT_RATE_KEY, TEST_LIMIT_RATE);
url = url.addParameter(TPS_LIMIT_INTERVAL_KEY, 1000);
for (int i = 1; i <= TEST_LIMIT_RATE; i++) {
Assertions.assertTrue(defaultTPSLimiter.isAllowable(url, invocation));
}
final int tenTimesLimitRate = TEST_LIMIT_RATE * 10;
url = url.addParameter(TPS_LIMIT_RATE_KEY, tenTimesLimitRate);
for (int i = 1; i <= tenTimesLimitRate; i++) {
Assertions.assertTrue(defaultTPSLimiter.isAllowable(url, invocation));
}
Assertions.assertFalse(defaultTPSLimiter.isAllowable(url, invocation));
}
@Test
void testMultiThread() throws InterruptedException {
Invocation invocation = new MockInvocation();
URL url = URL.valueOf("test://test");
url = url.addParameter(INTERFACE_KEY, "org.apache.dubbo.rpc.file.TpsService");
url = url.addParameter(TPS_LIMIT_RATE_KEY, 100);
url = url.addParameter(TPS_LIMIT_INTERVAL_KEY, 100000);
List<Task> taskList = new ArrayList<>();
int threadNum = 50;
CountDownLatch stopLatch = new CountDownLatch(threadNum);
CountDownLatch startLatch = new CountDownLatch(1);
for (int i = 0; i < threadNum; i++) {
taskList.add(new Task(defaultTPSLimiter, url, invocation, startLatch, stopLatch));
}
startLatch.countDown();
stopLatch.await();
Assertions.assertEquals(
taskList.stream().map(Task::getCount).reduce(Integer::sum).get(), 100);
}
static class Task implements Runnable {
private final DefaultTPSLimiter defaultTPSLimiter;
private final URL url;
private final Invocation invocation;
private final CountDownLatch startLatch;
private final CountDownLatch stopLatch;
private int count;
public Task(
DefaultTPSLimiter defaultTPSLimiter,
URL url,
Invocation invocation,
CountDownLatch startLatch,
CountDownLatch stopLatch) {
this.defaultTPSLimiter = defaultTPSLimiter;
this.url = url;
this.invocation = invocation;
this.startLatch = startLatch;
this.stopLatch = stopLatch;
new Thread(this).start();
}
@Override
public void run() {
try {
startLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int j = 0; j < 10000; j++) {
count = defaultTPSLimiter.isAllowable(url, invocation) ? count + 1 : count;
}
stopLatch.countDown();
}
public int getCount() {
return count;
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/tps/StatItemTest.java | dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/tps/StatItemTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.filter.tps;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class StatItemTest {
private StatItem statItem;
@AfterEach
public void tearDown() throws Exception {
statItem = null;
}
@Test
void testIsAllowable() throws Exception {
statItem = new StatItem("test", 5, 1000L);
long lastResetTime = statItem.getLastResetTime();
assertTrue(statItem.isAllowable());
Thread.sleep(1100L);
assertTrue(statItem.isAllowable());
assertTrue(lastResetTime != statItem.getLastResetTime());
assertEquals(4, statItem.getToken());
}
@Test
void testAccuracy() throws Exception {
final int EXPECTED_RATE = 5;
statItem = new StatItem("test", EXPECTED_RATE, 60_000L);
for (int i = 1; i <= EXPECTED_RATE; i++) {
assertTrue(statItem.isAllowable());
}
// Must block the 6th item
assertFalse(statItem.isAllowable());
}
@Test
void testConcurrency() throws Exception {
statItem = new StatItem("test", 100, 100000);
List<Task> taskList = new ArrayList<>();
int threadNum = 50;
CountDownLatch stopLatch = new CountDownLatch(threadNum);
CountDownLatch startLatch = new CountDownLatch(1);
for (int i = 0; i < threadNum; i++) {
taskList.add(new Task(statItem, startLatch, stopLatch));
}
startLatch.countDown();
stopLatch.await();
Assertions.assertEquals(
taskList.stream().map(Task::getCount).reduce(Integer::sum).get(), 100);
}
static class Task implements Runnable {
private final StatItem statItem;
private final CountDownLatch startLatch;
private final CountDownLatch stopLatch;
private int count;
public Task(StatItem statItem, CountDownLatch startLatch, CountDownLatch stopLatch) {
this.statItem = statItem;
this.startLatch = startLatch;
this.stopLatch = stopLatch;
new Thread(this).start();
}
@Override
public void run() {
try {
startLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int j = 0; j < 10000; j++) {
count = statItem.isAllowable() ? count + 1 : count;
}
stopLatch.countDown();
}
public int getCount() {
return count;
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/RemoteService.java | dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/RemoteService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.proxy;
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface RemoteService extends Remote {
String sayHello(String name) throws RemoteException;
String getThreadName() throws RemoteException;
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/DemoRequest.java | dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/DemoRequest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.proxy;
import java.io.Serializable;
/**
* TestRequest.
*/
class DemoRequest implements Serializable {
private static final long serialVersionUID = -2579095288792344869L;
private String mServiceName;
private String mMethodName;
private Class<?>[] mParameterTypes;
private Object[] mArguments;
public DemoRequest(String serviceName, String methodName, Class<?>[] parameterTypes, Object[] args) {
mServiceName = serviceName;
mMethodName = methodName;
mParameterTypes = parameterTypes;
mArguments = args;
}
public String getServiceName() {
return mServiceName;
}
public String getMethodName() {
return mMethodName;
}
public Class<?>[] getParameterTypes() {
return mParameterTypes;
}
public Object[] getArguments() {
return mArguments;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/Type.java | dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/Type.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.proxy;
public enum Type {
High,
Normal,
Lower
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/DemoServiceImpl.java | dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/DemoServiceImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.proxy;
import org.apache.dubbo.rpc.RpcContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DemoServiceImpl implements DemoService {
private static final Logger logger = LoggerFactory.getLogger(DemoServiceImpl.class);
public DemoServiceImpl() {
super();
}
public void sayHello(String name) {
logger.info("hello {}", name);
}
public String echo(String text) {
return text;
}
public long timestamp() {
return System.currentTimeMillis();
}
public String getThreadName() {
return Thread.currentThread().getName();
}
public int getSize(String[] strs) {
if (strs == null) return -1;
return strs.length;
}
public int getSize(Object[] os) {
if (os == null) return -1;
return os.length;
}
public Object invoke(String service, String method) throws Exception {
logger.info(
"RpcContext.getServerAttachment().getRemoteHost()={}",
RpcContext.getServiceContext().getRemoteHost());
return service + ":" + method;
}
public Type enumlength(Type... types) {
if (types.length == 0) return Type.Lower;
return types[0];
}
public int stringLength(String str) {
return str.length();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/DemoService.java | dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/DemoService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.proxy;
public interface DemoService {
void sayHello(String name);
String echo(String text);
long timestamp();
String getThreadName();
int getSize(String[] strs);
int getSize(Object[] os);
Object invoke(String service, String method) throws Exception;
int stringLength(String str);
Type enumlength(Type... types);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/InvokerInvocationHandlerTest.java | dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/InvokerInvocationHandlerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.proxy;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invoker;
import java.lang.reflect.Method;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.mockito.Mockito.when;
class InvokerInvocationHandlerTest {
private Invoker<?> invoker;
private InvokerInvocationHandler invokerInvocationHandler;
@BeforeEach
public void setUp() {
URL url = URL.valueOf("mock://localhost:8080/FooService?group=mock&version=1.0.0");
invoker = Mockito.mock(Invoker.class);
when(invoker.getUrl()).thenReturn(url);
invokerInvocationHandler = new InvokerInvocationHandler(invoker);
}
@Test
void testInvokeToString() throws Throwable {
String methodName = "toString";
when(invoker.toString()).thenReturn(methodName);
Method method = invoker.getClass().getMethod(methodName);
Object result = invokerInvocationHandler.invoke(null, method, new Object[] {});
Assertions.assertEquals(methodName, result);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/AbstractProxyTest.java | dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/AbstractProxyTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.proxy;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.ProxyFactory;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.service.Destroyable;
import org.apache.dubbo.rpc.service.EchoService;
import org.apache.dubbo.rpc.support.DemoService;
import org.apache.dubbo.rpc.support.DemoServiceImpl;
import org.apache.dubbo.rpc.support.MyInvoker;
import java.util.Arrays;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public abstract class AbstractProxyTest {
public static ProxyFactory factory;
@Test
void testGetProxy() {
URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1");
MyInvoker<DemoService> invoker = new MyInvoker<>(url);
DemoService proxy = factory.getProxy(invoker);
Assertions.assertNotNull(proxy);
Assertions.assertTrue(Arrays.asList(proxy.getClass().getInterfaces()).contains(DemoService.class));
Assertions.assertTrue(Arrays.asList(proxy.getClass().getInterfaces()).contains(Destroyable.class));
Assertions.assertTrue(Arrays.asList(proxy.getClass().getInterfaces()).contains(EchoService.class));
Assertions.assertEquals(
invoker.invoke(new RpcInvocation(
"echo",
DemoService.class.getName(),
DemoService.class.getName() + ":dubbo",
new Class[] {String.class},
new Object[] {"aa"}))
.getValue(),
proxy.echo("aa"));
Destroyable destroyable = (Destroyable) proxy;
destroyable.$destroy();
Assertions.assertTrue(invoker.isDestroyed());
}
@Test
void testGetInvoker() {
URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1");
DemoService origin = new DemoServiceImpl();
Invoker<DemoService> invoker = factory.getInvoker(new DemoServiceImpl(), DemoService.class, url);
Assertions.assertEquals(invoker.getInterface(), DemoService.class);
Assertions.assertEquals(
invoker.invoke(new RpcInvocation(
"echo",
DemoService.class.getName(),
DemoService.class.getName() + ":dubbo",
new Class[] {String.class},
new Object[] {"aa"}))
.getValue(),
origin.echo("aa"));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/MethodInvokerTest.java | dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/MethodInvokerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.proxy;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
class MethodInvokerTest {
@Test
void testNewInstance() throws Throwable {
String singleMethodName = "getThreadName";
String overloadMethodName = "sayHello";
MethodInvoker methodInvoker = MethodInvoker.newInstance(RemoteServiceImpl.class);
assertInstanceOf(MethodInvoker.CompositeMethodInvoker.class, methodInvoker);
MethodInvoker.CompositeMethodInvoker compositeMethodInvoker =
(MethodInvoker.CompositeMethodInvoker) methodInvoker;
Map<String, MethodInvoker> invokers = compositeMethodInvoker.getInvokers();
MethodInvoker getThreadNameMethodInvoker = invokers.get(singleMethodName);
assertInstanceOf(MethodInvoker.SingleMethodInvoker.class, getThreadNameMethodInvoker);
MethodInvoker sayHelloMethodInvoker = invokers.get(overloadMethodName);
assertInstanceOf(MethodInvoker.OverloadMethodInvoker.class, sayHelloMethodInvoker);
RemoteServiceImpl remoteService = Mockito.mock(RemoteServiceImpl.class);
// invoke success, SingleMethodInvoker does not check parameter types
methodInvoker.invoke(remoteService, singleMethodName, new Class[0], new Object[0]);
methodInvoker.invoke(
remoteService, singleMethodName, new Class[] {Object.class, Object.class, Object.class}, new Object[0]);
Mockito.verify(remoteService, Mockito.times(2)).getThreadName();
methodInvoker.invoke(
remoteService, overloadMethodName, new Class[] {String.class}, new Object[] {"Hello arg1"});
Mockito.verify(remoteService, Mockito.times(1)).sayHello("Hello arg1");
methodInvoker.invoke(remoteService, overloadMethodName, new Class[] {String.class, String.class}, new Object[] {
"Hello arg1", "Hello arg2"
});
Mockito.verify(remoteService, Mockito.times(1)).sayHello("Hello arg1", "Hello arg2");
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/RemoteServiceImpl.java | dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/RemoteServiceImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.proxy;
import org.apache.dubbo.rpc.RpcContext;
import java.rmi.RemoteException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RemoteServiceImpl implements RemoteService {
private static final Logger logger = LoggerFactory.getLogger(RemoteServiceImpl.class);
public String getThreadName() throws RemoteException {
logger.debug(
"RpcContext.getServerAttachment().getRemoteHost()={}",
RpcContext.getServiceContext().getRemoteHost());
return Thread.currentThread().getName();
}
public String sayHello(String name) throws RemoteException {
return "hello " + name + "@" + RemoteServiceImpl.class.getName();
}
public String sayHello(String name, String arg2) {
return "hello " + name + "@" + RemoteServiceImpl.class.getName() + ", arg2 " + arg2;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/jdk/JdkProxyFactoryTest.java | dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/jdk/JdkProxyFactoryTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.proxy.jdk;
import org.apache.dubbo.rpc.proxy.AbstractProxyTest;
class JdkProxyFactoryTest extends AbstractProxyTest {
static {
factory = new JdkProxyFactory();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/wrapper/StubProxyFactoryWrapperTest.java | dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/wrapper/StubProxyFactoryWrapperTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.proxy.wrapper;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Protocol;
import org.apache.dubbo.rpc.ProxyFactory;
import org.apache.dubbo.rpc.support.DemoService;
import org.apache.dubbo.rpc.support.DemoServiceStub;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.apache.dubbo.common.constants.CommonConstants.STUB_EVENT_KEY;
import static org.apache.dubbo.rpc.Constants.STUB_KEY;
/**
* {@link StubProxyFactoryWrapper }
*/
class StubProxyFactoryWrapperTest {
@Test
void test() {
ProxyFactory proxyFactory = Mockito.mock(ProxyFactory.class);
Protocol protocol = Mockito.mock(Protocol.class);
StubProxyFactoryWrapper stubProxyFactoryWrapper = new StubProxyFactoryWrapper(proxyFactory);
stubProxyFactoryWrapper.setProtocol(protocol);
URL url = URL.valueOf("test://127.0.0.1/test?stub=true");
url = url.addParameter(STUB_KEY, "true");
url = url.addParameter(STUB_EVENT_KEY, "true");
Invoker<DemoService> invoker = Mockito.mock(Invoker.class);
Mockito.when(invoker.getInterface()).thenReturn(DemoService.class);
Mockito.when(invoker.getUrl()).thenReturn(url);
DemoService proxy = stubProxyFactoryWrapper.getProxy(invoker, false);
Assertions.assertTrue(proxy instanceof DemoServiceStub);
Mockito.verify(protocol, Mockito.times(1)).export(Mockito.any());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/javassist/JavassistProxyFactoryTest.java | dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/javassist/JavassistProxyFactoryTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.proxy.javassist;
import org.apache.dubbo.rpc.proxy.AbstractProxyTest;
class JavassistProxyFactoryTest extends AbstractProxyTest {
static {
factory = new JavassistProxyFactory();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/stub/BiStreamMethodHandlerTest.java | dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/stub/BiStreamMethodHandlerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.stub;
import org.apache.dubbo.common.stream.StreamObserver;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
class BiStreamMethodHandlerTest {
@Test
void invoke() throws ExecutionException, InterruptedException, TimeoutException {
StreamObserver<String> responseObserver = Mockito.mock(StreamObserver.class);
BiStreamMethodHandler<String, String> handler = new BiStreamMethodHandler<>(o -> responseObserver);
CompletableFuture<StreamObserver<String>> future = handler.invoke(new Object[] {responseObserver});
Assertions.assertEquals(responseObserver, future.get(1, TimeUnit.SECONDS));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/stub/StubProxyFactoryTest.java | dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/stub/StubProxyFactoryTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.stub;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.ServerService;
import org.apache.dubbo.rpc.model.ServiceDescriptor;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.mockito.Mockito.when;
class StubProxyFactoryTest {
private final StubProxyFactory factory = new StubProxyFactory();
private final Invoker<MockInterface> invoker2 = Mockito.mock(Invoker.class);
@Test
void getProxy() {
Invoker<?> invoker = Mockito.mock(Invoker.class);
URL url = Mockito.mock(URL.class);
when(invoker.getUrl()).thenReturn(url);
String service = "SERV_PROX";
when(url.getServiceInterface()).thenReturn(service);
StubSuppliers.addSupplier(service, i -> invoker);
Assertions.assertEquals(invoker, factory.getProxy(invoker));
Assertions.assertEquals(invoker, factory.getProxy(invoker, false));
}
private interface MockInterface {}
private class MockStub implements ServerService<MockInterface>, MockInterface {
@Override
public Invoker<MockInterface> getInvoker(URL url) {
return invoker2;
}
@Override
public ServiceDescriptor getServiceDescriptor() {
return null;
}
}
@Test
void getInvoker() {
URL url = Mockito.mock(URL.class);
Assertions.assertEquals(invoker2, factory.getInvoker(new MockStub(), MockInterface.class, url));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/stub/ServerStreamMethodHandlerTest.java | dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/stub/ServerStreamMethodHandlerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.stub;
import org.apache.dubbo.common.stream.StreamObserver;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiConsumer;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doAnswer;
class ServerStreamMethodHandlerTest {
@Test
void invoke() {
AtomicInteger nextCounter = new AtomicInteger();
AtomicInteger completeCounter = new AtomicInteger();
AtomicInteger errorCounter = new AtomicInteger();
StreamObserver<String> responseObserver = Mockito.mock(StreamObserver.class);
doAnswer(o -> nextCounter.incrementAndGet()).when(responseObserver).onNext(anyString());
doAnswer(o -> completeCounter.incrementAndGet()).when(responseObserver).onCompleted();
doAnswer(o -> errorCounter.incrementAndGet()).when(responseObserver).onError(any(Throwable.class));
BiConsumer<String, StreamObserver<String>> consumer = (s, stringStreamObserver) -> {
for (int i = 0; i < 10; i++) {
stringStreamObserver.onNext(s + i);
}
stringStreamObserver.onCompleted();
};
ServerStreamMethodHandler<String, String> handler = new ServerStreamMethodHandler<>(consumer);
CompletableFuture<?> future = handler.invoke(new Object[] {"test", responseObserver});
Assertions.assertTrue(future.isDone());
Assertions.assertEquals(10, nextCounter.get());
Assertions.assertEquals(0, errorCounter.get());
Assertions.assertEquals(1, completeCounter.get());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/stub/FutureToObserverAdaptorTest.java | dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/stub/FutureToObserverAdaptorTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.stub;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.fail;
class FutureToObserverAdaptorTest {
@Test
void testAdapt() throws ExecutionException, InterruptedException, TimeoutException {
CompletableFuture<String> done = CompletableFuture.completedFuture("a");
FutureToObserverAdaptor<String> adaptor = new FutureToObserverAdaptor<>(done);
try {
adaptor.onNext("teet");
fail();
} catch (IllegalStateException e) {
// pass
}
CompletableFuture<String> cancel = new CompletableFuture<>();
cancel.cancel(true);
FutureToObserverAdaptor<String> adaptor1 = new FutureToObserverAdaptor<>(cancel);
try {
adaptor1.onNext("teet");
fail();
} catch (IllegalStateException e) {
// pass
}
CompletableFuture<String> exc = new CompletableFuture<>();
exc.completeExceptionally(new IllegalStateException("Test"));
FutureToObserverAdaptor<String> adaptor2 = new FutureToObserverAdaptor<>(exc);
try {
adaptor2.onNext("teet");
fail();
} catch (IllegalStateException e) {
// pass
}
CompletableFuture<String> success = new CompletableFuture<>();
FutureToObserverAdaptor<String> adaptor3 = new FutureToObserverAdaptor<>(success);
adaptor3.onNext("test");
adaptor3.onCompleted();
Assertions.assertEquals("test", success.get(1, TimeUnit.SECONDS));
CompletableFuture<String> exc2 = new CompletableFuture<>();
FutureToObserverAdaptor<String> adaptor4 = new FutureToObserverAdaptor<>(exc2);
adaptor4.onError(new IllegalStateException("test"));
try {
exc2.get();
fail();
} catch (ExecutionException e) {
Assertions.assertTrue(e.getCause() instanceof IllegalStateException);
}
CompletableFuture<String> complete = new CompletableFuture<>();
FutureToObserverAdaptor<String> adaptor5 = new FutureToObserverAdaptor<>(complete);
try {
adaptor5.onCompleted();
fail();
} catch (IllegalStateException e) {
// pass
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/stub/StubInvokerTest.java | dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/stub/StubInvokerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.stub;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.stream.StreamObserver;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.support.DemoService;
import org.apache.dubbo.rpc.support.DemoServiceImpl;
import java.util.Collections;
import java.util.Map;
import java.util.function.BiConsumer;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class StubInvokerTest {
private final URL url = URL.valueOf("tri://0.0.0.0:50051/" + DemoService.class.getName());
private final String methodName = "sayHello";
private final BiConsumer<String, StreamObserver<String>> func = (a, o) -> {
o.onNext("hello," + a);
o.onCompleted();
};
private final Map<String, StubMethodHandler<?, ?>> methodMap =
Collections.singletonMap(methodName, new UnaryStubMethodHandler<>(func));
private final StubInvoker<DemoService> invoker =
new StubInvoker<>(new DemoServiceImpl(), url, DemoService.class, methodMap);
@Test
void getUrl() {
Assertions.assertEquals(url, invoker.getUrl());
}
@Test
void isAvailable() {
Assertions.assertTrue(invoker.isAvailable());
}
@Test
void destroy() {
invoker.destroy();
}
@Test
void getInterface() {
Assertions.assertEquals(DemoService.class, invoker.getInterface());
}
@Test
void invoke() {
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName(methodName);
invocation.setArguments(new Object[] {"test"});
Result result = invoker.invoke(invocation);
Object value = result.getValue();
Assertions.assertEquals("hello,test", value);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/stub/StubSuppliersTest.java | dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/stub/StubSuppliersTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.stub;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.model.ServiceDescriptor;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.junit.jupiter.api.Assertions.fail;
class StubSuppliersTest {
private final String serviceName = "service";
@Test
void addDescriptor() {
ServiceDescriptor descriptor = Mockito.mock(ServiceDescriptor.class);
StubSuppliers.addDescriptor(serviceName, descriptor);
Assertions.assertEquals(descriptor, StubSuppliers.getServiceDescriptor(serviceName));
}
@Test
void addSupplier() {
Invoker<?> invoker = Mockito.mock(Invoker.class);
ServiceDescriptor descriptor = Mockito.mock(ServiceDescriptor.class);
StubSuppliers.addSupplier(serviceName, i -> invoker);
Assertions.assertEquals(invoker, StubSuppliers.createStub(serviceName, invoker));
}
@Test
void createStub() {
Invoker<?> invoker = Mockito.mock(Invoker.class);
try {
StubSuppliers.createStub(serviceName + 1, invoker);
fail();
} catch (IllegalStateException e) {
// pass
}
}
@Test
void getServiceDescriptor() {
try {
StubSuppliers.getServiceDescriptor(serviceName + 1);
fail();
} catch (IllegalStateException e) {
// pass
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/protocol/CountInvokerListener.java | dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/protocol/CountInvokerListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.InvokerListener;
import org.apache.dubbo.rpc.RpcException;
import java.util.concurrent.atomic.AtomicInteger;
public class CountInvokerListener implements InvokerListener {
private static final AtomicInteger counter = new AtomicInteger(0);
@Override
public void referred(Invoker<?> invoker) throws RpcException {
counter.set(0);
counter.incrementAndGet();
}
@Override
public void destroyed(Invoker<?> invoker) {}
public static int getCounter() {
return counter.get();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/protocol/ProtocolListenerWrapperTest.java | dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/protocol/ProtocolListenerWrapperTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Protocol;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.listener.ListenerInvokerWrapper;
import org.apache.dubbo.rpc.proxy.DemoService;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.INVOKER_LISTENER_KEY;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class ProtocolListenerWrapperTest {
@Test
void testLoadingListenerForLocalReference() {
// verify that no listener is loaded by default
URL urlWithoutListener =
URL.valueOf("injvm://127.0.0.1/DemoService").addParameter(INTERFACE_KEY, DemoService.class.getName());
AbstractInvoker<DemoService> invokerWithoutListener =
new AbstractInvoker<DemoService>(DemoService.class, urlWithoutListener) {
@Override
protected Result doInvoke(Invocation invocation) throws Throwable {
return null;
}
};
Protocol protocolWithoutListener = mock(Protocol.class);
when(protocolWithoutListener.refer(DemoService.class, urlWithoutListener))
.thenReturn(invokerWithoutListener);
ProtocolListenerWrapper protocolListenerWrapperWithoutListener =
new ProtocolListenerWrapper(protocolWithoutListener);
Invoker<?> invoker = protocolListenerWrapperWithoutListener.refer(DemoService.class, urlWithoutListener);
Assertions.assertTrue(invoker instanceof ListenerInvokerWrapper);
Assertions.assertEquals(
0, ((ListenerInvokerWrapper<?>) invoker).getListeners().size());
// verify that if the invoker.listener is configured, then load the specified listener
URL urlWithListener = URL.valueOf("injvm://127.0.0.1/DemoService")
.addParameter(INTERFACE_KEY, DemoService.class.getName())
.addParameter(INVOKER_LISTENER_KEY, "count");
AbstractInvoker<DemoService> invokerWithListener =
new AbstractInvoker<DemoService>(DemoService.class, urlWithListener) {
@Override
protected Result doInvoke(Invocation invocation) throws Throwable {
return null;
}
};
Protocol protocol = mock(Protocol.class);
when(protocol.refer(DemoService.class, urlWithListener)).thenReturn(invokerWithListener);
ProtocolListenerWrapper protocolListenerWrapper = new ProtocolListenerWrapper(protocol);
invoker = protocolListenerWrapper.refer(DemoService.class, urlWithListener);
Assertions.assertTrue(invoker instanceof ListenerInvokerWrapper);
Assertions.assertEquals(1, CountInvokerListener.getCounter());
}
@Test
void testLoadingListenerForRemoteReference() {
// verify that no listener is loaded by default
URL urlWithoutListener = URL.valueOf("dubbo://127.0.0.1:20880/DemoService")
.addParameter(INTERFACE_KEY, DemoService.class.getName());
AbstractInvoker<DemoService> invokerWithoutListener =
new AbstractInvoker<DemoService>(DemoService.class, urlWithoutListener) {
@Override
protected Result doInvoke(Invocation invocation) throws Throwable {
return null;
}
};
Protocol protocolWithoutListener = mock(Protocol.class);
when(protocolWithoutListener.refer(DemoService.class, urlWithoutListener))
.thenReturn(invokerWithoutListener);
ProtocolListenerWrapper protocolListenerWrapperWithoutListener =
new ProtocolListenerWrapper(protocolWithoutListener);
Invoker<?> invoker = protocolListenerWrapperWithoutListener.refer(DemoService.class, urlWithoutListener);
Assertions.assertTrue(invoker instanceof ListenerInvokerWrapper);
Assertions.assertEquals(
0, ((ListenerInvokerWrapper<?>) invoker).getListeners().size());
// verify that if the invoker.listener is configured, then load the specified listener
URL urlWithListener = URL.valueOf("dubbo://127.0.0.1:20880/DemoService")
.addParameter(INTERFACE_KEY, DemoService.class.getName())
.addParameter(INVOKER_LISTENER_KEY, "count");
AbstractInvoker<DemoService> invokerWithListener =
new AbstractInvoker<DemoService>(DemoService.class, urlWithListener) {
@Override
protected Result doInvoke(Invocation invocation) throws Throwable {
return null;
}
};
Protocol protocol = mock(Protocol.class);
when(protocol.refer(DemoService.class, urlWithListener)).thenReturn(invokerWithListener);
ProtocolListenerWrapper protocolListenerWrapper = new ProtocolListenerWrapper(protocol);
invoker = protocolListenerWrapper.refer(DemoService.class, urlWithListener);
Assertions.assertTrue(invoker instanceof ListenerInvokerWrapper);
Assertions.assertEquals(1, CountInvokerListener.getCounter());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/FutureFilterTest.java | dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/FutureFilterTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol.dubbo;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.AppResponse;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.cluster.filter.ClusterFilter;
import org.apache.dubbo.rpc.protocol.dubbo.filter.FutureFilter;
import org.apache.dubbo.rpc.support.DemoService;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
/**
* EventFilterTest.java
* TODO rely on callback integration test for now
*/
class FutureFilterTest {
private static RpcInvocation invocation;
private ClusterFilter eventFilter = new FutureFilter();
@BeforeAll
public static void setUp() {
invocation = new RpcInvocation();
invocation.setMethodName("echo");
invocation.setParameterTypes(new Class<?>[] {Enum.class});
invocation.setArguments(new Object[] {"hello"});
}
@Test
void testSyncCallback() {
@SuppressWarnings("unchecked")
Invoker<DemoService> invoker = mock(Invoker.class);
given(invoker.isAvailable()).willReturn(true);
given(invoker.getInterface()).willReturn(DemoService.class);
AppResponse result = new AppResponse();
result.setValue("High");
given(invoker.invoke(invocation)).willReturn(result);
URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1");
given(invoker.getUrl()).willReturn(url);
Result filterResult = eventFilter.invoke(invoker, invocation);
assertEquals("High", filterResult.getValue());
}
@Test
void testSyncCallbackHasException() throws RpcException, Throwable {
Assertions.assertThrows(RuntimeException.class, () -> {
@SuppressWarnings("unchecked")
Invoker<DemoService> invoker = mock(Invoker.class);
given(invoker.isAvailable()).willReturn(true);
given(invoker.getInterface()).willReturn(DemoService.class);
AppResponse result = new AppResponse();
result.setException(new RuntimeException());
given(invoker.invoke(invocation)).willReturn(result);
URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1&onthrow.method=echo");
given(invoker.getUrl()).willReturn(url);
eventFilter.invoke(invoker, invocation).recreate();
});
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/CancellationContext.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/CancellationContext.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc;
import java.io.Closeable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
public class CancellationContext implements Closeable {
private volatile ArrayList<ExecutableListener> listeners;
private Throwable cancellationCause;
private boolean cancelled;
public void addListener(final CancellationListener cancellationListener, final Executor executor) {
addListener(cancellationListener, executor, null);
}
public void addListener(final CancellationListener cancellationListener) {
addListener(cancellationListener, Runnable::run, null);
}
public void addListener(final CancellationListener cancellationListener, final RpcServiceContext context) {
addListener(cancellationListener, Runnable::run, context);
}
public void addListener(
final CancellationListener cancellationListener, final Executor executor, final RpcServiceContext context) {
addListenerInternal(new ExecutableListener(executor, cancellationListener, context));
}
public synchronized void addListenerInternal(ExecutableListener executableListener) {
if (isCancelled()) {
executableListener.deliver();
} else {
if (listeners == null) {
listeners = new ArrayList<>();
}
listeners.add(executableListener);
}
}
public boolean cancel(Throwable cause) {
boolean triggeredCancel = false;
synchronized (this) {
if (!cancelled) {
cancelled = true;
this.cancellationCause = cause;
triggeredCancel = true;
}
}
if (triggeredCancel) {
notifyAndClearListeners();
}
return triggeredCancel;
}
private void notifyAndClearListeners() {
ArrayList<ExecutableListener> tmpListeners;
synchronized (this) {
if (listeners == null) {
return;
}
tmpListeners = listeners;
listeners = null;
}
for (ExecutableListener tmpListener : tmpListeners) {
tmpListener.deliver();
}
}
public synchronized boolean isCancelled() {
return cancelled;
}
public List<ExecutableListener> getListeners() {
return listeners;
}
public Throwable getCancellationCause() {
return cancellationCause;
}
@Override
public void close() throws IOException {
cancel(null);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/BaseFilter.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/BaseFilter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc;
public interface BaseFilter {
/**
* Always call invoker.invoke() in the implementation to hand over the request to the next filter node.
*/
Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException;
/**
* This callback listener applies to both synchronous and asynchronous calls, please put logics that need to be executed
* on return of rpc result in onResponse or onError respectively based on it is normal return or exception return.
* <p>
* There's something that needs to pay attention on legacy synchronous style filer refactor, the thing is, try to move logics
* previously defined in the 'finally block' to both onResponse and onError.
*/
interface Listener {
/**
* This method will only be called on successful remote rpc execution, that means, the service in on remote received
* the request and the result (normal or exceptional) returned successfully.
*
* @param appResponse, the rpc call result, it can represent both normal result and exceptional result
* @param invoker, context
* @param invocation, context
*/
void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation);
/**
* This method will be called on detection of framework exceptions, for example, TimeoutException, NetworkException
* Exception raised in Filters, etc.
*
* @param t, framework exception
* @param invoker, context
* @param invocation, context
*/
void onError(Throwable t, Invoker<?> invoker, Invocation invocation);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/InvokeMode.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/InvokeMode.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc;
public enum InvokeMode {
SYNC,
ASYNC,
FUTURE;
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcContextAttachment.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcContextAttachment.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc;
import org.apache.dubbo.common.Experimental;
import org.apache.dubbo.common.utils.CollectionUtils;
import java.util.HashMap;
import java.util.Map;
public class RpcContextAttachment extends RpcContext {
protected volatile Map<String, Object> attachments = new HashMap<>();
// only useful on provider side.
protected AsyncContext asyncContext;
protected RpcContextAttachment() {}
/**
* @return
* @throws IllegalStateException
*/
@SuppressWarnings("unchecked")
public static AsyncContext startAsync() throws IllegalStateException {
RpcContextAttachment currentContext = getServerAttachment();
if (currentContext.asyncContext == null) {
currentContext.asyncContext = new AsyncContextImpl();
}
currentContext.asyncContext.start();
return currentContext.asyncContext;
}
@Override
protected void setAsyncContext(AsyncContext asyncContext) {
this.asyncContext = asyncContext;
}
@Override
public boolean isAsyncStarted() {
if (this.asyncContext == null) {
return false;
}
return asyncContext.isAsyncStarted();
}
@Override
public boolean stopAsync() {
return asyncContext.stop();
}
@Override
public AsyncContext getAsyncContext() {
return asyncContext;
}
/**
* also see {@link #getObjectAttachment(String)}.
*
* @param key
* @return attachment
*/
@Override
public String getAttachment(String key) {
Object value = attachments.get(key);
if (value instanceof String) {
return (String) value;
}
return null; // or JSON.toString(value);
}
/**
* get attachment.
*
* @param key
* @return attachment
*/
@Override
@Experimental("Experiment api for supporting Object transmission")
public Object getObjectAttachment(String key) {
return attachments.get(key);
}
/**
* set attachment.
*
* @param key
* @param value
* @return context
*/
@Override
public RpcContextAttachment setAttachment(String key, String value) {
return setObjectAttachment(key, (Object) value);
}
@Override
public RpcContextAttachment setAttachment(String key, Object value) {
return setObjectAttachment(key, value);
}
@Override
@Experimental("Experiment api for supporting Object transmission")
public RpcContextAttachment setObjectAttachment(String key, Object value) {
if (value == null) {
attachments.remove(key);
} else {
attachments.put(key, value);
}
return this;
}
/**
* remove attachment.
*
* @param key
* @return context
*/
@Override
public RpcContextAttachment removeAttachment(String key) {
attachments.remove(key);
return this;
}
/**
* get attachments.
*
* @return attachments
*/
@Override
@Deprecated
public Map<String, String> getAttachments() {
return new AttachmentsAdapter.ObjectToStringMap(this.getObjectAttachments());
}
/**
* get attachments.
*
* @return attachments
*/
@Override
@Experimental("Experiment api for supporting Object transmission")
public Map<String, Object> getObjectAttachments() {
return attachments;
}
/**
* set attachments
*
* @param attachment
* @return context
*/
@Override
public RpcContextAttachment setAttachments(Map<String, String> attachment) {
this.attachments.clear();
if (attachment != null && attachment.size() > 0) {
this.attachments.putAll(attachment);
}
return this;
}
/**
* set attachments
*
* @param attachment
* @return context
*/
@Override
@Experimental("Experiment api for supporting Object transmission")
public RpcContextAttachment setObjectAttachments(Map<String, Object> attachment) {
this.attachments.clear();
if (CollectionUtils.isNotEmptyMap(attachment)) {
this.attachments = attachment;
}
return this;
}
@Override
public void clearAttachments() {
this.attachments.clear();
}
/**
* get values.
*
* @return values
*/
@Override
@Deprecated
public Map<String, Object> get() {
return getObjectAttachments();
}
/**
* set value.
*
* @param key
* @param value
* @return context
*/
@Override
@Deprecated
public RpcContextAttachment set(String key, Object value) {
return setAttachment(key, value);
}
/**
* remove value.
*
* @param key
* @return value
*/
@Override
@Deprecated
public RpcContextAttachment remove(String key) {
return removeAttachment(key);
}
/**
* get value.
*
* @param key
* @return value
*/
@Override
@Deprecated
public Object get(String key) {
return getAttachment(key);
}
/**
* Also see {@link RpcServiceContext#copyOf(boolean)}
*
* @return a copy of RpcContextAttachment with deep copied attachments
*/
public RpcContextAttachment copyOf(boolean needCopy) {
if (!isValid()) {
return null;
}
if (needCopy) {
RpcContextAttachment copy = new RpcContextAttachment();
if (CollectionUtils.isNotEmptyMap(attachments)) {
copy.attachments.putAll(this.attachments);
}
if (asyncContext != null) {
copy.asyncContext = this.asyncContext;
}
return copy;
} else {
return this;
}
}
protected boolean isValid() {
return CollectionUtils.isNotEmptyMap(attachments);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/PenetrateAttachmentSelector.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/PenetrateAttachmentSelector.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc;
import org.apache.dubbo.common.extension.SPI;
import java.util.Map;
@SPI
public interface PenetrateAttachmentSelector {
/**
* Select some attachments to pass to next hop.
* These attachments can fetch from {@link RpcContext#getServerAttachment()} or user defined.
*
* @return attachment pass to next hop
*/
Map<String, Object> select(
Invocation invocation, RpcContextAttachment clientAttachment, RpcContextAttachment serverAttachment);
Map<String, Object> selectReverse(
Invocation invocation,
RpcContextAttachment clientResponseContext,
RpcContextAttachment serverResponseContext);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ProtocolServer.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ProtocolServer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.remoting.RemotingServer;
import java.util.Map;
/**
* Distinct from {@link RemotingServer}, each protocol holds one or more ProtocolServers(the number usually decides by port numbers),
* while each ProtocolServer holds zero or one RemotingServer.
*/
public interface ProtocolServer {
default RemotingServer getRemotingServer() {
return null;
}
default void setRemotingServers(RemotingServer server) {}
String getAddress();
void setAddress(String address);
default URL getUrl() {
return null;
}
default void reset(URL url) {}
void close();
Map<String, Object> getAttributes();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Invocation.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Invocation.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc;
import org.apache.dubbo.common.Experimental;
import org.apache.dubbo.rpc.model.ModuleModel;
import org.apache.dubbo.rpc.model.ScopeModelUtil;
import org.apache.dubbo.rpc.model.ServiceModel;
import java.beans.Transient;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.stream.Stream;
/**
* Invocation. (API, Prototype, NonThreadSafe)
*
* @serial Don't change the class name and package name.
* @see org.apache.dubbo.rpc.Invoker#invoke(Invocation)
* @see org.apache.dubbo.rpc.RpcInvocation
*/
public interface Invocation {
String getTargetServiceUniqueName();
String getProtocolServiceKey();
/**
* get method name.
*
* @return method name.
* @serial
*/
String getMethodName();
/**
* get the interface name
*
* @return
*/
String getServiceName();
/**
* get parameter types.
*
* @return parameter types.
* @serial
*/
Class<?>[] getParameterTypes();
/**
* get parameter's signature, string representation of parameter types.
*
* @return parameter's signature
*/
default String[] getCompatibleParamSignatures() {
return Stream.of(getParameterTypes()).map(Class::getName).toArray(String[]::new);
}
/**
* get arguments.
*
* @return arguments.
* @serial
*/
Object[] getArguments();
/**
* get attachments.
*
* @return attachments.
* @serial
*/
Map<String, String> getAttachments();
@Experimental("Experiment api for supporting Object transmission")
Map<String, Object> getObjectAttachments();
@Experimental("Experiment api for supporting Object transmission")
Map<String, Object> copyObjectAttachments();
@Experimental("Experiment api for supporting Object transmission")
void foreachAttachment(Consumer<Map.Entry<String, Object>> consumer);
void setAttachment(String key, String value);
@Experimental("Experiment api for supporting Object transmission")
void setAttachment(String key, Object value);
@Experimental("Experiment api for supporting Object transmission")
void setObjectAttachment(String key, Object value);
void setAttachmentIfAbsent(String key, String value);
@Experimental("Experiment api for supporting Object transmission")
void setAttachmentIfAbsent(String key, Object value);
@Experimental("Experiment api for supporting Object transmission")
void setObjectAttachmentIfAbsent(String key, Object value);
/**
* get attachment by key.
*
* @return attachment value.
* @serial
*/
String getAttachment(String key);
@Experimental("Experiment api for supporting Object transmission")
Object getObjectAttachment(String key);
@Experimental("Experiment api for supporting Object transmission")
default Object getObjectAttachmentWithoutConvert(String key) {
return getObjectAttachment(key);
}
/**
* get attachment by key with default value.
*
* @return attachment value.
* @serial
*/
String getAttachment(String key, String defaultValue);
@Experimental("Experiment api for supporting Object transmission")
Object getObjectAttachment(String key, Object defaultValue);
/**
* get the invoker in current context.
*
* @return invoker.
* @transient
*/
@Transient
Invoker<?> getInvoker();
void setServiceModel(ServiceModel serviceModel);
ServiceModel getServiceModel();
default ModuleModel getModuleModel() {
return ScopeModelUtil.getModuleModel(
getServiceModel() == null ? null : getServiceModel().getModuleModel());
}
Object put(Object key, Object value);
Object get(Object key);
Map<Object, Object> getAttributes();
/**
* To add invoked invokers into invocation. Can be used in ClusterFilter or Filter for tracing or debugging purpose.
* Currently, only support in consumer side.
*
* @param invoker invoked invokers
*/
void addInvokedInvoker(Invoker<?> invoker);
/**
* Get all invoked invokers in current invocation.
* NOTICE: A curtain invoker could be invoked for twice or more if retries.
*
* @return invokers
*/
List<Invoker<?>> getInvokedInvokers();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Exporter.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Exporter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc;
/**
* Exporter. (API/SPI, Prototype, ThreadSafe)
*
* @see org.apache.dubbo.rpc.Protocol#export(Invoker)
* @see org.apache.dubbo.rpc.ExporterListener
* @see org.apache.dubbo.rpc.protocol.AbstractExporter
*/
public interface Exporter<T> {
/**
* get invoker.
*
* @return invoker
*/
Invoker<T> getInvoker();
/**
* unexport.
* <p>
* <code>
* getInvoker().destroy();
* </code>
*/
void unexport();
/**
* register to registry
*/
void register();
/**
* unregister from registry
*/
void unregister();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AdaptiveMetrics.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AdaptiveMetrics.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc;
import org.apache.dubbo.common.utils.ConcurrentHashMapUtils;
import org.apache.dubbo.common.utils.StringUtils;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicLong;
/**
* adaptive Metrics statistics.
*/
public class AdaptiveMetrics {
private final ConcurrentMap<String, AdaptiveMetrics> metricsStatistics = new ConcurrentHashMap<>();
private long currentProviderTime = 0;
private double providerCPULoad = 0;
private long lastLatency = 0;
private long currentTime = 0;
// Allow some time disorder
private long pickTime = System.currentTimeMillis();
private double beta = 0.5;
private final AtomicLong consumerReq = new AtomicLong();
private final AtomicLong consumerSuccess = new AtomicLong();
private final AtomicLong errorReq = new AtomicLong();
private double ewma = 0;
public double getLoad(String idKey, int weight, int timeout) {
AdaptiveMetrics metrics = getStatus(idKey);
// If the time more than 2 times, mandatory selected
if (System.currentTimeMillis() - metrics.pickTime > timeout * 2) {
return 0;
}
if (metrics.currentTime > 0) {
long multiple = (System.currentTimeMillis() - metrics.currentTime) / timeout + 1;
if (multiple > 0) {
if (metrics.currentProviderTime == metrics.currentTime) {
// penalty value
metrics.lastLatency = timeout * 2L;
} else {
metrics.lastLatency = metrics.lastLatency >> multiple;
}
metrics.ewma = metrics.beta * metrics.ewma + (1 - metrics.beta) * metrics.lastLatency;
metrics.currentTime = System.currentTimeMillis();
}
}
long inflight = metrics.consumerReq.get() - metrics.consumerSuccess.get() - metrics.errorReq.get();
return metrics.providerCPULoad
* (Math.sqrt(metrics.ewma) + 1)
* (inflight + 1)
/ ((((double) metrics.consumerSuccess.get() / (double) (metrics.consumerReq.get() + 1)) * weight) + 1);
}
public AdaptiveMetrics getStatus(String idKey) {
return ConcurrentHashMapUtils.computeIfAbsent(metricsStatistics, idKey, k -> new AdaptiveMetrics());
}
public void addConsumerReq(String idKey) {
AdaptiveMetrics metrics = getStatus(idKey);
metrics.consumerReq.incrementAndGet();
}
public void addConsumerSuccess(String idKey) {
AdaptiveMetrics metrics = getStatus(idKey);
metrics.consumerSuccess.incrementAndGet();
}
public void addErrorReq(String idKey) {
AdaptiveMetrics metrics = getStatus(idKey);
metrics.errorReq.incrementAndGet();
}
public void setPickTime(String idKey, long time) {
AdaptiveMetrics metrics = getStatus(idKey);
metrics.pickTime = time;
}
public void setProviderMetrics(String idKey, Map<String, String> metricsMap) {
AdaptiveMetrics metrics = getStatus(idKey);
long serviceTime = Long.parseLong(Optional.ofNullable(metricsMap.get("curTime"))
.filter(v -> StringUtils.isNumeric(v, false))
.orElse("0"));
// If server time is less than the current time, discard
if (metrics.currentProviderTime > serviceTime) {
return;
}
metrics.currentProviderTime = serviceTime;
metrics.currentTime = serviceTime;
metrics.providerCPULoad = Double.parseDouble(Optional.ofNullable(metricsMap.get("load"))
.filter(v -> StringUtils.isNumeric(v, true))
.orElse("0"));
metrics.lastLatency = Long.parseLong((Optional.ofNullable(metricsMap.get("rt"))
.filter(v -> StringUtils.isNumeric(v, false))
.orElse("0")));
metrics.beta = 0.5;
// Vt = β * Vt-1 + (1 - β ) * θt
metrics.ewma = metrics.beta * metrics.ewma + (1 - metrics.beta) * metrics.lastLatency;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ListenableFilter.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ListenableFilter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* It's recommended to implement Filter.Listener directly for callback registration, check the default implementation,
* see {@link org.apache.dubbo.rpc.filter.ExceptionFilter}, for example.
* <p>
* If you do not want to share Listener instance between RPC calls. ListenableFilter can be used
* to keep a 'one Listener each RPC call' model.
*/
@Deprecated
public abstract class ListenableFilter implements Filter {
protected Listener listener = null;
protected final ConcurrentMap<Invocation, Listener> listeners = new ConcurrentHashMap<>();
public Listener listener() {
return listener;
}
public Listener listener(Invocation invocation) {
Listener invListener = listeners.get(invocation);
if (invListener == null) {
invListener = listener;
}
return invListener;
}
public void addListener(Invocation invocation, Listener listener) {
listeners.putIfAbsent(invocation, listener);
}
public void removeListener(Invocation invocation) {
listeners.remove(invocation);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Protocol.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Protocol.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Adaptive;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
import java.util.Collections;
import java.util.List;
/**
* RPC Protocol extension interface, which encapsulates the details of remote invocation. <br /><br />
*
* <p>Conventions:
*
* <li>
* When user invokes the 'invoke()' method in object that the method 'refer()' returns,
* the protocol needs to execute the 'invoke()' method of Invoker object that received by 'export()' method,
* which should have the same URL.
* </li>
*
* <li>
* Invoker that returned by 'refer()' is implemented by the protocol. The remote invocation request should be sent by that Invoker.
* </li>
*
* <li>
* The invoker that 'export()' receives will be implemented by framework. Protocol implementation should not care with that.
* </li>
*
* <p>Attentions:
*
* <li>
* The Protocol implementation does not care the transparent proxy. The invoker will be converted to business interface by other layer.
* </li>
*
* <li>
* The protocol doesn't need to be backed by TCP connection. It can also be backed by file sharing or inter-process communication.
* </li>
*
* (API/SPI, Singleton, ThreadSafe)
*/
@SPI(value = "dubbo", scope = ExtensionScope.FRAMEWORK)
public interface Protocol {
/**
* Get default port when user doesn't config the port.
*
* @return default port
*/
int getDefaultPort();
/**
* Export service for remote invocation: <br>
* 1. Protocol should record request source address after receive a request:
* RpcContext.getServerAttachment().setRemoteAddress();<br>
* 2. export() must be idempotent, that is, there's no difference between invoking once and invoking twice when
* export the same URL<br>
* 3. Invoker instance is passed in by the framework, protocol needs not to care <br>
*
* @param <T> Service type
* @param invoker Service invoker
* @return exporter reference for exported service, useful for unexport the service later
* @throws RpcException thrown when error occurs during export the service, for example: port is occupied
*/
@Adaptive
<T> Exporter<T> export(Invoker<T> invoker) throws RpcException;
/**
* Refer a remote service: <br>
* 1. When user calls `invoke()` method of `Invoker` object which's returned from `refer()` call, the protocol
* needs to correspondingly execute `invoke()` method of `Invoker` object <br>
* 2. It's protocol's responsibility to implement `Invoker` which's returned from `refer()`. Generally speaking,
* protocol sends remote request in the `Invoker` implementation. <br>
* 3. When there's check=false set in URL, the implementation must not throw exception but try to recover when
* connection fails.
*
* @param <T> Service type
* @param type Service class
* @param url URL address for the remote service
* @return invoker service's local proxy
* @throws RpcException when there's any error while connecting to the service provider
*/
@Adaptive
<T> Invoker<T> refer(Class<T> type, URL url) throws RpcException;
/**
* Destroy protocol: <br>
* 1. Cancel all services this protocol exports and refers <br>
* 2. Release all occupied resources, for example: connection, port, etc. <br>
* 3. Protocol can continue to export and refer new service even after it's destroyed.
*/
void destroy();
/**
* Get all servers serving this protocol
*
* @return
*/
default List<ProtocolServer> getServers() {
return Collections.emptyList();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/FutureContext.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/FutureContext.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.threadlocal.InternalThreadLocal;
import org.apache.dubbo.common.utils.SystemPropertyConfigUtils;
import org.apache.dubbo.rpc.protocol.dubbo.FutureAdapter;
import java.util.concurrent.CompletableFuture;
/**
* Used for async call scenario. But if the method you are calling has a {@link CompletableFuture<?>} signature
* you do not need to use this class since you will get a Future response directly.
* <p>
* Remember to save the Future reference before making another call using the same thread, otherwise,
* the current Future will be override by the new one, which means you will lose the chance get the return value.
*/
public class FutureContext {
private static final InternalThreadLocal<FutureContext> futureTL = new InternalThreadLocal<FutureContext>() {
@Override
protected FutureContext initialValue() {
return new FutureContext();
}
};
public static FutureContext getContext() {
return futureTL.get();
}
private CompletableFuture<?> future;
private CompletableFuture<?> compatibleFuture;
/**
* Whether clear future once get
*/
private static final boolean clearFutureAfterGet = Boolean.parseBoolean(SystemPropertyConfigUtils.getSystemProperty(
CommonConstants.ThirdPartyProperty.CLEAR_FUTURE_AFTER_GET, "false"));
/**
* get future.
*
* @param <T>
* @return future
*/
@SuppressWarnings("unchecked")
public <T> CompletableFuture<T> getCompletableFuture() {
try {
return (CompletableFuture<T>) future;
} finally {
if (clearFutureAfterGet) {
this.future = null;
}
}
}
/**
* set future.
*
* @param future
*/
public void setFuture(CompletableFuture<?> future) {
this.future = future;
}
@Deprecated
@SuppressWarnings("unchecked")
public <T> CompletableFuture<T> getCompatibleCompletableFuture() {
try {
return (CompletableFuture<T>) compatibleFuture;
} finally {
if (clearFutureAfterGet) {
this.compatibleFuture = null;
}
}
}
/**
* Guarantee 'using org.apache.dubbo.rpc.RpcContext.getFuture() before proxy returns' can work, a typical scenario is:
* <pre>{@code
* public final class TracingFilter implements Filter {
* public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
* Result result = invoker.invoke(invocation);
* Future<Object> future = rpcContext.getFuture();
* if (future instanceof FutureAdapter) {
* ((FutureAdapter) future).getFuture().setCallback(new FinishSpanCallback(span));
* }
* ......
* }
* }
* }</pre>
* <p>
* Start from 2.7.3, you don't have to get Future from RpcContext, we recommend using Result directly:
* <pre>{@code
* public final class TracingFilter implements Filter {
* public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
* Result result = invoker.invoke(invocation);
* result.getResponseFuture().whenComplete(new FinishSpanCallback(span));
* ......
* }
* }
* }</pre>
*/
@Deprecated
public void setCompatibleFuture(CompletableFuture<?> compatibleFuture) {
this.compatibleFuture = compatibleFuture;
if (compatibleFuture != null) {
this.setFuture(new FutureAdapter(compatibleFuture));
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AttachmentsAdapter.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AttachmentsAdapter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc;
import java.util.HashMap;
import java.util.Map;
/**
* This class provides map adapters to support attachments in RpcContext, Invocation and Result switch from
* <String, String> to <String, Object>
*/
public class AttachmentsAdapter {
public static class ObjectToStringMap extends HashMap<String, String> {
private final Map<String, Object> attachments;
public ObjectToStringMap(Map<String, Object> attachments) {
for (Entry<String, Object> entry : attachments.entrySet()) {
String convertResult = convert(entry.getValue());
if (convertResult != null) {
super.put(entry.getKey(), convertResult);
}
}
this.attachments = attachments;
}
@Override
public String put(String key, String value) {
attachments.put(key, value);
return super.put(key, value);
}
@Override
public String remove(Object key) {
attachments.remove(key);
return super.remove(key);
}
private String convert(Object obj) {
if (obj instanceof String) {
return (String) obj;
}
return null; // or JSON.toString(obj);
}
@Override
public void clear() {
attachments.clear();
super.clear();
}
@Override
public void putAll(Map<? extends String, ? extends String> map) {
attachments.putAll(map);
super.putAll(map);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AppResponse.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AppResponse.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc;
import org.apache.dubbo.common.compact.Dubbo2CompactUtils;
import org.apache.dubbo.rpc.support.Dubbo2RpcExceptionUtils;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.BiConsumer;
import java.util.function.Function;
import static org.apache.dubbo.rpc.Constants.INVOCATION_KEY;
/**
* {@link AsyncRpcResult} is introduced in 3.0.0 to replace RpcResult, and RpcResult is replaced with {@link AppResponse}:
* <ul>
* <li>AsyncRpcResult is the object that is actually passed in the call chain</li>
* <li>AppResponse only simply represents the business result</li>
* </ul>
* <p>
* The relationship between them can be described as follow, an abstraction of the definition of AsyncRpcResult:
* <pre>
* {@code
* Public class AsyncRpcResult implements CompletionStage<AppResponse> {
* ......
* }
* }
* </pre>
* </p>
* AsyncRpcResult is a future representing an unfinished RPC call, while AppResponse is the actual return type of this call.
* In theory, AppResponse doesn't have to implement the {@link Result} interface, this is done mainly for compatibility purpose.
*
* @serial Do not change the class name and properties.
*/
public class AppResponse implements Result {
private static final long serialVersionUID = -6925924956850004727L;
private Object result;
private Throwable exception;
private Map<String, Object> attachments = new HashMap<>();
private final Map<String, Object> attributes = new HashMap<>();
public AppResponse() {}
public AppResponse(Invocation invocation) {
this.setAttribute(INVOCATION_KEY, invocation);
}
public AppResponse(Object result) {
this.result = result;
}
public AppResponse(Throwable exception) {
this.exception = exception;
}
@Override
public Object recreate() throws Throwable {
if (exception != null) {
// fix issue#619
try {
Object stackTrace = exception.getStackTrace();
if (stackTrace == null) {
exception.setStackTrace(new StackTraceElement[0]);
}
} catch (Exception e) {
// ignore
}
if (Dubbo2CompactUtils.isEnabled()
&& Dubbo2RpcExceptionUtils.isRpcExceptionClassLoaded()
&& (exception instanceof RpcException)
&& !Dubbo2RpcExceptionUtils.getRpcExceptionClass().isAssignableFrom(exception.getClass())) {
RpcException recreated = Dubbo2RpcExceptionUtils.newRpcException(
((RpcException) exception).getCode(), exception.getMessage(), exception.getCause());
if (recreated != null) {
recreated.setStackTrace(exception.getStackTrace());
throw recreated;
}
}
throw exception;
}
return result;
}
@Override
public Object getValue() {
return result;
}
@Override
public void setValue(Object value) {
this.result = value;
}
@Override
public Throwable getException() {
return exception;
}
@Override
public void setException(Throwable e) {
this.exception = e;
}
@Override
public boolean hasException() {
return exception != null;
}
@Override
@Deprecated
public Map<String, String> getAttachments() {
return new AttachmentsAdapter.ObjectToStringMap(attachments);
}
@Override
public Map<String, Object> getObjectAttachments() {
return attachments;
}
/**
* Append all items from the map into the attachment, if map is empty then nothing happens
*
* @param map contains all key-value pairs to append
*/
public void setAttachments(Map<String, String> map) {
this.attachments = map == null ? new HashMap<>() : new HashMap<>(map);
}
@Override
public void setObjectAttachments(Map<String, Object> map) {
this.attachments = map == null ? new HashMap<>() : map;
}
public void addAttachments(Map<String, String> map) {
if (map == null) {
return;
}
if (this.attachments == null) {
this.attachments = new HashMap<>(map.size());
}
this.attachments.putAll(map);
}
@Override
public void addObjectAttachments(Map<String, Object> map) {
if (map == null) {
return;
}
if (this.attachments == null) {
this.attachments = new HashMap<>(map.size());
}
this.attachments.putAll(map);
}
@Override
public String getAttachment(String key) {
Object value = attachments.get(key);
if (value instanceof String) {
return (String) value;
}
return null;
}
@Override
public Object getObjectAttachment(String key) {
return attachments.get(key);
}
@Override
public String getAttachment(String key, String defaultValue) {
Object result = attachments.get(key);
if (result == null) {
return defaultValue;
}
if (result instanceof String) {
return (String) result;
}
return defaultValue;
}
@Override
public Object getObjectAttachment(String key, Object defaultValue) {
Object result = attachments.get(key);
if (result == null) {
result = defaultValue;
}
return result;
}
@Override
public void setAttachment(String key, String value) {
setObjectAttachment(key, value);
}
@Override
public void setAttachment(String key, Object value) {
setObjectAttachment(key, value);
}
@Override
public void setObjectAttachment(String key, Object value) {
attachments.put(key, value);
}
public Object getAttribute(String key) {
return attributes.get(key);
}
public void setAttribute(String key, Object value) {
attributes.put(key, value);
}
@Override
public Result whenCompleteWithContext(BiConsumer<Result, Throwable> fn) {
throw new UnsupportedOperationException(
"AppResponse represents an concrete business response, there will be no status changes, you should get internal values directly.");
}
@Override
public <U> CompletableFuture<U> thenApply(Function<Result, ? extends U> fn) {
throw new UnsupportedOperationException(
"AppResponse represents an concrete business response, there will be no status changes, you should get internal values directly.");
}
@Override
public Result get() throws InterruptedException, ExecutionException {
throw new UnsupportedOperationException(
"AppResponse represents an concrete business response, there will be no status changes, you should get internal values directly.");
}
@Override
public Result get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
throw new UnsupportedOperationException(
"AppResponse represents an concrete business response, there will be no status changes, you should get internal values directly.");
}
public void clear() {
this.result = null;
this.exception = null;
this.attachments.clear();
}
@Override
public String toString() {
return "AppResponse [value=" + result + ", exception=" + exception + "]";
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/TimeoutCountDown.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/TimeoutCountDown.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc;
import java.util.concurrent.TimeUnit;
public final class TimeoutCountDown implements Comparable<TimeoutCountDown> {
public static TimeoutCountDown newCountDown(long timeout, TimeUnit unit) {
return new TimeoutCountDown(timeout, unit);
}
private final long timeoutInMillis;
private final long deadlineInNanos;
private volatile boolean expired;
private TimeoutCountDown(long timeout, TimeUnit unit) {
timeoutInMillis = TimeUnit.MILLISECONDS.convert(timeout, unit);
deadlineInNanos = System.nanoTime() + TimeUnit.NANOSECONDS.convert(timeout, unit);
}
public long getTimeoutInMilli() {
return timeoutInMillis;
}
public boolean isExpired() {
if (!expired) {
if (deadlineInNanos - System.nanoTime() <= 0) {
expired = true;
} else {
return false;
}
}
return true;
}
public long timeRemaining(TimeUnit unit) {
final long currentNanos = System.nanoTime();
if (!expired && deadlineInNanos - currentNanos <= 0) {
expired = true;
}
return unit.convert(deadlineInNanos - currentNanos, TimeUnit.NANOSECONDS);
}
public long elapsedMillis() {
if (isExpired()) {
return timeoutInMillis
+ TimeUnit.MILLISECONDS.convert(System.nanoTime() - deadlineInNanos, TimeUnit.NANOSECONDS);
} else {
return timeoutInMillis
- TimeUnit.MILLISECONDS.convert(deadlineInNanos - System.nanoTime(), TimeUnit.NANOSECONDS);
}
}
@Override
public String toString() {
long timeoutMillis = TimeUnit.MILLISECONDS.convert(deadlineInNanos, TimeUnit.NANOSECONDS);
long remainingMillis = timeRemaining(TimeUnit.MILLISECONDS);
StringBuilder buf = new StringBuilder();
buf.append("Total timeout value - ");
buf.append(timeoutMillis);
buf.append(", times remaining - ");
buf.append(remainingMillis);
return buf.toString();
}
@Override
public int compareTo(TimeoutCountDown another) {
long delta = this.deadlineInNanos - another.deadlineInNanos;
if (delta < 0) {
return -1;
} else if (delta > 0) {
return 1;
}
return 0;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcConstants.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcConstants.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.constants.FilterConstants;
import org.apache.dubbo.common.constants.QosConstants;
import org.apache.dubbo.common.constants.RegistryConstants;
import org.apache.dubbo.common.constants.RemotingConstants;
/**
* RpcConstants
*
* @deprecated Replace to org.apache.dubbo.common.Constants
*/
@Deprecated
public final class RpcConstants
implements CommonConstants, QosConstants, FilterConstants, RegistryConstants, RemotingConstants {
private RpcConstants() {}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcScopeModelInitializer.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcScopeModelInitializer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc;
import org.apache.dubbo.common.beans.factory.ScopeBeanFactory;
import org.apache.dubbo.rpc.listener.InjvmExporterListener;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ScopeModelInitializer;
import org.apache.dubbo.rpc.protocol.PermittedSerializationKeeper;
public class RpcScopeModelInitializer implements ScopeModelInitializer {
@Override
public void initializeFrameworkModel(FrameworkModel frameworkModel) {
ScopeBeanFactory beanFactory = frameworkModel.getBeanFactory();
beanFactory.registerBean(InjvmExporterListener.class);
beanFactory.registerBean(PermittedSerializationKeeper.class);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Filter.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Filter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
/**
* Extension for intercepting the invocation for both service provider and consumer, furthermore, most of
* functions in dubbo are implemented base on the same mechanism. Since every time when remote method is
* invoked, the filter extensions will be executed too, the corresponding penalty should be considered before
* more filters are added.
* <pre>
* They way filter work from sequence point of view is
* <b>
* ...code before filter ...
* invoker.invoke(invocation) //filter work in a filter implementation class
* ...code after filter ...
* </b>
* Caching is implemented in dubbo using filter approach. If cache is configured for invocation then before
* remote call configured caching type's (e.g. Thread Local, JCache etc) implementation invoke method gets called.
* </pre>
*
* Starting from 3.0, Filter on consumer side has been refactored. There are two different kinds of Filters working at different stages
* of an RPC request.
* 1. Filter. Works at the instance level, each Filter is bond to one specific Provider instance(invoker).
* 2. ClusterFilter. Newly introduced in 3.0, intercepts request before Loadbalancer picks one specific Filter(Invoker).
*
* Filter Chain in 3.x
*
* -> Filter -> Invoker
*
* Proxy -> ClusterFilter -> ClusterInvoker -> Filter -> Invoker
*
* -> Filter -> Invoker
*
*
* Filter Chain in 2.x
*
* Filter -> Invoker
*
* Proxy -> ClusterInvoker -> Filter -> Invoker
*
* Filter -> Invoker
*
*
* Filter. (SPI, Singleton, ThreadSafe)
*
* @see org.apache.dubbo.rpc.filter.GenericFilter
* @see org.apache.dubbo.rpc.filter.EchoFilter
* @see org.apache.dubbo.rpc.filter.TokenFilter
* @see org.apache.dubbo.rpc.filter.TpsLimitFilter
*/
@SPI(scope = ExtensionScope.MODULE)
public interface Filter extends BaseFilter {}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AsyncContext.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AsyncContext.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc;
/**
* AsyncContext works like {@see javax.servlet.AsyncContext} in the Servlet 3.0.
* An AsyncContext is stated by a call to {@link RpcContext#startAsync()}.
* <p>
* The demo is {@see com.alibaba.dubbo.examples.async.AsyncConsumer}
* and {@see com.alibaba.dubbo.examples.async.AsyncProvider}
*/
public interface AsyncContext {
/**
* write value and complete the async context.
*
* @param value invoke result
*/
void write(Object value);
/**
* @return true if the async context is started
*/
boolean isAsyncStarted();
/**
* change the context state to stop
*/
boolean stop();
/**
* change the context state to start
*/
void start();
/**
* Signal RpcContext switch.
* Use this method to switch RpcContext from a Dubbo thread to a new thread created by the user.
*
* Note that you should use it in a new thread like this:
* <code>
* public class AsyncServiceImpl implements AsyncService {
* public String sayHello(String name) {
* final AsyncContext asyncContext = RpcContext.startAsync();
* new Thread(() -> {
*
* // right place to use this method
* asyncContext.signalContextSwitch();
*
* try {
* Thread.sleep(500);
* } catch (InterruptedException e) {
* e.printStackTrace();
* }
* asyncContext.write("Hello " + name + ", response from provider.");
* }).start();
* return null;
* }
* }
* </code>
*/
void signalContextSwitch();
/**
* Reset Context is not necessary. Only reset context after result was write back if it is necessary.
*
* <code>
* public class AsyncServiceImpl implements AsyncService {
* public String sayHello(String name) {
* final AsyncContext asyncContext = RpcContext.startAsync();
* new Thread(() -> {
* <p>
* // the right place to use this method
* asyncContext.signalContextSwitch();
* <p>
* try {
* Thread.sleep(500);
* } catch (InterruptedException e) {
* e.printStackTrace();
* }
* asyncContext.write("Hello " + name + ", response from provider.");
* // only reset after asyncContext.write()
* asyncContext.resetContext();
* }).start();
* return null;
* }
* }
* </code>
*
* <code>
* public class AsyncServiceImpl implements AsyncService {
* public CompletableFuture sayHello(String name) {
* CompletableFuture future = new CompletableFuture();
* final AsyncContext asyncContext = RpcContext.startAsync();
* new Thread(() -> {
* // the right place to use this method
* asyncContext.signalContextSwitch();
* // some operations...
* future.complete();
* // only reset after future.complete()
* asyncContext.resetContext();
* }).start();
* return future;
* }
* }
* </code>
*/
void resetContext();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcContext.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcContext.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc;
import org.apache.dubbo.common.Experimental;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.threadlocal.InternalThreadLocal;
import org.apache.dubbo.common.utils.StringUtils;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
/**
* Thread local context. (API, ThreadLocal, ThreadSafe)
* <p>
* Note: RpcContext is a temporary state holder. States in RpcContext changes every time when request is sent or received.
* <p/>
* There are four kinds of RpcContext, which are ServerContext, ClientAttachment, ServerAttachment and ServiceContext.
* <p/>
* ServiceContext: Using to pass environment parameters in the whole invocation. For example, `remotingApplicationName`,
* `remoteAddress`, etc. {@link RpcServiceContext}
* ClientAttachment, ServerAttachment and ServiceContext are using to transfer attachments.
* Imaging a situation like this, A is calling B, and B will call C, after that, B wants to return some attachments back to A.
* ClientAttachment is using to pass attachments to next hop as a consumer. ( A --> B , in A side)
* ServerAttachment is using to fetch attachments from previous hop as a provider. ( A --> B , in B side)
* ServerContext is using to return some attachments back to client as a provider. ( A <-- B , in B side)
* The reason why using `ServiceContext` is to make API compatible with previous.
*
* @export
* @see org.apache.dubbo.rpc.filter.ContextFilter
*/
public class RpcContext {
private static final RpcContext AGENT = new RpcContext();
/**
* use internal thread local to improve performance
*/
private static final InternalThreadLocal<RpcContextAttachment> CLIENT_RESPONSE_LOCAL =
new InternalThreadLocal<RpcContextAttachment>() {
@Override
protected RpcContextAttachment initialValue() {
return new RpcContextAttachment();
}
};
private static final InternalThreadLocal<RpcContextAttachment> SERVER_RESPONSE_LOCAL =
new InternalThreadLocal<RpcContextAttachment>() {
@Override
protected RpcContextAttachment initialValue() {
return new RpcContextAttachment();
}
};
private static final InternalThreadLocal<RpcContextAttachment> CLIENT_ATTACHMENT =
new InternalThreadLocal<RpcContextAttachment>() {
@Override
protected RpcContextAttachment initialValue() {
return new RpcContextAttachment();
}
};
private static final InternalThreadLocal<RpcContextAttachment> SERVER_ATTACHMENT =
new InternalThreadLocal<RpcContextAttachment>() {
@Override
protected RpcContextAttachment initialValue() {
return new RpcContextAttachment();
}
};
private static final InternalThreadLocal<RpcServiceContext> SERVICE_CONTEXT =
new InternalThreadLocal<RpcServiceContext>() {
@Override
protected RpcServiceContext initialValue() {
return new RpcServiceContext();
}
};
/**
* use by cancel call
*/
private static final InternalThreadLocal<CancellationContext> CANCELLATION_CONTEXT =
new InternalThreadLocal<CancellationContext>() {
@Override
protected CancellationContext initialValue() {
return new CancellationContext();
}
};
public static CancellationContext getCancellationContext() {
return CANCELLATION_CONTEXT.get();
}
public static void removeCancellationContext() {
CANCELLATION_CONTEXT.remove();
}
public static void restoreCancellationContext(CancellationContext oldContext) {
CANCELLATION_CONTEXT.set(oldContext);
}
private boolean remove = true;
protected RpcContext() {}
/**
* get server side context. ( A <-- B , in B side)
*
* @return server context
*/
public static RpcContextAttachment getServerContext() {
return new RpcServerContextAttachment();
}
/**
* remove server side context.
*
* @see org.apache.dubbo.rpc.filter.ContextFilter
*/
public static RpcContextAttachment getClientResponseContext() {
return CLIENT_RESPONSE_LOCAL.get();
}
public static RpcContextAttachment getServerResponseContext() {
return SERVER_RESPONSE_LOCAL.get();
}
public static void removeClientResponseContext() {
CLIENT_RESPONSE_LOCAL.remove();
}
public static void removeServerResponseContext() {
SERVER_RESPONSE_LOCAL.remove();
}
/**
* get context.
*
* @return context
*/
@Deprecated
public static RpcContext getContext() {
return AGENT;
}
/**
* get consumer side attachment ( A --> B , in A side)
*
* @return context
*/
public static RpcContextAttachment getClientAttachment() {
return CLIENT_ATTACHMENT.get();
}
/**
* get provider side attachment from consumer ( A --> B , in B side)
*
* @return context
*/
public static RpcContextAttachment getServerAttachment() {
return SERVER_ATTACHMENT.get();
}
public static void removeServerContext() {
RpcContextAttachment rpcContextAttachment = RpcContext.getServerContext();
for (String key : rpcContextAttachment.attachments.keySet()) {
rpcContextAttachment.remove(key);
}
}
public boolean canRemove() {
return remove;
}
public void clearAfterEachInvoke(boolean remove) {
this.remove = remove;
}
/**
* Using to pass environment parameters in the whole invocation. For example, `remotingApplicationName`,
* `remoteAddress`, etc. {@link RpcServiceContext}
*
* @return context
*/
public static RpcServiceContext getServiceContext() {
return SERVICE_CONTEXT.get();
}
public static RpcServiceContext getCurrentServiceContext() {
return SERVICE_CONTEXT.getWithoutInitialize();
}
public static void removeServiceContext() {
SERVICE_CONTEXT.remove();
}
public static void removeClientAttachment() {
if (CLIENT_ATTACHMENT.get().canRemove()) {
CLIENT_ATTACHMENT.remove();
}
}
public static void removeServerAttachment() {
if (SERVER_ATTACHMENT.get().canRemove()) {
SERVER_ATTACHMENT.remove();
}
}
/**
* customized for internal use.
*/
public static void removeContext() {
if (CLIENT_ATTACHMENT.get().canRemove()) {
CLIENT_ATTACHMENT.remove();
}
if (SERVER_ATTACHMENT.get().canRemove()) {
SERVER_ATTACHMENT.remove();
}
CLIENT_RESPONSE_LOCAL.remove();
SERVER_RESPONSE_LOCAL.remove();
SERVICE_CONTEXT.remove();
CANCELLATION_CONTEXT.remove();
}
/**
* Get the request object of the underlying RPC protocol, e.g. HttpServletRequest
*
* @return null if the underlying protocol doesn't provide support for getting request
*/
public Object getRequest() {
return SERVICE_CONTEXT.get().getRequest();
}
public void setRequest(Object request) {
SERVICE_CONTEXT.get().setRequest(request);
}
/**
* Get the request object of the underlying RPC protocol, e.g. HttpServletRequest
*
* @return null if the underlying protocol doesn't provide support for getting request or the request is not of the specified type
*/
@SuppressWarnings("unchecked")
public <T> T getRequest(Class<T> clazz) {
return SERVICE_CONTEXT.get().getRequest(clazz);
}
/**
* Get the response object of the underlying RPC protocol, e.g. HttpServletResponse
*
* @return null if the underlying protocol doesn't provide support for getting response
*/
public Object getResponse() {
return SERVICE_CONTEXT.get().getResponse();
}
public void setResponse(Object response) {
SERVICE_CONTEXT.get().setResponse(response);
}
/**
* Get the response object of the underlying RPC protocol, e.g. HttpServletResponse
*
* @return null if the underlying protocol doesn't provide support for getting response or the response is not of the specified type
*/
@SuppressWarnings("unchecked")
public <T> T getResponse(Class<T> clazz) {
return SERVICE_CONTEXT.get().getResponse(clazz);
}
/**
* is provider side.
*
* @return provider side.
*/
public boolean isProviderSide() {
return SERVICE_CONTEXT.get().isProviderSide();
}
/**
* is consumer side.
*
* @return consumer side.
*/
public boolean isConsumerSide() {
return SERVICE_CONTEXT.get().isConsumerSide();
}
/**
* get CompletableFuture.
*
* @param <T>
* @return future
*/
@SuppressWarnings("unchecked")
public <T> CompletableFuture<T> getCompletableFuture() {
return SERVICE_CONTEXT.get().getCompletableFuture();
}
/**
* get future.
*
* @param <T>
* @return future
*/
@SuppressWarnings("unchecked")
public <T> Future<T> getFuture() {
return SERVICE_CONTEXT.get().getFuture();
}
/**
* set future.
*
* @param future
*/
public void setFuture(CompletableFuture<?> future) {
SERVICE_CONTEXT.get().setFuture(future);
}
public List<URL> getUrls() {
return SERVICE_CONTEXT.get().getUrls();
}
public void setUrls(List<URL> urls) {
SERVICE_CONTEXT.get().setUrls(urls);
}
public URL getUrl() {
return SERVICE_CONTEXT.get().getUrl();
}
public void setUrl(URL url) {
SERVICE_CONTEXT.get().setUrl(url);
}
/**
* get method name.
*
* @return method name.
*/
public String getMethodName() {
return SERVICE_CONTEXT.get().getMethodName();
}
public void setMethodName(String methodName) {
SERVICE_CONTEXT.get().setMethodName(methodName);
}
/**
* get parameter types.
*
* @serial
*/
public Class<?>[] getParameterTypes() {
return SERVICE_CONTEXT.get().getParameterTypes();
}
public void setParameterTypes(Class<?>[] parameterTypes) {
SERVICE_CONTEXT.get().setParameterTypes(parameterTypes);
}
/**
* get arguments.
*
* @return arguments.
*/
public Object[] getArguments() {
return SERVICE_CONTEXT.get().getArguments();
}
public void setArguments(Object[] arguments) {
SERVICE_CONTEXT.get().setArguments(arguments);
}
/**
* set local address.
*
* @param host
* @param port
* @return context
*/
public RpcContext setLocalAddress(String host, int port) {
return SERVICE_CONTEXT.get().setLocalAddress(host, port);
}
/**
* get local address.
*
* @return local address
*/
public InetSocketAddress getLocalAddress() {
return SERVICE_CONTEXT.get().getLocalAddress();
}
/**
* set local address.
*
* @param address
* @return context
*/
public RpcContext setLocalAddress(InetSocketAddress address) {
return SERVICE_CONTEXT.get().setLocalAddress(address);
}
public String getLocalAddressString() {
return SERVICE_CONTEXT.get().getLocalAddressString();
}
/**
* get local host name.
*
* @return local host name
*/
public String getLocalHostName() {
return SERVICE_CONTEXT.get().getLocalHostName();
}
/**
* set remote address.
*
* @param host
* @param port
* @return context
*/
public RpcContext setRemoteAddress(String host, int port) {
return SERVICE_CONTEXT.get().setRemoteAddress(host, port);
}
/**
* get remote address.
*
* @return remote address
*/
public InetSocketAddress getRemoteAddress() {
return SERVICE_CONTEXT.get().getRemoteAddress();
}
/**
* set remote address.
*
* @param address
* @return context
*/
public RpcContext setRemoteAddress(InetSocketAddress address) {
return SERVICE_CONTEXT.get().setRemoteAddress(address);
}
public String getRemoteApplicationName() {
return SERVICE_CONTEXT.get().getRemoteApplicationName();
}
public RpcContext setRemoteApplicationName(String remoteApplicationName) {
return SERVICE_CONTEXT.get().setRemoteApplicationName(remoteApplicationName);
}
/**
* get remote address string.
*
* @return remote address string.
*/
public String getRemoteAddressString() {
return SERVICE_CONTEXT.get().getRemoteAddressString();
}
/**
* get remote host name.
*
* @return remote host name
*/
public String getRemoteHostName() {
return SERVICE_CONTEXT.get().getRemoteHostName();
}
/**
* get local host.
*
* @return local host
*/
public String getLocalHost() {
return SERVICE_CONTEXT.get().getLocalHost();
}
/**
* get local port.
*
* @return port
*/
public int getLocalPort() {
return SERVICE_CONTEXT.get().getLocalPort();
}
/**
* get remote host.
*
* @return remote host
*/
public String getRemoteHost() {
return SERVICE_CONTEXT.get().getRemoteHost();
}
/**
* get remote port.
*
* @return remote port
*/
public int getRemotePort() {
return SERVICE_CONTEXT.get().getRemotePort();
}
/**
* also see {@link #getObjectAttachment(String)}.
*
* @param key
* @return attachment
*/
public String getAttachment(String key) {
String client = CLIENT_ATTACHMENT.get().getAttachment(key);
if (StringUtils.isEmpty(client)) {
return SERVER_ATTACHMENT.get().getAttachment(key);
}
return client;
}
/**
* get attachment.
*
* @param key
* @return attachment
*/
@Experimental("Experiment api for supporting Object transmission")
public Object getObjectAttachment(String key) {
Object client = CLIENT_ATTACHMENT.get().getObjectAttachment(key);
if (client == null) {
return SERVER_ATTACHMENT.get().getObjectAttachment(key);
}
return client;
}
/**
* set attachment.
*
* @param key
* @param value
* @return context
*/
public RpcContext setAttachment(String key, String value) {
return setObjectAttachment(key, value);
}
public RpcContext setAttachment(String key, Object value) {
return setObjectAttachment(key, value);
}
@Experimental("Experiment api for supporting Object transmission")
public RpcContext setObjectAttachment(String key, Object value) {
// TODO compatible with previous
CLIENT_ATTACHMENT.get().setObjectAttachment(key, value);
return this;
}
/**
* remove attachment.
*
* @param key
* @return context
*/
public RpcContext removeAttachment(String key) {
CLIENT_ATTACHMENT.get().removeAttachment(key);
return this;
}
/**
* get attachments.
*
* @return attachments
*/
@Deprecated
public Map<String, String> getAttachments() {
return new AttachmentsAdapter.ObjectToStringMap(this.getObjectAttachments());
}
/**
* get attachments.
*
* @return attachments
*/
@Experimental("Experiment api for supporting Object transmission")
public Map<String, Object> getObjectAttachments() {
Map<String, Object> result =
new HashMap<>((int) ((CLIENT_ATTACHMENT.get().attachments.size()
+ SERVER_ATTACHMENT.get().attachments.size())
/ .75)
+ 1);
result.putAll(SERVER_ATTACHMENT.get().attachments);
result.putAll(CLIENT_ATTACHMENT.get().attachments);
return result;
}
/**
* set attachments
*
* @param attachment
* @return context
*/
public RpcContext setAttachments(Map<String, String> attachment) {
CLIENT_ATTACHMENT.get().attachments.clear();
if (attachment != null && attachment.size() > 0) {
CLIENT_ATTACHMENT.get().attachments.putAll(attachment);
}
return this;
}
/**
* set attachments
*
* @param attachment
* @return context
*/
@Experimental("Experiment api for supporting Object transmission")
public RpcContext setObjectAttachments(Map<String, Object> attachment) {
CLIENT_ATTACHMENT.get().attachments.clear();
if (attachment != null && attachment.size() > 0) {
CLIENT_ATTACHMENT.get().attachments.putAll(attachment);
}
return this;
}
public void clearAttachments() {
CLIENT_ATTACHMENT.get().attachments.clear();
}
/**
* get values.
*
* @return values
*/
@Deprecated
public Map<String, Object> get() {
return CLIENT_ATTACHMENT.get().get();
}
/**
* set value.
*
* @param key
* @param value
* @return context
*/
@Deprecated
public RpcContext set(String key, Object value) {
CLIENT_ATTACHMENT.get().set(key, value);
return this;
}
/**
* remove value.
*
* @param key
* @return value
*/
@Deprecated
public RpcContext remove(String key) {
CLIENT_ATTACHMENT.get().remove(key);
return this;
}
/**
* get value.
*
* @param key
* @return value
*/
@Deprecated
public Object get(String key) {
return CLIENT_ATTACHMENT.get().get(key);
}
/**
* @deprecated Replace to isProviderSide()
*/
@Deprecated
public boolean isServerSide() {
return SERVICE_CONTEXT.get().isServerSide();
}
/**
* @deprecated Replace to isConsumerSide()
*/
@Deprecated
public boolean isClientSide() {
return SERVICE_CONTEXT.get().isClientSide();
}
/**
* @deprecated Replace to getUrls()
*/
@Deprecated
@SuppressWarnings({"unchecked", "rawtypes"})
public List<Invoker<?>> getInvokers() {
return SERVICE_CONTEXT.get().getInvokers();
}
public RpcContext setInvokers(List<Invoker<?>> invokers) {
return SERVICE_CONTEXT.get().setInvokers(invokers);
}
/**
* @deprecated Replace to getUrl()
*/
@Deprecated
public Invoker<?> getInvoker() {
return SERVICE_CONTEXT.get().getInvoker();
}
public RpcContext setInvoker(Invoker<?> invoker) {
return SERVICE_CONTEXT.get().setInvoker(invoker);
}
/**
* @deprecated Replace to getMethodName(), getParameterTypes(), getArguments()
*/
@Deprecated
public Invocation getInvocation() {
return SERVICE_CONTEXT.get().getInvocation();
}
public RpcContext setInvocation(Invocation invocation) {
return SERVICE_CONTEXT.get().setInvocation(invocation);
}
/**
* Async invocation. Timeout will be handled even if <code>Future.get()</code> is not called.
*
* @param callable
* @return get the return result from <code>future.get()</code>
*/
@SuppressWarnings("unchecked")
public <T> CompletableFuture<T> asyncCall(Callable<T> callable) {
return SERVICE_CONTEXT.get().asyncCall(callable);
}
/**
* one way async call, send request only, and result is not required
*
* @param runnable
*/
public void asyncCall(Runnable runnable) {
SERVICE_CONTEXT.get().asyncCall(runnable);
}
/**
* @return
* @throws IllegalStateException
*/
@SuppressWarnings("unchecked")
public static AsyncContext startAsync() throws IllegalStateException {
return RpcContextAttachment.startAsync();
}
protected void setAsyncContext(AsyncContext asyncContext) {
SERVER_ATTACHMENT.get().setAsyncContext(asyncContext);
}
public boolean isAsyncStarted() {
return SERVER_ATTACHMENT.get().isAsyncStarted();
}
public boolean stopAsync() {
return SERVER_ATTACHMENT.get().stopAsync();
}
public AsyncContext getAsyncContext() {
return SERVER_ATTACHMENT.get().getAsyncContext();
}
public String getGroup() {
return SERVICE_CONTEXT.get().getGroup();
}
public String getVersion() {
return SERVICE_CONTEXT.get().getVersion();
}
public String getInterfaceName() {
return SERVICE_CONTEXT.get().getInterfaceName();
}
public String getProtocol() {
return SERVICE_CONTEXT.get().getProtocol();
}
public String getServiceKey() {
return SERVICE_CONTEXT.get().getServiceKey();
}
public String getProtocolServiceKey() {
return SERVICE_CONTEXT.get().getProtocolServiceKey();
}
public URL getConsumerUrl() {
return SERVICE_CONTEXT.get().getConsumerUrl();
}
public void setConsumerUrl(URL consumerUrl) {
SERVICE_CONTEXT.get().setConsumerUrl(consumerUrl);
}
@Deprecated
public static void setRpcContext(URL url) {
RpcServiceContext.getServiceContext().setConsumerUrl(url);
}
protected static RestoreContext clearAndStoreContext() {
RestoreContext restoreContext = new RestoreContext();
RpcContext.removeContext();
return restoreContext;
}
protected static RestoreContext storeContext() {
return new RestoreContext();
}
public static RestoreServiceContext storeServiceContext() {
return new RestoreServiceContext();
}
public static void restoreServiceContext(RestoreServiceContext restoreServiceContext) {
if (restoreServiceContext != null) {
restoreServiceContext.restore();
}
}
protected static void restoreContext(RestoreContext restoreContext) {
if (restoreContext != null) {
restoreContext.restore();
}
}
/**
* Used to temporarily store and restore all kinds of contexts of current thread.
*/
public static class RestoreContext {
private final RpcServiceContext serviceContext;
private final RpcContextAttachment clientAttachment;
private final RpcContextAttachment serverAttachment;
private final RpcContextAttachment clientResponseLocal;
private final RpcContextAttachment serverResponseLocal;
public RestoreContext() {
serviceContext = getServiceContext().copyOf(false);
clientAttachment = getClientAttachment().copyOf(false);
serverAttachment = getServerAttachment().copyOf(false);
clientResponseLocal = getClientResponseContext().copyOf(false);
serverResponseLocal = getServerResponseContext().copyOf(false);
}
public void restore() {
if (serviceContext != null) {
SERVICE_CONTEXT.set(serviceContext);
} else {
removeServiceContext();
}
if (clientAttachment != null) {
CLIENT_ATTACHMENT.set(clientAttachment);
} else {
removeClientAttachment();
}
if (serverAttachment != null) {
SERVER_ATTACHMENT.set(serverAttachment);
} else {
removeServerAttachment();
}
if (clientResponseLocal != null) {
CLIENT_RESPONSE_LOCAL.set(clientResponseLocal);
} else {
removeClientResponseContext();
}
if (serverResponseLocal != null) {
SERVER_RESPONSE_LOCAL.set(serverResponseLocal);
} else {
removeServerResponseContext();
}
}
}
public static class RestoreServiceContext {
private final RpcServiceContext serviceContext;
public RestoreServiceContext() {
RpcServiceContext originContext = getCurrentServiceContext();
if (originContext == null) {
this.serviceContext = null;
} else {
this.serviceContext = originContext.copyOf(true);
}
}
protected void restore() {
if (serviceContext != null) {
SERVICE_CONTEXT.set(serviceContext);
} else {
removeServiceContext();
}
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ServerService.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ServerService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.model.ServiceDescriptor;
public interface ServerService<T> {
Invoker<T> getInvoker(URL url);
ServiceDescriptor getServiceDescriptor();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcStatus.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcStatus.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.ConcurrentHashMapUtils;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
/**
* URL statistics. (API, Cached, ThreadSafe)
*
* @see org.apache.dubbo.rpc.filter.ActiveLimitFilter
* @see org.apache.dubbo.rpc.filter.ExecuteLimitFilter
* @see org.apache.dubbo.rpc.cluster.loadbalance.LeastActiveLoadBalance
*/
public class RpcStatus {
private static final ConcurrentMap<String, RpcStatus> SERVICE_STATISTICS = new ConcurrentHashMap<>();
private static final ConcurrentMap<String, ConcurrentMap<String, RpcStatus>> METHOD_STATISTICS =
new ConcurrentHashMap<>();
private final ConcurrentMap<String, Object> values = new ConcurrentHashMap<>();
private final AtomicInteger active = new AtomicInteger();
private final AtomicLong total = new AtomicLong();
private final AtomicInteger failed = new AtomicInteger();
private final AtomicLong totalElapsed = new AtomicLong();
private final AtomicLong failedElapsed = new AtomicLong();
private final AtomicLong maxElapsed = new AtomicLong();
private final AtomicLong failedMaxElapsed = new AtomicLong();
private final AtomicLong succeededMaxElapsed = new AtomicLong();
private RpcStatus() {}
/**
* @param url
* @return status
*/
public static RpcStatus getStatus(URL url) {
String uri = url.toIdentityString();
return ConcurrentHashMapUtils.computeIfAbsent(SERVICE_STATISTICS, uri, key -> new RpcStatus());
}
/**
* @param url
*/
public static void removeStatus(URL url) {
String uri = url.toIdentityString();
SERVICE_STATISTICS.remove(uri);
}
/**
* @param url
* @param methodName
* @return status
*/
public static RpcStatus getStatus(URL url, String methodName) {
String uri = url.toIdentityString();
ConcurrentMap<String, RpcStatus> map =
ConcurrentHashMapUtils.computeIfAbsent(METHOD_STATISTICS, uri, k -> new ConcurrentHashMap<>());
return ConcurrentHashMapUtils.computeIfAbsent(map, methodName, k -> new RpcStatus());
}
/**
* @param url
*/
public static void removeStatus(URL url, String methodName) {
String uri = url.toIdentityString();
ConcurrentMap<String, RpcStatus> map = METHOD_STATISTICS.get(uri);
if (map != null) {
map.remove(methodName);
}
}
public static void beginCount(URL url, String methodName) {
beginCount(url, methodName, Integer.MAX_VALUE);
}
/**
* @param url
*/
public static boolean beginCount(URL url, String methodName, int max) {
max = (max <= 0) ? Integer.MAX_VALUE : max;
RpcStatus appStatus = getStatus(url);
RpcStatus methodStatus = getStatus(url, methodName);
if (methodStatus.active.get() == Integer.MAX_VALUE) {
return false;
}
for (int i; ; ) {
i = methodStatus.active.get();
if (i == Integer.MAX_VALUE || i + 1 > max) {
return false;
}
if (methodStatus.active.compareAndSet(i, i + 1)) {
break;
}
}
appStatus.active.incrementAndGet();
return true;
}
/**
* @param url
* @param elapsed
* @param succeeded
*/
public static void endCount(URL url, String methodName, long elapsed, boolean succeeded) {
endCount(getStatus(url), elapsed, succeeded);
endCount(getStatus(url, methodName), elapsed, succeeded);
}
private static void endCount(RpcStatus status, long elapsed, boolean succeeded) {
status.active.decrementAndGet();
status.total.incrementAndGet();
status.totalElapsed.addAndGet(elapsed);
if (status.maxElapsed.get() < elapsed) {
status.maxElapsed.set(elapsed);
}
if (succeeded) {
if (status.succeededMaxElapsed.get() < elapsed) {
status.succeededMaxElapsed.set(elapsed);
}
} else {
status.failed.incrementAndGet();
status.failedElapsed.addAndGet(elapsed);
if (status.failedMaxElapsed.get() < elapsed) {
status.failedMaxElapsed.set(elapsed);
}
}
}
/**
* set value.
*
* @param key
* @param value
*/
public void set(String key, Object value) {
values.put(key, value);
}
/**
* get value.
*
* @param key
* @return value
*/
public Object get(String key) {
return values.get(key);
}
/**
* get active.
*
* @return active
*/
public int getActive() {
return active.get();
}
/**
* get total.
*
* @return total
*/
public long getTotal() {
return total.longValue();
}
/**
* get total elapsed.
*
* @return total elapsed
*/
public long getTotalElapsed() {
return totalElapsed.get();
}
/**
* get average elapsed.
*
* @return average elapsed
*/
public long getAverageElapsed() {
long total = getTotal();
if (total == 0) {
return 0;
}
return getTotalElapsed() / total;
}
/**
* get max elapsed.
*
* @return max elapsed
*/
public long getMaxElapsed() {
return maxElapsed.get();
}
/**
* get failed.
*
* @return failed
*/
public int getFailed() {
return failed.get();
}
/**
* get failed elapsed.
*
* @return failed elapsed
*/
public long getFailedElapsed() {
return failedElapsed.get();
}
/**
* get failed average elapsed.
*
* @return failed average elapsed
*/
public long getFailedAverageElapsed() {
long failed = getFailed();
if (failed == 0) {
return 0;
}
return getFailedElapsed() / failed;
}
/**
* get failed max elapsed.
*
* @return failed max elapsed
*/
public long getFailedMaxElapsed() {
return failedMaxElapsed.get();
}
/**
* get succeeded.
*
* @return succeeded
*/
public long getSucceeded() {
return getTotal() - getFailed();
}
/**
* get succeeded elapsed.
*
* @return succeeded elapsed
*/
public long getSucceededElapsed() {
return getTotalElapsed() - getFailedElapsed();
}
/**
* get succeeded average elapsed.
*
* @return succeeded average elapsed
*/
public long getSucceededAverageElapsed() {
long succeeded = getSucceeded();
if (succeeded == 0) {
return 0;
}
return getSucceededElapsed() / succeeded;
}
/**
* get succeeded max elapsed.
*
* @return succeeded max elapsed.
*/
public long getSucceededMaxElapsed() {
return succeededMaxElapsed.get();
}
/**
* Calculate average TPS (Transaction per second).
*
* @return tps
*/
public long getAverageTps() {
if (getTotalElapsed() >= 1000L) {
return getTotal() / (getTotalElapsed() / 1000L);
}
return getTotal();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Result.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Result.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc;
import org.apache.dubbo.common.Experimental;
import java.io.Serializable;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.BiConsumer;
import java.util.function.Function;
/**
* (API, Prototype, NonThreadSafe)
*
* An RPC {@link Result}.
*
* Known implementations are:
* 1. {@link AsyncRpcResult}, it's a {@link CompletionStage} whose underlying value signifies the return value of an RPC call.
* 2. {@link AppResponse}, it inevitably inherits {@link CompletionStage} and {@link Future}, but you should never treat AppResponse as a type of Future,
* instead, it is a normal concrete type.
*
* @serial Don't change the class name and package name.
* @see org.apache.dubbo.rpc.Invoker#invoke(Invocation)
* @see AppResponse
*/
public interface Result extends Serializable {
/**
* Get invoke result.
*
* @return result. if no result return null.
*/
Object getValue();
void setValue(Object value);
/**
* Get exception.
*
* @return exception. if no exception return null.
*/
Throwable getException();
void setException(Throwable t);
/**
* Has exception.
*
* @return has exception.
*/
boolean hasException();
/**
* Recreate.
* <p>
* <code>
* if (hasException()) {
* throw getException();
* } else {
* return getValue();
* }
* </code>
*
* @return result.
* @throws if has exception throw it.
*/
Object recreate() throws Throwable;
/**
* get attachments.
*
* @return attachments.
*/
Map<String, String> getAttachments();
/**
* get attachments.
*
* @return attachments.
*/
@Experimental("Experiment api for supporting Object transmission")
Map<String, Object> getObjectAttachments();
/**
* Add the specified map to existing attachments in this instance.
*
* @param map
*/
void addAttachments(Map<String, String> map);
/**
* Add the specified map to existing attachments in this instance.
*
* @param map
*/
@Experimental("Experiment api for supporting Object transmission")
void addObjectAttachments(Map<String, Object> map);
/**
* Replace the existing attachments with the specified param.
*
* @param map
*/
void setAttachments(Map<String, String> map);
/**
* Replace the existing attachments with the specified param.
*
* @param map
*/
@Experimental("Experiment api for supporting Object transmission")
void setObjectAttachments(Map<String, Object> map);
/**
* get attachment by key.
*
* @return attachment value.
*/
String getAttachment(String key);
/**
* get attachment by key.
*
* @return attachment value.
*/
@Experimental("Experiment api for supporting Object transmission")
Object getObjectAttachment(String key);
/**
* get attachment by key with default value.
*
* @return attachment value.
*/
String getAttachment(String key, String defaultValue);
/**
* get attachment by key with default value.
*
* @return attachment value.
*/
@Experimental("Experiment api for supporting Object transmission")
Object getObjectAttachment(String key, Object defaultValue);
void setAttachment(String key, String value);
@Experimental("Experiment api for supporting Object transmission")
void setAttachment(String key, Object value);
@Experimental("Experiment api for supporting Object transmission")
void setObjectAttachment(String key, Object value);
/**
* Add a callback which can be triggered when the RPC call finishes.
* <p>
* Just as the method name implies, this method will guarantee the callback being triggered under the same context as when the call was started,
* see implementation in {@link Result#whenCompleteWithContext(BiConsumer)}
*
* @param fn
* @return
*/
Result whenCompleteWithContext(BiConsumer<Result, Throwable> fn);
<U> CompletableFuture<U> thenApply(Function<Result, ? extends U> fn);
Result get() throws InterruptedException, ExecutionException;
Result get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException;
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Invoker.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Invoker.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc;
import org.apache.dubbo.common.Node;
/**
* Invoker. (API/SPI, Prototype, ThreadSafe)
*
* @see org.apache.dubbo.rpc.Protocol#refer(Class, org.apache.dubbo.common.URL)
* @see org.apache.dubbo.rpc.InvokerListener
* @see org.apache.dubbo.rpc.protocol.AbstractInvoker
*/
public interface Invoker<T> extends Node {
/**
* get service interface.
*
* @return service interface.
*/
Class<T> getInterface();
/**
* invoke.
*
* @param invocation
* @return result
* @throws RpcException
*/
Result invoke(Invocation invocation) throws RpcException;
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ZoneDetector.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ZoneDetector.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc;
import org.apache.dubbo.common.extension.SPI;
/**
* Extend and provide your own implementation if you want to distribute traffic around registries.
* Please, name it as 'default'
*/
@SPI
public interface ZoneDetector {
String getZoneOfCurrentRequest(Invocation invocation);
String isZoneForcingEnabled(Invocation invocation, String zone);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/InvokerListener.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/InvokerListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc;
import org.apache.dubbo.common.extension.SPI;
/**
* InvokerListener. (SPI, Singleton, ThreadSafe)
*/
@SPI
public interface InvokerListener {
/**
* The invoker referred
*
* @param invoker
* @throws RpcException
* @see org.apache.dubbo.rpc.Protocol#refer(Class, org.apache.dubbo.common.URL)
*/
void referred(Invoker<?> invoker) throws RpcException;
/**
* The invoker destroyed.
*
* @param invoker
* @see org.apache.dubbo.rpc.Invoker#destroy()
*/
void destroyed(Invoker<?> invoker);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/GracefulShutdown.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/GracefulShutdown.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.List;
public interface GracefulShutdown {
void readonly();
void writeable();
static List<GracefulShutdown> getGracefulShutdowns(FrameworkModel frameworkModel) {
return frameworkModel.getBeanFactory().getBeansOfType(GracefulShutdown.class);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/InvocationProfilerUtils.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/InvocationProfilerUtils.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc;
import org.apache.dubbo.common.profiler.Profiler;
import org.apache.dubbo.common.profiler.ProfilerEntry;
import org.apache.dubbo.common.profiler.ProfilerSwitch;
import java.util.concurrent.Callable;
public class InvocationProfilerUtils {
public static void enterSimpleProfiler(Invocation invocation, Callable<String> messageCallable) {
if (ProfilerSwitch.isEnableSimpleProfiler()) {
enterProfiler(invocation, messageCallable);
}
}
public static void releaseSimpleProfiler(Invocation invocation) {
if (ProfilerSwitch.isEnableSimpleProfiler()) {
releaseProfiler(invocation);
}
}
public static void enterDetailProfiler(Invocation invocation, Callable<String> messageCallable) {
if (ProfilerSwitch.isEnableDetailProfiler()) {
enterProfiler(invocation, messageCallable);
}
}
public static void releaseDetailProfiler(Invocation invocation) {
if (ProfilerSwitch.isEnableDetailProfiler()) {
releaseProfiler(invocation);
}
}
public static void enterProfiler(Invocation invocation, String message) {
Object fromInvocation = invocation.get(Profiler.PROFILER_KEY);
if (fromInvocation instanceof ProfilerEntry) {
invocation.put(Profiler.PROFILER_KEY, Profiler.enter((ProfilerEntry) fromInvocation, message));
}
}
public static void enterProfiler(Invocation invocation, Callable<String> messageCallable) {
Object fromInvocation = invocation.get(Profiler.PROFILER_KEY);
if (fromInvocation instanceof ProfilerEntry) {
String message = "";
try {
message = messageCallable.call();
} catch (Exception ignore) {
}
invocation.put(Profiler.PROFILER_KEY, Profiler.enter((ProfilerEntry) fromInvocation, message));
}
}
public static void releaseProfiler(Invocation invocation) {
Object fromInvocation = invocation.get(Profiler.PROFILER_KEY);
if (fromInvocation instanceof ProfilerEntry) {
invocation.put(Profiler.PROFILER_KEY, Profiler.release((ProfilerEntry) fromInvocation));
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AsyncRpcResult.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AsyncRpcResult.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.threadpool.ThreadlessExecutor;
import org.apache.dubbo.common.utils.SystemPropertyConfigUtils;
import org.apache.dubbo.rpc.model.ConsumerMethodModel;
import org.apache.dubbo.rpc.protocol.dubbo.FutureAdapter;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.BiConsumer;
import java.util.function.Function;
import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_ASYNC_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROXY_ERROR_ASYNC_RESPONSE;
import static org.apache.dubbo.common.utils.ReflectUtils.defaultReturn;
/**
* This class represents an unfinished RPC call, it will hold some context information for this call, for example RpcContext and Invocation,
* so that when the call finishes and the result returns, it can guarantee all the contexts being recovered as the same as when the call was made
* before any callback is invoked.
* <p>
* TODO if it's reasonable or even right to keep a reference to Invocation?
* <p>
* As {@link Result} implements CompletionStage, {@link AsyncRpcResult} allows you to easily build a async filter chain whose status will be
* driven entirely by the state of the underlying RPC call.
* <p>
* AsyncRpcResult does not contain any concrete value (except the underlying value bring by CompletableFuture), consider it as a status transfer node.
* {@link #getValue()} and {@link #getException()} are all inherited from {@link Result} interface, implementing them are mainly
* for compatibility consideration. Because many legacy {@link Filter} implementation are most possibly to call getValue directly.
*/
public class AsyncRpcResult implements Result {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(AsyncRpcResult.class);
/**
* RpcContext may already have been changed when callback happens, it happens when the same thread is used to execute another RPC call.
* So we should keep the copy of current RpcContext instance and restore it before callback being executed.
*/
private RpcContext.RestoreContext storedContext;
private Executor executor;
private final Invocation invocation;
private final boolean async;
private CompletableFuture<AppResponse> responseFuture;
/**
* Whether set future to Thread Local when invocation mode is sync
*/
private static final boolean setFutureWhenSync = Boolean.parseBoolean(SystemPropertyConfigUtils.getSystemProperty(
CommonConstants.ThirdPartyProperty.SET_FUTURE_IN_SYNC_MODE, "true"));
public AsyncRpcResult(CompletableFuture<AppResponse> future, Invocation invocation) {
this.responseFuture = future;
this.invocation = invocation;
RpcInvocation rpcInvocation = (RpcInvocation) invocation;
if ((rpcInvocation.get(PROVIDER_ASYNC_KEY) != null || InvokeMode.SYNC != rpcInvocation.getInvokeMode())
&& !future.isDone()) {
async = true;
this.storedContext = RpcContext.clearAndStoreContext();
} else {
async = false;
}
}
/**
* Notice the return type of {@link #getValue} is the actual type of the RPC method, not {@link AppResponse}
*
* @return
*/
@Override
public Object getValue() {
return getAppResponse().getValue();
}
/**
* CompletableFuture can only be completed once, so try to update the result of one completed CompletableFuture will
* have no effect. To avoid this problem, we check the complete status of this future before update its value.
* <p>
* But notice that trying to give an uncompleted CompletableFuture a new specified value may face a race condition,
* because the background thread watching the real result will also change the status of this CompletableFuture.
* The result is you may lose the value you expected to set.
*
* @param value
*/
@Override
public void setValue(Object value) {
try {
if (responseFuture.isDone()) {
responseFuture.get().setValue(value);
} else {
AppResponse appResponse = new AppResponse(invocation);
appResponse.setValue(value);
responseFuture.complete(appResponse);
}
} catch (Exception e) {
// This should not happen in normal request process;
logger.error(
PROXY_ERROR_ASYNC_RESPONSE,
"",
"",
"Got exception when trying to fetch the underlying result from AsyncRpcResult.");
throw new RpcException(e);
}
}
@Override
public Throwable getException() {
return getAppResponse().getException();
}
@Override
public void setException(Throwable t) {
try {
if (responseFuture.isDone()) {
responseFuture.get().setException(t);
} else {
AppResponse appResponse = new AppResponse(invocation);
appResponse.setException(t);
responseFuture.complete(appResponse);
}
} catch (Exception e) {
// This should not happen in normal request process;
logger.error(
PROXY_ERROR_ASYNC_RESPONSE,
"",
"",
"Got exception when trying to fetch the underlying result from AsyncRpcResult.");
throw new RpcException(e);
}
}
@Override
public boolean hasException() {
return getAppResponse().hasException();
}
public CompletableFuture<AppResponse> getResponseFuture() {
return responseFuture;
}
public void setResponseFuture(CompletableFuture<AppResponse> responseFuture) {
this.responseFuture = responseFuture;
}
public Result getAppResponse() {
try {
if (responseFuture.isDone()) {
return responseFuture.get();
}
} catch (Exception e) {
// This should not happen in normal request process;
logger.error(
PROXY_ERROR_ASYNC_RESPONSE,
"",
"",
"Got exception when trying to fetch the underlying result from AsyncRpcResult.");
throw new RpcException(e);
}
return createDefaultValue(invocation);
}
/**
* This method will always return after a maximum 'timeout' waiting:
* 1. if value returns before timeout, return normally.
* 2. if no value returns after timeout, throw TimeoutException.
*
* @return
* @throws InterruptedException
* @throws ExecutionException
*/
@Override
public Result get() throws InterruptedException, ExecutionException {
if (executor instanceof ThreadlessExecutor) {
ThreadlessExecutor threadlessExecutor = (ThreadlessExecutor) executor;
try {
while (!responseFuture.isDone() && !threadlessExecutor.isShutdown()) {
threadlessExecutor.waitAndDrain(Long.MAX_VALUE);
}
} finally {
threadlessExecutor.shutdown();
}
}
return responseFuture.get();
}
@Override
public Result get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
long deadline = System.nanoTime() + unit.toNanos(timeout);
if (executor instanceof ThreadlessExecutor) {
ThreadlessExecutor threadlessExecutor = (ThreadlessExecutor) executor;
try {
while (!responseFuture.isDone() && !threadlessExecutor.isShutdown()) {
long restTime = deadline - System.nanoTime();
if (restTime > 0) {
threadlessExecutor.waitAndDrain(deadline);
} else {
throw new TimeoutException(
"Timeout after " + unit.toMillis(timeout) + "ms waiting for result.");
}
}
} finally {
threadlessExecutor.shutdown();
}
}
long restTime = deadline - System.nanoTime();
if (!responseFuture.isDone() && restTime < 0) {
throw new TimeoutException("Timeout after " + unit.toMillis(timeout) + "ms waiting for result.");
}
return responseFuture.get(restTime, TimeUnit.NANOSECONDS);
}
@Override
public Object recreate() throws Throwable {
RpcInvocation rpcInvocation = (RpcInvocation) invocation;
if (InvokeMode.FUTURE == rpcInvocation.getInvokeMode()) {
return RpcContext.getClientAttachment().getFuture();
} else if (InvokeMode.ASYNC == rpcInvocation.getInvokeMode()) {
return createDefaultValue(invocation).recreate();
}
return getAppResponse().recreate();
}
public Result whenCompleteWithContext(BiConsumer<Result, Throwable> fn) {
this.responseFuture = this.responseFuture.whenComplete((v, t) -> {
if (async) {
RpcContext.restoreContext(storedContext);
}
fn.accept(v, t);
});
if (setFutureWhenSync || ((RpcInvocation) invocation).getInvokeMode() != InvokeMode.SYNC) {
// Necessary! update future in context, see https://github.com/apache/dubbo/issues/9461
RpcContext.getServiceContext().setFuture(new FutureAdapter<>(this.responseFuture));
}
return this;
}
@Override
public <U> CompletableFuture<U> thenApply(Function<Result, ? extends U> fn) {
return this.responseFuture.thenApply(fn);
}
@Override
@Deprecated
public Map<String, String> getAttachments() {
return getAppResponse().getAttachments();
}
@Override
public Map<String, Object> getObjectAttachments() {
return getAppResponse().getObjectAttachments();
}
@Override
public void setAttachments(Map<String, String> map) {
getAppResponse().setAttachments(map);
}
@Override
public void setObjectAttachments(Map<String, Object> map) {
getAppResponse().setObjectAttachments(map);
}
@Deprecated
@Override
public void addAttachments(Map<String, String> map) {
getAppResponse().addAttachments(map);
}
@Override
public void addObjectAttachments(Map<String, Object> map) {
getAppResponse().addObjectAttachments(map);
}
@Override
public String getAttachment(String key) {
return getAppResponse().getAttachment(key);
}
@Override
public Object getObjectAttachment(String key) {
return getAppResponse().getObjectAttachment(key);
}
@Override
public String getAttachment(String key, String defaultValue) {
return getAppResponse().getAttachment(key, defaultValue);
}
@Override
public Object getObjectAttachment(String key, Object defaultValue) {
return getAppResponse().getObjectAttachment(key, defaultValue);
}
@Override
public void setAttachment(String key, String value) {
setObjectAttachment(key, value);
}
@Override
public void setAttachment(String key, Object value) {
setObjectAttachment(key, value);
}
@Override
public void setObjectAttachment(String key, Object value) {
getAppResponse().setAttachment(key, value);
}
public Executor getExecutor() {
return executor;
}
public void setExecutor(Executor executor) {
this.executor = executor;
}
/**
* Some utility methods used to quickly generate default AsyncRpcResult instance.
*/
public static AsyncRpcResult newDefaultAsyncResult(AppResponse appResponse, Invocation invocation) {
return new AsyncRpcResult(CompletableFuture.completedFuture(appResponse), invocation);
}
public static AsyncRpcResult newDefaultAsyncResult(Invocation invocation) {
return newDefaultAsyncResult(null, null, invocation);
}
public static AsyncRpcResult newDefaultAsyncResult(Object value, Invocation invocation) {
return newDefaultAsyncResult(value, null, invocation);
}
public static AsyncRpcResult newDefaultAsyncResult(Throwable t, Invocation invocation) {
return newDefaultAsyncResult(null, t, invocation);
}
public static AsyncRpcResult newDefaultAsyncResult(Object value, Throwable t, Invocation invocation) {
CompletableFuture<AppResponse> future = new CompletableFuture<>();
AppResponse result = new AppResponse(invocation);
if (t != null) {
result.setException(t);
} else {
result.setValue(value);
}
future.complete(result);
return new AsyncRpcResult(future, invocation);
}
private static Result createDefaultValue(Invocation invocation) {
ConsumerMethodModel method = (ConsumerMethodModel) invocation.get(Constants.METHOD_MODEL);
return method != null ? new AppResponse(defaultReturn(method.getReturnClass())) : new AppResponse();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/HeaderFilter.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/HeaderFilter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
@SPI(scope = ExtensionScope.FRAMEWORK)
public interface HeaderFilter {
RpcInvocation invoke(Invoker<?> invoker, RpcInvocation invocation) throws RpcException;
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcException.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc;
import javax.naming.LimitExceededException;
/**
* RPC Exception. (API, Prototype, ThreadSafe)
*
* @serial Don't change the class name and properties.
* @see org.apache.dubbo.rpc.Invoker#invoke(Invocation)
* @since 1.0
*/
public class RpcException extends RuntimeException {
public static final int UNKNOWN_EXCEPTION = 0;
public static final int NETWORK_EXCEPTION = 1;
public static final int TIMEOUT_EXCEPTION = 2;
public static final int BIZ_EXCEPTION = 3;
public static final int FORBIDDEN_EXCEPTION = 4;
public static final int SERIALIZATION_EXCEPTION = 5;
public static final int NO_INVOKER_AVAILABLE_AFTER_FILTER = 6;
public static final int LIMIT_EXCEEDED_EXCEPTION = 7;
public static final int TIMEOUT_TERMINATE = 8;
public static final int REGISTRY_EXCEPTION = 9;
public static final int ROUTER_CACHE_NOT_BUILD = 10;
public static final int METHOD_NOT_FOUND = 11;
public static final int VALIDATION_EXCEPTION = 12;
public static final int AUTHORIZATION_EXCEPTION = 13;
private static final long serialVersionUID = 7815426752583648734L;
/**
* RpcException cannot be extended, use error code for exception type to keep compatibility
*/
private int code;
public RpcException() {
super();
}
public RpcException(String message, Throwable cause) {
super(message, cause);
}
public RpcException(String message) {
super(message);
}
public RpcException(Throwable cause) {
super(cause);
}
public RpcException(int code) {
super();
this.code = code;
}
public RpcException(int code, String message, Throwable cause) {
super(message, cause);
this.code = code;
}
public RpcException(int code, String message) {
super(message);
this.code = code;
}
public RpcException(int code, Throwable cause) {
super(cause);
this.code = code;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public boolean isBiz() {
return code == BIZ_EXCEPTION;
}
public boolean isForbidden() {
return code == FORBIDDEN_EXCEPTION;
}
public boolean isTimeout() {
return code == TIMEOUT_EXCEPTION;
}
public boolean isNetwork() {
return code == NETWORK_EXCEPTION;
}
public boolean isSerialization() {
return code == SERIALIZATION_EXCEPTION;
}
public boolean isAuthorization() {
return code == AUTHORIZATION_EXCEPTION;
}
public boolean isNoInvokerAvailableAfterFilter() {
return code == NO_INVOKER_AVAILABLE_AFTER_FILTER;
}
public boolean isLimitExceed() {
return code == LIMIT_EXCEEDED_EXCEPTION || getCause() instanceof LimitExceededException;
}
public boolean isValidation() {
return code == VALIDATION_EXCEPTION;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AdaptiveScopeModelInitializer.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AdaptiveScopeModelInitializer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc;
import org.apache.dubbo.common.beans.factory.ScopeBeanFactory;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ScopeModelInitializer;
public class AdaptiveScopeModelInitializer implements ScopeModelInitializer {
@Override
public void initializeApplicationModel(ApplicationModel applicationModel) {
ScopeBeanFactory beanFactory = applicationModel.getBeanFactory();
beanFactory.registerBean(AdaptiveMetrics.class);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/PathResolver.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/PathResolver.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
/**
* PathResolver maintains a mapping between request paths and invokers for multiple protocols.
*/
@SPI(value = CommonConstants.TRIPLE, scope = ExtensionScope.FRAMEWORK)
public interface PathResolver {
void register(Invoker<?> invoker);
void unregister(Invoker<?> invoker);
Invoker<?> add(String path, Invoker<?> invoker);
Invoker<?> addIfAbsent(String path, Invoker<?> invoker);
Invoker<?> resolve(String path, String group, String version);
boolean hasNativeStub(String path);
void addNativeStub(String path);
void remove(String path);
void destroy();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcServiceContext.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcServiceContext.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.common.utils.StringUtils;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE;
import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE;
import static org.apache.dubbo.rpc.Constants.ASYNC_KEY;
import static org.apache.dubbo.rpc.Constants.RETURN_KEY;
public class RpcServiceContext extends RpcContext {
protected RpcServiceContext() {}
// RPC service context updated before each service call.
private URL consumerUrl;
private List<URL> urls;
private URL url;
private String methodName;
private Class<?>[] parameterTypes;
private Object[] arguments;
private InetSocketAddress localAddress;
private InetSocketAddress remoteAddress;
private String remoteApplicationName;
private Boolean localInvoke;
@Deprecated
private List<Invoker<?>> invokers;
@Deprecated
private Invoker<?> invoker;
@Deprecated
private Invocation invocation;
// now we don't use the 'values' map to hold these objects
// we want these objects to be as generic as possible
private Object request;
private Object response;
private boolean needPrintRouterSnapshot;
/**
* Get the request object of the underlying RPC protocol, e.g. HttpServletRequest
*
* @return null if the underlying protocol doesn't provide support for getting request
*/
@Override
public Object getRequest() {
return request;
}
@Override
public void setRequest(Object request) {
this.request = request;
}
/**
* Get the request object of the underlying RPC protocol, e.g. HttpServletRequest
*
* @return null if the underlying protocol doesn't provide support for getting request or the request is not of the specified type
*/
@Override
@SuppressWarnings("unchecked")
public <T> T getRequest(Class<T> clazz) {
return (request != null && clazz.isAssignableFrom(request.getClass())) ? (T) request : null;
}
/**
* Get the response object of the underlying RPC protocol, e.g. HttpServletResponse
*
* @return null if the underlying protocol doesn't provide support for getting response
*/
@Override
public Object getResponse() {
return response;
}
@Override
public void setResponse(Object response) {
this.response = response;
}
/**
* Get the response object of the underlying RPC protocol, e.g. HttpServletResponse
*
* @return null if the underlying protocol doesn't provide support for getting response or the response is not of the specified type
*/
@Override
@SuppressWarnings("unchecked")
public <T> T getResponse(Class<T> clazz) {
return (response != null && clazz.isAssignableFrom(response.getClass())) ? (T) response : null;
}
/**
* is provider side.
*
* @return provider side.
*/
@Override
public boolean isProviderSide() {
return !isConsumerSide();
}
/**
* is consumer side.
*
* @return consumer side.
*/
@Override
public boolean isConsumerSide() {
return getUrl().getSide(PROVIDER_SIDE).equals(CONSUMER_SIDE);
}
/**
* get CompletableFuture.
*
* @param <T>
* @return future
*/
@Override
@SuppressWarnings("unchecked")
public <T> CompletableFuture<T> getCompletableFuture() {
return FutureContext.getContext().getCompletableFuture();
}
/**
* get future.
*
* @param <T>
* @return future
*/
@Override
@SuppressWarnings("unchecked")
public <T> Future<T> getFuture() {
return FutureContext.getContext().getCompletableFuture();
}
/**
* set future.
*
* @param future
*/
@Override
public void setFuture(CompletableFuture<?> future) {
FutureContext.getContext().setFuture(future);
}
@Override
public List<URL> getUrls() {
return urls == null && url != null ? Arrays.asList(url) : urls;
}
@Override
public void setUrls(List<URL> urls) {
this.urls = urls;
if (!urls.isEmpty()) {
this.url = urls.get(0);
}
}
@Override
public URL getUrl() {
return url;
}
@Override
public void setUrl(URL url) {
this.url = url;
}
/**
* get method name.
*
* @return method name.
*/
@Override
public String getMethodName() {
return methodName;
}
@Override
public void setMethodName(String methodName) {
this.methodName = methodName;
}
/**
* get parameter types.
*
* @serial
*/
@Override
public Class<?>[] getParameterTypes() {
return parameterTypes;
}
@Override
public void setParameterTypes(Class<?>[] parameterTypes) {
this.parameterTypes = parameterTypes;
}
/**
* get arguments.
*
* @return arguments.
*/
@Override
public Object[] getArguments() {
return arguments;
}
@Override
public void setArguments(Object[] arguments) {
this.arguments = arguments;
}
/**
* set local address.
*
* @param host
* @param port
* @return context
*/
@Override
public RpcServiceContext setLocalAddress(String host, int port) {
if (port < 0) {
port = 0;
}
this.localAddress = InetSocketAddress.createUnresolved(host, port);
return this;
}
/**
* get local address.
*
* @return local address
*/
@Override
public InetSocketAddress getLocalAddress() {
return localAddress;
}
/**
* set local address.
*
* @param address
* @return context
*/
@Override
public RpcServiceContext setLocalAddress(InetSocketAddress address) {
this.localAddress = address;
return this;
}
@Override
public String getLocalAddressString() {
return getLocalHost() + ":" + getLocalPort();
}
/**
* get local host name.
*
* @return local host name
*/
@Override
public String getLocalHostName() {
String host = localAddress == null ? null : localAddress.getHostName();
if (StringUtils.isEmpty(host)) {
return getLocalHost();
}
return host;
}
/**
* set remote address.
*
* @param host
* @param port
* @return context
*/
@Override
public RpcServiceContext setRemoteAddress(String host, int port) {
if (port < 0) {
port = 0;
}
this.remoteAddress = InetSocketAddress.createUnresolved(host, port);
return this;
}
/**
* get remote address.
*
* @return remote address
*/
@Override
public InetSocketAddress getRemoteAddress() {
return remoteAddress;
}
/**
* set remote address.
*
* @param address
* @return context
*/
@Override
public RpcServiceContext setRemoteAddress(InetSocketAddress address) {
this.remoteAddress = address;
return this;
}
@Override
public String getRemoteApplicationName() {
return remoteApplicationName;
}
@Override
public RpcServiceContext setRemoteApplicationName(String remoteApplicationName) {
this.remoteApplicationName = remoteApplicationName;
return this;
}
/**
* get remote address string.
*
* @return remote address string.
*/
@Override
public String getRemoteAddressString() {
return getRemoteHost() + ":" + getRemotePort();
}
/**
* get remote host name.
*
* @return remote host name
*/
@Override
public String getRemoteHostName() {
return remoteAddress == null ? null : remoteAddress.getHostName();
}
/**
* get local host.
*
* @return local host
*/
@Override
public String getLocalHost() {
String host = localAddress == null
? null
: localAddress.getAddress() == null
? localAddress.getHostName()
: NetUtils.filterLocalHost(localAddress.getAddress().getHostAddress());
if (host == null || host.length() == 0) {
return NetUtils.getLocalHost();
}
return host;
}
/**
* get local port.
*
* @return port
*/
@Override
public int getLocalPort() {
return localAddress == null ? 0 : localAddress.getPort();
}
/**
* get remote host.
*
* @return remote host
*/
@Override
public String getRemoteHost() {
return remoteAddress == null
? null
: remoteAddress.getAddress() == null
? remoteAddress.getHostName()
: NetUtils.filterLocalHost(remoteAddress.getAddress().getHostAddress());
}
/**
* get remote port.
*
* @return remote port
*/
@Override
public int getRemotePort() {
return remoteAddress == null ? 0 : remoteAddress.getPort();
}
/**
* @deprecated Replace to isProviderSide()
*/
@Override
@Deprecated
public boolean isServerSide() {
return isProviderSide();
}
/**
* @deprecated Replace to isConsumerSide()
*/
@Override
@Deprecated
public boolean isClientSide() {
return isConsumerSide();
}
/**
* @deprecated Replace to getUrls()
*/
@Override
@Deprecated
@SuppressWarnings({"unchecked", "rawtypes"})
public List<Invoker<?>> getInvokers() {
return invokers == null && invoker != null ? (List) Arrays.asList(invoker) : invokers;
}
@Override
public RpcServiceContext setInvokers(List<Invoker<?>> invokers) {
this.invokers = invokers;
if (CollectionUtils.isNotEmpty(invokers)) {
List<URL> urls = new ArrayList<>(invokers.size());
for (Invoker<?> invoker : invokers) {
urls.add(invoker.getUrl());
}
setUrls(urls);
}
return this;
}
/**
* @deprecated Replace to getUrl()
*/
@Override
@Deprecated
public Invoker<?> getInvoker() {
return invoker;
}
@Override
public RpcServiceContext setInvoker(Invoker<?> invoker) {
this.invoker = invoker;
if (invoker != null) {
setUrl(invoker.getUrl());
}
return this;
}
/**
* @deprecated Replace to getMethodName(), getParameterTypes(), getArguments()
*/
@Override
@Deprecated
public Invocation getInvocation() {
return invocation;
}
@Override
public RpcServiceContext setInvocation(Invocation invocation) {
this.invocation = invocation;
if (invocation != null) {
setMethodName(invocation.getMethodName());
setParameterTypes(invocation.getParameterTypes());
setArguments(invocation.getArguments());
}
return this;
}
/**
* Async invocation. Timeout will be handled even if <code>Future.get()</code> is not called.
*
* @param callable
* @return get the return result from <code>future.get()</code>
*/
@Override
@SuppressWarnings("unchecked")
public <T> CompletableFuture<T> asyncCall(Callable<T> callable) {
try {
try {
setAttachment(ASYNC_KEY, Boolean.TRUE.toString());
final T o = callable.call();
// local invoke will return directly
if (o != null) {
if (o instanceof CompletableFuture) {
return (CompletableFuture<T>) o;
}
return CompletableFuture.completedFuture(o);
} else {
// The service has a normal sync method signature, should get future from RpcContext.
}
} catch (Exception e) {
throw new RpcException(e);
} finally {
removeAttachment(ASYNC_KEY);
}
} catch (final RpcException e) {
CompletableFuture<T> exceptionFuture = new CompletableFuture<>();
exceptionFuture.completeExceptionally(e);
return exceptionFuture;
}
return ((CompletableFuture<T>) getServiceContext().getFuture());
}
/**
* one way async call, send request only, and result is not required
*
* @param runnable
*/
@Override
public void asyncCall(Runnable runnable) {
try {
setAttachment(RETURN_KEY, Boolean.FALSE.toString());
runnable.run();
} catch (Throwable e) {
// FIXME should put exception in future?
throw new RpcException("oneway call error ." + e.getMessage(), e);
} finally {
removeAttachment(RETURN_KEY);
}
}
@Override
public String getGroup() {
if (consumerUrl == null) {
return null;
}
return consumerUrl.getGroup();
}
@Override
public String getVersion() {
if (consumerUrl == null) {
return null;
}
return consumerUrl.getVersion();
}
@Override
public String getInterfaceName() {
if (consumerUrl == null) {
return null;
}
return consumerUrl.getServiceInterface();
}
@Override
public String getProtocol() {
if (consumerUrl == null) {
return null;
}
return consumerUrl.getProtocol();
}
@Override
public String getServiceKey() {
if (consumerUrl == null) {
return null;
}
return consumerUrl.getServiceKey();
}
@Override
public String getProtocolServiceKey() {
if (consumerUrl == null) {
return null;
}
return consumerUrl.getProtocolServiceKey();
}
@Override
public URL getConsumerUrl() {
return consumerUrl;
}
@Override
public void setConsumerUrl(URL consumerUrl) {
this.consumerUrl = consumerUrl;
}
public boolean isNeedPrintRouterSnapshot() {
return needPrintRouterSnapshot;
}
public void setNeedPrintRouterSnapshot(boolean needPrintRouterSnapshot) {
this.needPrintRouterSnapshot = needPrintRouterSnapshot;
}
public RpcServiceContext setLocalInvoke(Boolean localInvoke) {
this.localInvoke = localInvoke;
return this;
}
public Boolean getLocalInvoke() {
return this.localInvoke;
}
/**
* Only part of the properties are copied, the others are either not used currently or can be got from invocation.
* Also see {@link RpcContextAttachment#copyOf(boolean)}
*
* @param needCopy
* @return a shallow copy of RpcServiceContext
*/
public RpcServiceContext copyOf(boolean needCopy) {
if (needCopy) {
RpcServiceContext copy = new RpcServiceContext();
copy.arguments = this.arguments;
copy.consumerUrl = this.consumerUrl;
copy.invocation = this.invocation;
copy.invokers = this.invokers;
copy.invoker = this.invoker;
copy.localAddress = this.localAddress;
copy.methodName = this.methodName;
copy.needPrintRouterSnapshot = this.needPrintRouterSnapshot;
copy.parameterTypes = this.parameterTypes;
copy.remoteAddress = this.remoteAddress;
copy.remoteApplicationName = this.remoteApplicationName;
copy.request = this.request;
copy.response = this.response;
copy.url = this.url;
copy.urls = this.urls;
return copy;
} else {
return this;
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcInvocation.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcInvocation.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.ReflectUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.model.FrameworkModel;
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.ServiceModel;
import org.apache.dubbo.rpc.support.RpcUtils;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;
import java.util.stream.Stream;
import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_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_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY;
import static org.apache.dubbo.rpc.Constants.TOKEN_KEY;
/**
* RPC Invocation.
*
* @serial Don't change the class name and properties.
*/
public class RpcInvocation implements Invocation, Serializable {
private static final long serialVersionUID = -4355285085441097045L;
private String targetServiceUniqueName;
private String protocolServiceKey;
private ServiceModel serviceModel;
private String methodName;
private String interfaceName;
private transient Class<?>[] parameterTypes;
private String parameterTypesDesc;
private String[] compatibleParamSignatures;
private Object[] arguments;
/**
* Passed to the remote server during RPC call
*/
private Map<String, Object> attachments;
private final transient Lock attachmentLock = new ReentrantLock();
/**
* Only used on the caller side, will not appear on the wire.
*/
private transient Map<Object, Object> attributes = Collections.synchronizedMap(new HashMap<>());
private transient Invoker<?> invoker;
private transient Class<?> returnType;
private transient Type[] returnTypes;
private transient InvokeMode invokeMode;
private transient List<Invoker<?>> invokedInvokers = new LinkedList<>();
/**
* @deprecated only for test
*/
@Deprecated
public RpcInvocation() {}
/**
* Deep clone of an invocation
*
* @param invocation original invocation
*/
public RpcInvocation(Invocation invocation) {
this(invocation, null);
}
/**
* Deep clone of an invocation & put some service params into attachment from invoker (will not change the invoker in invocation)
*
* @param invocation original invocation
* @param invoker target invoker
*/
public RpcInvocation(Invocation invocation, Invoker<?> invoker) {
this(
invocation.getTargetServiceUniqueName(),
invocation.getServiceModel(),
invocation.getMethodName(),
invocation.getServiceName(),
invocation.getProtocolServiceKey(),
invocation.getParameterTypes(),
invocation.getArguments(),
invocation.copyObjectAttachments(),
invocation.getInvoker(),
invocation.getAttributes(),
invocation instanceof RpcInvocation ? ((RpcInvocation) invocation).getInvokeMode() : null);
if (invoker != null) {
URL url = invoker.getUrl();
setAttachment(PATH_KEY, url.getPath());
if (url.hasParameter(INTERFACE_KEY)) {
setAttachment(INTERFACE_KEY, url.getParameter(INTERFACE_KEY));
}
if (url.hasParameter(GROUP_KEY)) {
setAttachment(GROUP_KEY, url.getGroup());
}
if (url.hasParameter(VERSION_KEY)) {
setAttachment(VERSION_KEY, url.getVersion("0.0.0"));
}
if (url.hasParameter(TIMEOUT_KEY)) {
setAttachment(TIMEOUT_KEY, url.getParameter(TIMEOUT_KEY));
}
if (url.hasParameter(TOKEN_KEY)) {
setAttachment(TOKEN_KEY, url.getParameter(TOKEN_KEY));
}
if (url.hasParameter(APPLICATION_KEY)) {
setAttachment(APPLICATION_KEY, url.getApplication());
}
}
}
/**
* To create a brand-new invocation
*/
public RpcInvocation(
ServiceModel serviceModel,
String methodName,
String interfaceName,
String protocolServiceKey,
Class<?>[] parameterTypes,
Object[] arguments) {
this(
null,
serviceModel,
methodName,
interfaceName,
protocolServiceKey,
parameterTypes,
arguments,
null,
null,
null,
null);
}
/**
* @deprecated deprecated, will be removed in 3.1.x
*/
@Deprecated
public RpcInvocation(
ServiceModel serviceModel,
Method method,
String interfaceName,
String protocolServiceKey,
Object[] arguments) {
this(
null,
serviceModel,
method.getName(),
interfaceName,
protocolServiceKey,
method.getParameterTypes(),
arguments,
null,
null,
null,
null);
}
/**
* @deprecated deprecated, will be removed in 3.1.x
*/
@Deprecated
public RpcInvocation(Method method, String interfaceName, String protocolServiceKey, Object[] arguments) {
this(
null,
null,
method.getName(),
interfaceName,
protocolServiceKey,
method.getParameterTypes(),
arguments,
null,
null,
null,
null);
}
/**
* @deprecated deprecated, will be removed in 3.1.x
*/
@Deprecated
public RpcInvocation(
ServiceModel serviceModel,
Method method,
String interfaceName,
String protocolServiceKey,
Object[] arguments,
Map<String, Object> attachment,
Map<Object, Object> attributes) {
this(
null,
serviceModel,
method.getName(),
interfaceName,
protocolServiceKey,
method.getParameterTypes(),
arguments,
attachment,
null,
attributes,
null);
}
/**
* @deprecated deprecated, will be removed in 3.1.x
*/
@Deprecated
public RpcInvocation(
Method method,
String interfaceName,
String protocolServiceKey,
Object[] arguments,
Map<String, Object> attachment,
Map<Object, Object> attributes) {
this(
null,
null,
method.getName(),
interfaceName,
protocolServiceKey,
method.getParameterTypes(),
arguments,
attachment,
null,
attributes,
null);
}
/**
* @deprecated deprecated, will be removed in 3.1.x
*/
@Deprecated
public RpcInvocation(
String methodName,
String interfaceName,
String protocolServiceKey,
Class<?>[] parameterTypes,
Object[] arguments) {
this(
null,
null,
methodName,
interfaceName,
protocolServiceKey,
parameterTypes,
arguments,
null,
null,
null,
null);
}
/**
* @deprecated deprecated, will be removed in 3.1.x
*/
@Deprecated
public RpcInvocation(
ServiceModel serviceModel,
String methodName,
String interfaceName,
String protocolServiceKey,
Class<?>[] parameterTypes,
Object[] arguments,
Map<String, Object> attachments) {
this(
null,
serviceModel,
methodName,
interfaceName,
protocolServiceKey,
parameterTypes,
arguments,
attachments,
null,
null,
null);
}
/**
* @deprecated deprecated, will be removed in 3.1.x
*/
@Deprecated
public RpcInvocation(
String methodName,
String interfaceName,
String protocolServiceKey,
Class<?>[] parameterTypes,
Object[] arguments,
Map<String, Object> attachments) {
this(
null,
null,
methodName,
interfaceName,
protocolServiceKey,
parameterTypes,
arguments,
attachments,
null,
null,
null);
}
/**
* @deprecated deprecated, will be removed in 3.1.x
*/
@Deprecated
public RpcInvocation(
String methodName,
String interfaceName,
String protocolServiceKey,
Class<?>[] parameterTypes,
Object[] arguments,
Map<String, Object> attachments,
Invoker<?> invoker,
Map<Object, Object> attributes) {
this(
null,
null,
methodName,
interfaceName,
protocolServiceKey,
parameterTypes,
arguments,
attachments,
invoker,
attributes,
null);
}
/**
* @deprecated deprecated, will be removed in 3.1.x
*/
@Deprecated
public RpcInvocation(
ServiceModel serviceModel,
String methodName,
String interfaceName,
String protocolServiceKey,
Class<?>[] parameterTypes,
Object[] arguments,
Map<String, Object> attachments,
Invoker<?> invoker,
Map<Object, Object> attributes) {
this(
null,
serviceModel,
methodName,
interfaceName,
protocolServiceKey,
parameterTypes,
arguments,
attachments,
invoker,
attributes,
null);
}
/**
* @deprecated deprecated, will be removed in 3.1.x
*/
@Deprecated
public RpcInvocation(
ServiceModel serviceModel,
String methodName,
String interfaceName,
String protocolServiceKey,
Class<?>[] parameterTypes,
Object[] arguments,
Map<String, Object> attachments,
Invoker<?> invoker,
Map<Object, Object> attributes,
InvokeMode invokeMode) {
this(
null,
serviceModel,
methodName,
interfaceName,
protocolServiceKey,
parameterTypes,
arguments,
attachments,
invoker,
attributes,
invokeMode);
}
/**
* To create a brand-new invocation
*/
public RpcInvocation(
String targetServiceUniqueName,
ServiceModel serviceModel,
String methodName,
String interfaceName,
String protocolServiceKey,
Class<?>[] parameterTypes,
Object[] arguments,
Map<String, Object> attachments,
Invoker<?> invoker,
Map<Object, Object> attributes,
InvokeMode invokeMode) {
this.targetServiceUniqueName = targetServiceUniqueName;
this.serviceModel = serviceModel;
this.methodName = methodName;
this.interfaceName = interfaceName;
this.protocolServiceKey = protocolServiceKey;
this.parameterTypes = parameterTypes == null ? new Class<?>[0] : parameterTypes;
this.arguments = arguments == null ? new Object[0] : arguments;
this.attachments = attachments == null ? new HashMap<>() : attachments;
this.attributes = attributes == null ? Collections.synchronizedMap(new HashMap<>()) : attributes;
this.invoker = invoker;
initParameterDesc();
this.invokeMode = invokeMode;
}
private void initParameterDesc() {
AtomicReference<ServiceDescriptor> serviceDescriptor = new AtomicReference<>();
if (serviceModel != null) {
serviceDescriptor.set(serviceModel.getServiceModel());
} else if (StringUtils.isNotEmpty(interfaceName)) {
// TODO: Multi Instance compatible mode
FrameworkModel.defaultModel().getServiceRepository().allProviderModels().stream()
.map(ProviderModel::getServiceModel)
.filter(s -> interfaceName.equals(s.getInterfaceName()))
.findFirst()
.ifPresent(serviceDescriptor::set);
}
if (serviceDescriptor.get() != null) {
MethodDescriptor methodDescriptor = serviceDescriptor.get().getMethod(methodName, parameterTypes);
if (methodDescriptor != null) {
this.parameterTypesDesc = methodDescriptor.getParamDesc();
this.compatibleParamSignatures = methodDescriptor.getCompatibleParamSignatures();
this.returnTypes = methodDescriptor.getReturnTypes();
this.returnType = methodDescriptor.getReturnClass();
}
}
if (parameterTypesDesc == null) {
this.parameterTypesDesc = ReflectUtils.getDesc(this.getParameterTypes());
this.compatibleParamSignatures =
Stream.of(this.parameterTypes).map(Class::getName).toArray(String[]::new);
this.returnTypes = RpcUtils.getReturnTypes(this);
this.returnType = RpcUtils.getReturnType(this);
}
}
@Override
public Invoker<?> getInvoker() {
return invoker;
}
public void setInvoker(Invoker<?> invoker) {
this.invoker = invoker;
}
public Object remove(Object key) {
return attributes.remove(key);
}
@Override
public Object put(Object key, Object value) {
return attributes.put(key, value);
}
@Override
public Object get(Object key) {
return attributes.get(key);
}
@Override
public Map<Object, Object> getAttributes() {
return attributes;
}
@Override
public void addInvokedInvoker(Invoker<?> invoker) {
this.invokedInvokers.add(invoker);
}
@Override
public List<Invoker<?>> getInvokedInvokers() {
return this.invokedInvokers;
}
@Override
public String getTargetServiceUniqueName() {
return targetServiceUniqueName;
}
public void setTargetServiceUniqueName(String targetServiceUniqueName) {
this.targetServiceUniqueName = targetServiceUniqueName;
}
@Override
public String getProtocolServiceKey() {
return protocolServiceKey;
}
@Override
public String getMethodName() {
return methodName;
}
public void setMethodName(String methodName) {
this.methodName = methodName;
}
@Override
public String getServiceName() {
return interfaceName;
}
public void setServiceName(String interfaceName) {
this.interfaceName = interfaceName;
}
@Override
public Class<?>[] getParameterTypes() {
return parameterTypes;
}
public void setParameterTypes(Class<?>[] parameterTypes) {
this.parameterTypes = parameterTypes == null ? new Class<?>[0] : parameterTypes;
}
public String getParameterTypesDesc() {
return parameterTypesDesc;
}
public void setParameterTypesDesc(String parameterTypesDesc) {
this.parameterTypesDesc = parameterTypesDesc;
}
@Override
public String[] getCompatibleParamSignatures() {
return compatibleParamSignatures;
}
// parameter signatures can be set independently, it is useful when the service type is not found on caller side and
// the invocation is not generic invocation either.
public void setCompatibleParamSignatures(String[] compatibleParamSignatures) {
this.compatibleParamSignatures = compatibleParamSignatures;
}
@Override
public Object[] getArguments() {
return arguments;
}
public void setArguments(Object[] arguments) {
this.arguments = arguments == null ? new Object[0] : arguments;
}
@Override
public Map<String, Object> getObjectAttachments() {
try {
attachmentLock.lock();
if (attachments == null) {
attachments = new HashMap<>();
}
return attachments;
} finally {
attachmentLock.unlock();
}
}
@Override
public Map<String, Object> copyObjectAttachments() {
try {
attachmentLock.lock();
if (attachments == null) {
return new HashMap<>();
}
return new HashMap<>(attachments);
} finally {
attachmentLock.unlock();
}
}
@Override
public void foreachAttachment(Consumer<Map.Entry<String, Object>> consumer) {
try {
attachmentLock.lock();
if (attachments != null) {
attachments.entrySet().forEach(consumer);
}
} finally {
attachmentLock.unlock();
}
}
public void setObjectAttachments(Map<String, Object> attachments) {
try {
attachmentLock.lock();
this.attachments = attachments == null ? new HashMap<>() : attachments;
} finally {
attachmentLock.unlock();
}
}
@Override
public void setAttachment(String key, String value) {
setObjectAttachment(key, value);
}
@Deprecated
@Override
public Map<String, String> getAttachments() {
try {
attachmentLock.lock();
if (attachments == null) {
attachments = new HashMap<>();
}
return new AttachmentsAdapter.ObjectToStringMap(attachments);
} finally {
attachmentLock.unlock();
}
}
@Deprecated
public void setAttachments(Map<String, String> attachments) {
try {
attachmentLock.lock();
this.attachments = attachments == null ? new HashMap<>() : new HashMap<>(attachments);
} finally {
attachmentLock.unlock();
}
}
@Override
public void setAttachment(String key, Object value) {
setObjectAttachment(key, value);
}
@Override
public void setObjectAttachment(String key, Object value) {
try {
attachmentLock.lock();
if (attachments == null) {
attachments = new HashMap<>();
}
attachments.put(key, value);
} finally {
attachmentLock.unlock();
}
}
@Override
public void setAttachmentIfAbsent(String key, String value) {
setObjectAttachmentIfAbsent(key, value);
}
@Override
public void setAttachmentIfAbsent(String key, Object value) {
setObjectAttachmentIfAbsent(key, value);
}
@Override
public void setObjectAttachmentIfAbsent(String key, Object value) {
try {
attachmentLock.lock();
if (attachments == null) {
attachments = new HashMap<>();
}
if (!attachments.containsKey(key)) {
attachments.put(key, value);
}
} finally {
attachmentLock.unlock();
}
}
@Deprecated
public void addAttachments(Map<String, String> attachments) {
try {
attachmentLock.lock();
if (attachments == null) {
return;
}
if (this.attachments == null) {
this.attachments = new HashMap<>();
}
this.attachments.putAll(attachments);
} finally {
attachmentLock.unlock();
}
}
public void addObjectAttachments(Map<String, Object> attachments) {
try {
attachmentLock.lock();
if (attachments == null) {
return;
}
if (this.attachments == null) {
this.attachments = new HashMap<>();
}
this.attachments.putAll(attachments);
} finally {
attachmentLock.unlock();
}
}
@Deprecated
public void addAttachmentsIfAbsent(Map<String, String> attachments) {
if (attachments == null) {
return;
}
for (Map.Entry<String, String> entry : attachments.entrySet()) {
setAttachmentIfAbsent(entry.getKey(), entry.getValue());
}
}
public void addObjectAttachmentsIfAbsent(Map<String, Object> attachments) {
if (attachments == null) {
return;
}
for (Map.Entry<String, Object> entry : attachments.entrySet()) {
setAttachmentIfAbsent(entry.getKey(), entry.getValue());
}
}
@Override
@Deprecated
public String getAttachment(String key) {
try {
attachmentLock.lock();
if (attachments == null) {
return null;
}
Object value = attachments.get(key);
if (value instanceof String) {
return (String) value;
}
return null;
} finally {
attachmentLock.unlock();
}
}
@Override
public Object getObjectAttachment(String key) {
try {
attachmentLock.lock();
if (attachments == null) {
return null;
}
final Object val = attachments.get(key);
if (val != null) {
return val;
}
return attachments.get(key.toLowerCase(Locale.ROOT));
} finally {
attachmentLock.unlock();
}
}
@Override
@Deprecated
public String getAttachment(String key, String defaultValue) {
try {
attachmentLock.lock();
if (attachments == null) {
return defaultValue;
}
Object value = attachments.get(key);
if (value instanceof String) {
String strValue = (String) value;
if (StringUtils.isEmpty(strValue)) {
return defaultValue;
} else {
return strValue;
}
}
return defaultValue;
} finally {
attachmentLock.unlock();
}
}
@Deprecated
@Override
public Object getObjectAttachment(String key, Object defaultValue) {
try {
attachmentLock.lock();
if (attachments == null) {
return defaultValue;
}
Object value = attachments.get(key);
if (value == null) {
return defaultValue;
}
return value;
} finally {
attachmentLock.unlock();
}
}
@Override
public Object getObjectAttachmentWithoutConvert(String key) {
try {
attachmentLock.lock();
if (attachments == null) {
return null;
}
return attachments.get(key);
} finally {
attachmentLock.unlock();
}
}
public Class<?> getReturnType() {
return returnType;
}
public void setReturnType(Class<?> returnType) {
this.returnType = returnType;
}
public Type[] getReturnTypes() {
return returnTypes;
}
public void setReturnTypes(Type[] returnTypes) {
this.returnTypes = returnTypes;
}
public InvokeMode getInvokeMode() {
return invokeMode;
}
public void setInvokeMode(InvokeMode invokeMode) {
this.invokeMode = invokeMode;
}
@Override
public void setServiceModel(ServiceModel serviceModel) {
this.serviceModel = serviceModel;
}
@Override
public ServiceModel getServiceModel() {
return serviceModel;
}
@Override
public String toString() {
return "RpcInvocation [methodName=" + methodName + ", parameterTypes=" + Arrays.toString(parameterTypes) + "]";
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcServerContextAttachment.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcServerContextAttachment.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class RpcServerContextAttachment extends RpcContextAttachment {
@Override
public RpcContextAttachment copyOf(boolean needCopy) {
throw new RuntimeException("copyOf internal method, should not be invoke");
}
@Override
protected boolean isValid() {
throw new RuntimeException("isValid of is internal method, should not be invoke");
}
@Override
public RpcContextAttachment setObjectAttachment(String key, Object value) {
RpcContext.getServerResponseContext().setObjectAttachment(key, value);
return this;
}
@Override
protected void setAsyncContext(AsyncContext asyncContext) {
RpcContext.getServerResponseContext().setAsyncContext(asyncContext);
}
@Override
public boolean isAsyncStarted() {
return RpcContext.getServerResponseContext().isAsyncStarted();
}
@Override
public boolean stopAsync() {
return RpcContext.getServerResponseContext().stopAsync();
}
@Override
public AsyncContext getAsyncContext() {
return RpcContext.getServerResponseContext().getAsyncContext();
}
@Override
public String getAttachment(String key) {
Object attachment = getObjectAttachment(key);
if (attachment instanceof String) {
return (String) attachment;
}
return null;
}
@Override
public Object getObjectAttachment(String key) {
Object fromServerResponse = RpcContext.getServerResponseContext().getObjectAttachment(key);
if (fromServerResponse == null) {
fromServerResponse = RpcContext.getClientResponseContext().getObjectAttachment(key);
}
return fromServerResponse;
}
@Override
public RpcContextAttachment setAttachment(String key, String value) {
return RpcContext.getServerResponseContext().setAttachment(key, value);
}
@Override
public RpcContextAttachment setAttachment(String key, Object value) {
return RpcContext.getServerResponseContext().setAttachment(key, value);
}
@Override
public RpcContextAttachment removeAttachment(String key) {
RpcContext.getServerResponseContext().removeAttachment(key);
RpcContext.getClientResponseContext().removeAttachment(key);
return this;
}
@Override
public Map<String, String> getAttachments() {
return new AttachmentsAdapter.ObjectToStringMap(new ObjectAttachmentMap(this));
}
@Override
public Map<String, Object> getObjectAttachments() {
return new ObjectAttachmentMap(this);
}
@Override
public RpcContextAttachment setAttachments(Map<String, String> attachment) {
RpcContext.getServerResponseContext().setAttachments(attachment);
RpcContext.getClientResponseContext().clearAttachments();
return this;
}
@Override
public RpcContextAttachment setObjectAttachments(Map<String, Object> attachment) {
RpcContext.getServerResponseContext().setObjectAttachments(attachment);
RpcContext.getClientResponseContext().clearAttachments();
return this;
}
@Override
public void clearAttachments() {
RpcContext.getServerResponseContext().clearAttachments();
RpcContext.getClientResponseContext().clearAttachments();
}
@Override
public Map<String, Object> get() {
return getObjectAttachments();
}
@Override
public RpcContextAttachment set(String key, Object value) {
return setAttachment(key, value);
}
@Override
public RpcContextAttachment remove(String key) {
return removeAttachment(key);
}
@Override
public Object get(String key) {
return getAttachment(key);
}
static class ObjectAttachmentMap implements Map<String, Object> {
private final RpcServerContextAttachment adapter;
public ObjectAttachmentMap(RpcServerContextAttachment adapter) {
this.adapter = adapter;
}
private Map<String, Object> getAttachments() {
Map<String, Object> clientResponse =
RpcContext.getClientResponseContext().getObjectAttachments();
Map<String, Object> serverResponse =
RpcContext.getServerResponseContext().getObjectAttachments();
Map<String, Object> result =
new HashMap<>((int) (clientResponse.size() + serverResponse.size() / 0.75) + 1);
result.putAll(clientResponse);
result.putAll(serverResponse);
return result;
}
@Override
public int size() {
return getAttachments().size();
}
@Override
public boolean isEmpty() {
return RpcContext.getClientResponseContext().getObjectAttachments().isEmpty()
&& RpcContext.getServerResponseContext()
.getObjectAttachments()
.isEmpty();
}
@Override
public boolean containsKey(Object key) {
return RpcContext.getClientResponseContext().getObjectAttachments().containsKey(key)
|| RpcContext.getServerResponseContext()
.getObjectAttachments()
.containsKey(key);
}
@Override
public boolean containsValue(Object value) {
return RpcContext.getClientResponseContext().getObjectAttachments().containsValue(value)
|| RpcContext.getServerResponseContext()
.getObjectAttachments()
.containsValue(value);
}
@Override
public Object get(Object key) {
if (key instanceof String) {
return adapter.getObjectAttachment((String) key);
} else {
return null;
}
}
@Override
public Object put(String key, Object value) {
return adapter.setObjectAttachment(key, value);
}
@Override
public Object remove(Object key) {
if (key instanceof String) {
return adapter.removeAttachment((String) key);
} else {
return null;
}
}
@Override
public void putAll(Map<? extends String, ?> m) {
for (Entry<? extends String, ?> entry : m.entrySet()) {
adapter.setObjectAttachment(entry.getKey(), entry.getValue());
}
}
@Override
public void clear() {
adapter.clearAttachments();
}
@Override
public Set<String> keySet() {
return getAttachments().keySet();
}
@Override
public Collection<Object> values() {
return getAttachments().values();
}
@Override
public Set<Entry<String, Object>> entrySet() {
return getAttachments().entrySet();
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ExecutableListener.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ExecutableListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import java.util.concurrent.Executor;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_FAILED_NOTIFY_EVENT;
public class ExecutableListener implements Runnable {
private static final ErrorTypeAwareLogger log = LoggerFactory.getErrorTypeAwareLogger(ExecutableListener.class);
private final Executor executor;
private final CancellationListener listener;
private final RpcServiceContext context;
public ExecutableListener(Executor executor, CancellationListener listener, RpcServiceContext context) {
this.executor = executor;
this.listener = listener;
this.context = context;
}
public ExecutableListener(Executor executor, CancellationListener listener) {
this(executor, listener, null);
}
public void deliver() {
try {
executor.execute(this);
} catch (Throwable t) {
log.warn(COMMON_FAILED_NOTIFY_EVENT, "", "", "Exception notifying context listener", t);
}
}
public Executor getExecutor() {
return executor;
}
public CancellationListener getListener() {
return listener;
}
public RpcServiceContext getContext() {
return context;
}
@Override
public void run() {
listener.cancelled(context);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ProxyFactory.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ProxyFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Adaptive;
import org.apache.dubbo.common.extension.SPI;
import static org.apache.dubbo.common.extension.ExtensionScope.FRAMEWORK;
import static org.apache.dubbo.rpc.Constants.PROXY_KEY;
/**
* ProxyFactory. (API/SPI, Singleton, ThreadSafe)
*/
@SPI(value = "javassist", scope = FRAMEWORK)
public interface ProxyFactory {
/**
* create proxy.
*
* @param invoker
* @return proxy
*/
@Adaptive({PROXY_KEY})
<T> T getProxy(Invoker<T> invoker) throws RpcException;
/**
* create proxy.
*
* @param invoker
* @return proxy
*/
@Adaptive({PROXY_KEY})
<T> T getProxy(Invoker<T> invoker, boolean generic) throws RpcException;
/**
* create invoker.
*
* @param <T>
* @param proxy
* @param type
* @param url
* @return invoker
*/
@Adaptive({PROXY_KEY})
<T> Invoker<T> getInvoker(T proxy, Class<T> type, URL url) throws RpcException;
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AsyncContextImpl.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AsyncContextImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicBoolean;
public class AsyncContextImpl implements AsyncContext {
private final AtomicBoolean started = new AtomicBoolean(false);
private final AtomicBoolean stopped = new AtomicBoolean(false);
private CompletableFuture<Object> future;
private final RpcContext.RestoreContext restoreContext;
private final ClassLoader restoreClassLoader;
private ClassLoader stagedClassLoader;
public AsyncContextImpl() {
restoreContext = RpcContext.storeContext();
restoreClassLoader = Thread.currentThread().getContextClassLoader();
}
@Override
public void write(Object value) {
if (isAsyncStarted() && stop()) {
if (value instanceof Throwable) {
Throwable bizExe = (Throwable) value;
future.completeExceptionally(bizExe);
} else {
future.complete(value);
}
} else {
throw new IllegalStateException(
"The async response has probably been wrote back by another thread, or the asyncContext has been closed.");
}
}
@Override
public boolean isAsyncStarted() {
return started.get();
}
@Override
public boolean stop() {
return stopped.compareAndSet(false, true);
}
@Override
public void start() {
if (this.started.compareAndSet(false, true)) {
this.future = new CompletableFuture<>();
}
}
@Override
public void signalContextSwitch() {
RpcContext.restoreContext(restoreContext);
if (restoreClassLoader != null) {
stagedClassLoader = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(restoreClassLoader);
}
}
@Override
public void resetContext() {
RpcContext.removeContext();
if (stagedClassLoader != null) {
Thread.currentThread().setContextClassLoader(restoreClassLoader);
}
}
public CompletableFuture<Object> getInternalFuture() {
return future;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/CancellationListener.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/CancellationListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc;
/**
* A listener notified on context cancellation.
*/
public interface CancellationListener {
/**
* Notifies that a context was cancelled.
*
* @param context the newly cancelled context.
*/
void cancelled(RpcServiceContext context);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Constants.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Constants.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc;
public interface Constants {
String LOCAL_KEY = "local";
String STUB_KEY = "stub";
String MOCK_KEY = "mock";
String DEPRECATED_KEY = "deprecated";
String $ECHO = "$echo";
String $ECHO_PARAMETER_DESC = "Ljava/lang/Object;";
String RETURN_PREFIX = "return ";
String THROW_PREFIX = "throw";
String FAIL_PREFIX = "fail:";
String FORCE_PREFIX = "force:";
String MERGER_KEY = "merger";
String IS_SERVER_KEY = "isserver";
String FORCE_USE_TAG = "dubbo.force.tag";
String TPS_LIMIT_RATE_KEY = "tps";
String TPS_LIMIT_INTERVAL_KEY = "tps.interval";
long DEFAULT_TPS_LIMIT_INTERVAL = 60 * 1000;
String AUTO_ATTACH_INVOCATIONID_KEY = "invocationid.autoattach";
boolean DEFAULT_STUB_EVENT = false;
String STUB_EVENT_METHODS_KEY = "dubbo.stub.event.methods";
String COMPRESSOR_KEY = "dubbo.rpc.tri.compressor";
String PROXY_KEY = "proxy";
String EXECUTES_KEY = "executes";
String ACCESS_LOG_KEY = "accesslog";
String ACCESS_LOG_FIXED_PATH_KEY = "accesslog.fixed.path";
String ACTIVES_KEY = "actives";
String ID_KEY = "id";
String ASYNC_KEY = "async";
String RETURN_KEY = "return";
String TOKEN_KEY = "token";
String AUTH_KEY = "auth";
String AUTHENTICATOR_KEY = "authenticator";
String INTERFACE = "interface";
String INTERFACES = "interfaces";
String GENERIC_KEY = "generic";
String LOCAL_PROTOCOL = "injvm";
String DEFAULT_REMOTING_SERVER = "netty";
String SCOPE_KEY = "scope";
String SCOPE_LOCAL = "local";
String SCOPE_REMOTE = "remote";
String INPUT_KEY = "input";
String OUTPUT_KEY = "output";
String CONSUMER_MODEL = "consumerModel";
String METHOD_MODEL = "methodModel";
String INVOCATION_KEY = "invocation";
String SERIALIZATION_ID_KEY = "serialization_id";
String HTTP3_KEY = "http3";
String H2_SETTINGS_SUPPORT_NO_LOWER_HEADER_KEY = "dubbo.rpc.tri.support-no-lower-header";
String H2_SETTINGS_IGNORE_1_0_0_KEY = "dubbo.rpc.tri.ignore-1.0.0-version";
String H2_SETTINGS_RESOLVE_FALLBACK_TO_DEFAULT_KEY = "dubbo.rpc.tri.resolve-fallback-to-default";
String H2_SETTINGS_BUILTIN_SERVICE_INIT = "dubbo.tri.builtin.service.init";
String H2_SETTINGS_JSON_FRAMEWORK_NAME = "dubbo.protocol.triple.rest.json-framework";
String H2_SETTINGS_MAX_MESSAGE_SIZE = "dubbo.protocol.triple.max-message-size";
String H2_SETTINGS_DISALLOWED_CONTENT_TYPES = "dubbo.protocol.triple.rest.disallowed-content-types";
String H2_SETTINGS_OPENAPI_PREFIX = "dubbo.protocol.triple.rest.openapi";
String H2_SETTINGS_VERBOSE_ENABLED = "dubbo.protocol.triple.verbose";
String H2_SETTINGS_REST_ENABLED = "dubbo.protocol.triple.rest.enabled";
String H2_SETTINGS_OPENAPI_ENABLED = "dubbo.protocol.triple.rest.openapi.enabled";
String H2_SETTINGS_SERVLET_ENABLED = "dubbo.protocol.triple.servlet.enabled";
String H3_SETTINGS_HTTP3_ENABLED = "dubbo.protocol.triple.http3.enabled";
String H3_SETTINGS_HTTP3_NEGOTIATION = "dubbo.protocol.triple.http3.negotiation";
String ADAPTIVE_LOADBALANCE_ATTACHMENT_KEY = "lb_adaptive";
String ADAPTIVE_LOADBALANCE_START_TIME = "adaptive_startTime";
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ExporterListener.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ExporterListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
/**
* ExporterListener. (SPI, Singleton, ThreadSafe)
*/
@SPI(scope = ExtensionScope.FRAMEWORK)
public interface ExporterListener {
/**
* The exporter exported.
*
* @param exporter
* @throws RpcException
* @see org.apache.dubbo.rpc.Protocol#export(Invoker)
*/
void exported(Exporter<?> exporter) throws RpcException;
/**
* The exporter unexported.
*
* @param exporter
* @throws RpcException
* @see org.apache.dubbo.rpc.Exporter#unexport()
*/
void unexported(Exporter<?> exporter);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/TrieTree.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/TrieTree.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.support;
import java.util.Set;
class TrieNode {
TrieNode[] children;
boolean isEndOfWord = false;
// Constructor: Initializes children array
public TrieNode() {
this.children = new TrieNode[29]; // 0-25: 'a' - 'z', 26: '-', 27: '_', 28: '.'
}
}
public class TrieTree {
private final TrieNode root;
// Constructor: Initializes the Trie and inserts all words from the given set
public TrieTree(Set<String> words) {
root = new TrieNode();
for (String word : words) {
insert(word);
}
}
// Inserts a word into the Trie, case-insensitive
private void insert(String word) {
TrieNode node = root;
for (char ch : word.toCharArray()) {
int index = getCharIndex(ch);
if (index == -1) {
return; // Invalid character, skip this word
}
if (node.children[index] == null) {
node.children[index] = new TrieNode();
}
node = node.children[index];
}
node.isEndOfWord = true;
}
// Checks if a word exists in the Trie, case-insensitive
public boolean search(String word) {
TrieNode node = root;
for (char ch : word.toCharArray()) {
int index = getCharIndex(ch);
if (index == -1 || node.children[index] == null) {
return false; // Invalid character or node doesn't exist
}
node = node.children[index];
}
return node.isEndOfWord;
}
// Maps the character to the array index, handling case-insensitivity
// 'a-z' -> 0-25, '-' -> 26, '_' -> 27, '.' -> 28
// Returns -1 if the character is invalid
private int getCharIndex(char ch) {
// Convert uppercase to lowercase within this function
if (ch >= 'A' && ch <= 'Z') {
ch = (char) (ch + 32); // Convert 'A'-'Z' to 'a'-'z'
}
if (ch >= 'a' && ch <= 'z') {
return ch - 'a'; // 'a' -> 0, 'b' -> 1, ..., 'z' -> 25
} else if (ch == '-') {
return 26;
} else if (ch == '_') {
return 27;
} else if (ch == '.') {
return 28;
} else {
return -1; // Invalid character
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/RpcUtils.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/RpcUtils.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.ReflectUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.InvokeMode;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.TimeoutCountDown;
import org.apache.dubbo.rpc.service.GenericService;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import static org.apache.dubbo.common.constants.CommonConstants.$INVOKE;
import static org.apache.dubbo.common.constants.CommonConstants.$INVOKE_ASYNC;
import static org.apache.dubbo.common.constants.CommonConstants.ENABLE_TIMEOUT_COUNTDOWN_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_PARAMETER_DESC;
import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_ATTACHMENT_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_ATTACHMENT_KEY_LOWER;
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.common.constants.LoggerCodeConstants.COMMON_REFLECTIVE_OPERATION_FAILED;
import static org.apache.dubbo.rpc.Constants.$ECHO;
import static org.apache.dubbo.rpc.Constants.$ECHO_PARAMETER_DESC;
import static org.apache.dubbo.rpc.Constants.ASYNC_KEY;
import static org.apache.dubbo.rpc.Constants.AUTO_ATTACH_INVOCATIONID_KEY;
import static org.apache.dubbo.rpc.Constants.ID_KEY;
import static org.apache.dubbo.rpc.Constants.RETURN_KEY;
public class RpcUtils {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(RpcUtils.class);
private static final AtomicLong INVOKE_ID = new AtomicLong(0);
public static Class<?> getReturnType(Invocation invocation) {
try {
if (invocation != null
&& invocation.getInvoker() != null
&& invocation.getInvoker().getUrl() != null
&& invocation.getInvoker().getInterface() != GenericService.class
&& !invocation.getMethodName().startsWith("$")) {
String service = invocation.getInvoker().getUrl().getServiceInterface();
if (StringUtils.isNotEmpty(service)) {
Method method = getMethodByService(invocation, service);
return method == null ? null : method.getReturnType();
}
}
} catch (Throwable t) {
logger.warn(COMMON_REFLECTIVE_OPERATION_FAILED, "", "", t.getMessage(), t);
}
return null;
}
public static Type[] getReturnTypes(Invocation invocation) {
try {
if (invocation != null
&& invocation.getInvoker() != null
&& invocation.getInvoker().getUrl() != null
&& invocation.getInvoker().getInterface() != GenericService.class
&& !invocation.getMethodName().startsWith("$")) {
Type[] returnTypes = null;
if (invocation instanceof RpcInvocation) {
returnTypes = ((RpcInvocation) invocation).getReturnTypes();
if (returnTypes != null) {
return returnTypes;
}
}
String service = invocation.getInvoker().getUrl().getServiceInterface();
if (StringUtils.isNotEmpty(service)) {
Method method = getMethodByService(invocation, service);
if (method != null) {
returnTypes = ReflectUtils.getReturnTypes(method);
}
}
if (returnTypes != null) {
return returnTypes;
}
}
} catch (Throwable t) {
logger.warn(COMMON_REFLECTIVE_OPERATION_FAILED, "", "", t.getMessage(), t);
}
return null;
}
public static Long getInvocationId(Invocation inv) {
String id = inv.getAttachment(ID_KEY);
return id == null ? null : new Long(id);
}
/**
* Idempotent operation: invocation id will be added in async operation by default
*
* @param url
* @param inv
*/
public static void attachInvocationIdIfAsync(URL url, Invocation inv) {
if (isAttachInvocationId(url, inv) && getInvocationId(inv) == null && inv instanceof RpcInvocation) {
inv.setAttachment(ID_KEY, String.valueOf(INVOKE_ID.getAndIncrement()));
}
}
private static boolean isAttachInvocationId(URL url, Invocation invocation) {
String value = url.getMethodParameter(invocation.getMethodName(), AUTO_ATTACH_INVOCATIONID_KEY);
if (value == null) {
// add invocationid in async operation by default
return isAsync(url, invocation);
}
return Boolean.TRUE.toString().equalsIgnoreCase(value);
}
public static String getMethodName(Invocation invocation) {
if (($INVOKE.equals(invocation.getMethodName()) || $INVOKE_ASYNC.equals(invocation.getMethodName()))
&& invocation.getArguments() != null
&& invocation.getArguments().length > 0
&& invocation.getArguments()[0] instanceof String) {
return (String) invocation.getArguments()[0];
}
return invocation.getMethodName();
}
public static Object[] getArguments(Invocation invocation) {
if (($INVOKE.equals(invocation.getMethodName()) || $INVOKE_ASYNC.equals(invocation.getMethodName()))
&& invocation.getArguments() != null
&& invocation.getArguments().length > 2
&& invocation.getArguments()[2] instanceof Object[]) {
return (Object[]) invocation.getArguments()[2];
}
return invocation.getArguments();
}
public static Class<?>[] getParameterTypes(Invocation invocation) {
if (($INVOKE.equals(invocation.getMethodName()) || $INVOKE_ASYNC.equals(invocation.getMethodName()))
&& invocation.getArguments() != null
&& invocation.getArguments().length > 1
&& invocation.getArguments()[1] instanceof String[]) {
String[] types = (String[]) invocation.getArguments()[1];
if (types == null) {
return new Class<?>[0];
}
Class<?>[] parameterTypes = new Class<?>[types.length];
for (int i = 0; i < types.length; i++) {
parameterTypes[i] = ReflectUtils.forName(types[i]);
}
return parameterTypes;
}
return invocation.getParameterTypes();
}
public static boolean isAsync(URL url, Invocation inv) {
boolean isAsync;
if (inv instanceof RpcInvocation) {
RpcInvocation rpcInvocation = (RpcInvocation) inv;
if (rpcInvocation.getInvokeMode() != null) {
return rpcInvocation.getInvokeMode() == InvokeMode.ASYNC;
}
}
if (Boolean.TRUE.toString().equals(inv.getAttachment(ASYNC_KEY))) {
isAsync = true;
} else {
isAsync = url.getMethodParameter(getMethodName(inv), ASYNC_KEY, false);
}
return isAsync;
}
public static boolean isReturnTypeFuture(Invocation inv) {
Class<?> clazz;
if (inv instanceof RpcInvocation) {
clazz = ((RpcInvocation) inv).getReturnType();
} else {
clazz = getReturnType(inv);
}
return (clazz != null && CompletableFuture.class.isAssignableFrom(clazz)) || isGenericAsync(inv);
}
public static boolean isGenericAsync(Invocation inv) {
return $INVOKE_ASYNC.equals(inv.getMethodName());
}
// check parameterTypesDesc to fix CVE-2020-1948
public static boolean isGenericCall(String parameterTypesDesc, String method) {
return ($INVOKE.equals(method) || $INVOKE_ASYNC.equals(method))
&& GENERIC_PARAMETER_DESC.equals(parameterTypesDesc);
}
// check parameterTypesDesc to fix CVE-2020-1948
public static boolean isEcho(String parameterTypesDesc, String method) {
return $ECHO.equals(method) && $ECHO_PARAMETER_DESC.equals(parameterTypesDesc);
}
public static InvokeMode getInvokeMode(URL url, Invocation inv) {
if (inv instanceof RpcInvocation) {
RpcInvocation rpcInvocation = (RpcInvocation) inv;
if (rpcInvocation.getInvokeMode() != null) {
return rpcInvocation.getInvokeMode();
}
}
if (isReturnTypeFuture(inv)) {
return InvokeMode.FUTURE;
} else if (isAsync(url, inv)) {
return InvokeMode.ASYNC;
} else {
return InvokeMode.SYNC;
}
}
public static boolean isOneway(URL url, Invocation inv) {
boolean isOneway;
if (Boolean.FALSE.toString().equals(inv.getAttachment(RETURN_KEY))) {
isOneway = true;
} else {
isOneway = !url.getMethodParameter(getMethodName(inv), RETURN_KEY, true);
}
return isOneway;
}
private static Method getMethodByService(Invocation invocation, String service) throws NoSuchMethodException {
Class<?> invokerInterface = invocation.getInvoker().getInterface();
Class<?> cls = invokerInterface != null ? invokerInterface : ReflectUtils.forName(service);
Method method = cls.getMethod(invocation.getMethodName(), invocation.getParameterTypes());
if (method.getReturnType() == void.class) {
return null;
}
return method;
}
public static long getTimeout(Invocation invocation, long defaultTimeout) {
long timeout = defaultTimeout;
Object genericTimeout = invocation.getObjectAttachmentWithoutConvert(TIMEOUT_ATTACHMENT_KEY);
if (genericTimeout == null) {
genericTimeout = invocation.getObjectAttachmentWithoutConvert(TIMEOUT_ATTACHMENT_KEY_LOWER);
}
if (genericTimeout != null) {
timeout = convertToNumber(genericTimeout, defaultTimeout);
}
return timeout;
}
public static long getTimeout(
URL url, String methodName, RpcContext context, Invocation invocation, long defaultTimeout) {
long timeout = defaultTimeout;
Object timeoutFromContext = context.getObjectAttachment(TIMEOUT_KEY);
Object timeoutFromInvocation = invocation.getObjectAttachment(TIMEOUT_KEY);
if (timeoutFromContext != null) {
timeout = convertToNumber(timeoutFromContext, defaultTimeout);
} else if (timeoutFromInvocation != null) {
timeout = convertToNumber(timeoutFromInvocation, defaultTimeout);
} else if (url != null) {
timeout = url.getMethodPositiveParameter(methodName, TIMEOUT_KEY, defaultTimeout);
}
return timeout;
}
public static int calculateTimeout(URL url, Invocation invocation, String methodName, long defaultTimeout) {
Object countdown = RpcContext.getClientAttachment().getObjectAttachment(TIME_COUNTDOWN_KEY);
int timeout = (int) defaultTimeout;
if (countdown == null) {
if (url != null) {
timeout = (int) RpcUtils.getTimeout(
url, methodName, RpcContext.getClientAttachment(), invocation, defaultTimeout);
if (url.getMethodParameter(methodName, ENABLE_TIMEOUT_COUNTDOWN_KEY, false)) {
// pass timeout to remote server
invocation.setObjectAttachment(TIMEOUT_ATTACHMENT_KEY, timeout);
}
}
} else {
TimeoutCountDown timeoutCountDown = (TimeoutCountDown) countdown;
timeout = (int) timeoutCountDown.timeRemaining(TimeUnit.MILLISECONDS);
// pass timeout to remote server
invocation.setObjectAttachment(TIMEOUT_ATTACHMENT_KEY, timeout);
}
invocation.getObjectAttachments().remove(TIME_COUNTDOWN_KEY);
return timeout;
}
public static Long convertToNumber(Object obj, long defaultTimeout) {
Long timeout = convertToNumber(obj);
return timeout == null ? defaultTimeout : timeout;
}
public static Long convertToNumber(Object obj) {
Long timeout = null;
try {
if (obj instanceof String) {
timeout = Long.parseLong((String) obj);
} else if (obj instanceof Number) {
timeout = ((Number) obj).longValue();
} else if (obj != null) {
timeout = Long.parseLong(obj.toString());
}
} catch (Exception e) {
// ignore
}
return timeout;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/MockProtocol.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/MockProtocol.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Exporter;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.protocol.AbstractProtocol;
/**
* MockProtocol is used for generating a mock invoker by URL and type on consumer side
*/
public final class MockProtocol extends AbstractProtocol {
@Override
public int getDefaultPort() {
return 0;
}
@Override
public <T> Exporter<T> export(Invoker<T> invoker) throws RpcException {
throw new UnsupportedOperationException();
}
@Override
public <T> Invoker<T> protocolBindingRefer(Class<T> type, URL url) throws RpcException {
return new MockInvoker<>(url, type);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/Dubbo2RpcExceptionUtils.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/Dubbo2RpcExceptionUtils.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.support;
import java.lang.reflect.Constructor;
public class Dubbo2RpcExceptionUtils {
private static final Class<? extends org.apache.dubbo.rpc.RpcException> RPC_EXCEPTION_CLASS;
private static final Constructor<? extends org.apache.dubbo.rpc.RpcException> RPC_EXCEPTION_CONSTRUCTOR_I_S_T;
static {
RPC_EXCEPTION_CLASS = loadClass();
RPC_EXCEPTION_CONSTRUCTOR_I_S_T = loadConstructor(int.class, String.class, Throwable.class);
}
@SuppressWarnings("unchecked")
private static Class<? extends org.apache.dubbo.rpc.RpcException> loadClass() {
try {
Class<?> clazz = Class.forName("com.alibaba.dubbo.rpc.RpcException");
if (org.apache.dubbo.rpc.RpcException.class.isAssignableFrom(clazz)) {
return (Class<? extends org.apache.dubbo.rpc.RpcException>) clazz;
} else {
return null;
}
} catch (Throwable e) {
return null;
}
}
private static Constructor<? extends org.apache.dubbo.rpc.RpcException> loadConstructor(
Class<?>... parameterTypes) {
if (RPC_EXCEPTION_CLASS == null) {
return null;
}
try {
return RPC_EXCEPTION_CLASS.getConstructor(parameterTypes);
} catch (Throwable e) {
return null;
}
}
public static boolean isRpcExceptionClassLoaded() {
return RPC_EXCEPTION_CLASS != null && RPC_EXCEPTION_CONSTRUCTOR_I_S_T != null;
}
public static Class<? extends org.apache.dubbo.rpc.RpcException> getRpcExceptionClass() {
return RPC_EXCEPTION_CLASS;
}
public static org.apache.dubbo.rpc.RpcException newRpcException(int code, String message, Throwable cause) {
if (RPC_EXCEPTION_CONSTRUCTOR_I_S_T == null) {
return null;
}
try {
return RPC_EXCEPTION_CONSTRUCTOR_I_S_T.newInstance(code, message, cause);
} catch (Throwable e) {
return null;
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/AccessLogData.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/AccessLogData.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.support;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.common.utils.ToStringUtils;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcContext;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* AccessLogData is a container for log event data. In internally uses map and store each field of log as value. It
* does not generate any dynamic value e.g. time stamp, local jvm machine host address etc. It does not allow any null
* or empty key.
*/
public final class AccessLogData {
private static final String MESSAGE_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss.SSSSS";
private static final DateTimeFormatter MESSAGE_DATE_FORMATTER = DateTimeFormatter.ofPattern(MESSAGE_DATE_FORMAT);
private static final String VERSION = "version";
private static final String GROUP = "group";
private static final String SERVICE = "service";
private static final String METHOD_NAME = "method-name";
private static final String INVOCATION_TIME = "invocation-time";
private static final String OUT_TIME = "out-time";
private static final String TYPES = "types";
private static final String ARGUMENTS = "arguments";
private static final String REMOTE_HOST = "remote-host";
private static final String REMOTE_PORT = "remote-port";
private static final String LOCAL_HOST = "localhost";
private static final String LOCAL_PORT = "local-port";
/**
* This is used to store log data in key val format.
*/
private final Map<String, Object> data;
/**
* Default constructor.
*/
private AccessLogData() {
RpcContext context = RpcContext.getServiceContext();
data = new HashMap<>();
setLocalHost(context.getLocalHost());
setLocalPort(context.getLocalPort());
setRemoteHost(context.getRemoteHost());
setRemotePort(context.getRemotePort());
}
/**
* Get new instance of log data.
*
* @return instance of AccessLogData
*/
public static AccessLogData newLogData() {
return new AccessLogData();
}
/**
* Add version information.
*
* @param version
*/
public void setVersion(String version) {
set(VERSION, version);
}
/**
* Add service name.
*
* @param serviceName
*/
public void setServiceName(String serviceName) {
set(SERVICE, serviceName);
}
/**
* Add group name
*
* @param group
*/
public void setGroup(String group) {
set(GROUP, group);
}
/**
* Set the invocation date. As an argument it accept date string.
*
* @param invocationTime
*/
public void setInvocationTime(Date invocationTime) {
set(INVOCATION_TIME, invocationTime);
}
/**
* Set the out date. As an argument it accept date string.
*
* @param outTime
*/
public void setOutTime(Date outTime) {
set(OUT_TIME, outTime);
}
/**
* Set caller remote host
*
* @param remoteHost
*/
private void setRemoteHost(String remoteHost) {
set(REMOTE_HOST, remoteHost);
}
/**
* Set caller remote port.
*
* @param remotePort
*/
private void setRemotePort(Integer remotePort) {
set(REMOTE_PORT, remotePort);
}
/**
* Set local host
*
* @param localHost
*/
private void setLocalHost(String localHost) {
set(LOCAL_HOST, localHost);
}
/**
* Set local port of exported service
*
* @param localPort
*/
private void setLocalPort(Integer localPort) {
set(LOCAL_PORT, localPort);
}
/**
* Set target method name.
*
* @param methodName
*/
public void setMethodName(String methodName) {
set(METHOD_NAME, methodName);
}
/**
* Set invocation's method's input parameter's types
*
* @param types
*/
public void setTypes(Class[] types) {
set(TYPES, types != null ? Arrays.copyOf(types, types.length) : null);
}
/**
* Sets invocation arguments
*
* @param arguments
*/
public void setArguments(Object[] arguments) {
set(ARGUMENTS, arguments != null ? Arrays.copyOf(arguments, arguments.length) : null);
}
/**
* Return gthe service of access log entry
*
* @return
*/
public String getServiceName() {
return get(SERVICE).toString();
}
public String getLogMessage() {
StringBuilder sn = new StringBuilder();
sn.append("[")
.append(LocalDateTime.ofInstant(getInvocationTime().toInstant(), ZoneId.systemDefault())
.format(MESSAGE_DATE_FORMATTER))
.append("] ")
.append("-> ")
.append("[")
.append(LocalDateTime.ofInstant(getOutTime().toInstant(), ZoneId.systemDefault())
.format(MESSAGE_DATE_FORMATTER))
.append("] ")
.append(get(REMOTE_HOST))
.append(':')
.append(get(REMOTE_PORT))
.append(" -> ")
.append(get(LOCAL_HOST))
.append(':')
.append(get(LOCAL_PORT))
.append(" - ");
String group = get(GROUP) != null ? get(GROUP).toString() : "";
if (StringUtils.isNotEmpty(group)) {
sn.append(group).append('/');
}
sn.append(get(SERVICE));
String version = get(VERSION) != null ? get(VERSION).toString() : "";
if (StringUtils.isNotEmpty(version)) {
sn.append(':').append(version);
}
sn.append(' ');
sn.append(get(METHOD_NAME));
sn.append('(');
Class<?>[] types = get(TYPES) != null ? (Class<?>[]) get(TYPES) : new Class[0];
boolean first = true;
for (Class<?> type : types) {
if (first) {
first = false;
} else {
sn.append(',');
}
sn.append(type.getName());
}
sn.append(") ");
Object[] args = get(ARGUMENTS) != null ? (Object[]) get(ARGUMENTS) : null;
if (args != null && args.length > 0) {
sn.append(ToStringUtils.printToString(args));
}
return sn.toString();
}
private Date getInvocationTime() {
return (Date) get(INVOCATION_TIME);
}
private Date getOutTime() {
return (Date) get(OUT_TIME);
}
/**
* Return value of key
*
* @param key
* @return
*/
private Object get(String key) {
return data.get(key);
}
/**
* Add log key along with his value.
*
* @param key Any not null or non empty string
* @param value Any object including null.
*/
private void set(String key, Object value) {
data.put(key, value);
}
public void buildAccessLogData(Invoker<?> invoker, Invocation inv) {
setServiceName(invoker.getInterface().getName());
setMethodName(RpcUtils.getMethodName(inv));
setVersion(invoker.getUrl().getVersion());
setGroup(invoker.getUrl().getGroup());
setInvocationTime(new Date());
setTypes(inv.getParameterTypes());
setArguments(inv.getArguments());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/MockInvoker.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/MockInvoker.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionDirector;
import org.apache.dubbo.common.extension.ExtensionInjector;
import org.apache.dubbo.common.utils.ArrayUtils;
import org.apache.dubbo.common.utils.ConfigUtils;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.common.utils.PojoUtils;
import org.apache.dubbo.common.utils.ReflectUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.AsyncRpcResult;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.ProxyFactory;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.RpcInvocation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Type;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import static org.apache.dubbo.rpc.Constants.FAIL_PREFIX;
import static org.apache.dubbo.rpc.Constants.FORCE_PREFIX;
import static org.apache.dubbo.rpc.Constants.MOCK_KEY;
import static org.apache.dubbo.rpc.Constants.RETURN_KEY;
import static org.apache.dubbo.rpc.Constants.RETURN_PREFIX;
import static org.apache.dubbo.rpc.Constants.THROW_PREFIX;
public final class MockInvoker<T> implements Invoker<T> {
private final ProxyFactory proxyFactory;
private static final Map<String, Invoker<?>> MOCK_MAP = new ConcurrentHashMap<>();
private static final Map<String, Throwable> THROWABLE_MAP = new ConcurrentHashMap<>();
private final URL url;
private final Class<T> type;
public MockInvoker(URL url, Class<T> type) {
this.url = url;
this.type = type;
this.proxyFactory = url.getOrDefaultFrameworkModel()
.getExtensionLoader(ProxyFactory.class)
.getAdaptiveExtension();
}
public static Object parseMockValue(String mock) throws Exception {
return parseMockValue(mock, null);
}
public static Object parseMockValue(String mock, Type[] returnTypes) throws Exception {
Object value;
if ("empty".equals(mock)) {
value = ReflectUtils.getEmptyObject(
returnTypes != null && returnTypes.length > 0 ? (Class<?>) returnTypes[0] : null);
} else if ("null".equals(mock)) {
value = null;
} else if ("true".equals(mock)) {
value = true;
} else if ("false".equals(mock)) {
value = false;
} else if (mock.length() >= 2
&& (mock.startsWith("\"") && mock.endsWith("\"") || mock.startsWith("\'") && mock.endsWith("\'"))) {
value = mock.subSequence(1, mock.length() - 1);
} else if (returnTypes != null && returnTypes.length > 0 && returnTypes[0] == String.class) {
value = mock;
} else if (StringUtils.isNumeric(mock, false)) {
value = JsonUtils.toJavaObject(mock, Object.class);
} else if (mock.startsWith("{")) {
value = JsonUtils.toJavaObject(mock, Map.class);
} else if (mock.startsWith("[")) {
value = JsonUtils.toJavaList(mock, Object.class);
} else {
value = mock;
}
if (ArrayUtils.isNotEmpty(returnTypes)) {
value = PojoUtils.realize(value, (Class<?>) returnTypes[0], returnTypes.length > 1 ? returnTypes[1] : null);
}
return value;
}
@Override
public Result invoke(Invocation invocation) throws RpcException {
if (invocation instanceof RpcInvocation) {
((RpcInvocation) invocation).setInvoker(this);
}
String mock = getUrl().getMethodParameter(invocation.getMethodName(), MOCK_KEY);
if (StringUtils.isBlank(mock)) {
throw new RpcException(new IllegalAccessException("mock can not be null. url :" + url));
}
mock = normalizeMock(URL.decode(mock));
if (mock.startsWith(RETURN_PREFIX)) {
mock = mock.substring(RETURN_PREFIX.length()).trim();
try {
Type[] returnTypes = RpcUtils.getReturnTypes(invocation);
Object value = parseMockValue(mock, returnTypes);
return AsyncRpcResult.newDefaultAsyncResult(value, invocation);
} catch (Exception ew) {
throw new RpcException(
"mock return invoke error. method :" + invocation.getMethodName() + ", mock:" + mock + ", url: "
+ url,
ew);
}
} else if (mock.startsWith(THROW_PREFIX)) {
mock = mock.substring(THROW_PREFIX.length()).trim();
if (StringUtils.isBlank(mock)) {
throw new RpcException("mocked exception for service degradation.");
} else { // user customized class
Throwable t = getThrowable(mock);
throw new RpcException(RpcException.BIZ_EXCEPTION, t);
}
} else { // impl mock
try {
Invoker<T> invoker = getInvoker(mock);
return invoker.invoke(invocation);
} catch (Throwable t) {
throw new RpcException("Failed to create mock implementation class " + mock, t);
}
}
}
public static Throwable getThrowable(String throwstr) {
Throwable throwable = THROWABLE_MAP.get(throwstr);
if (throwable != null) {
return throwable;
}
try {
Throwable t;
Class<?> bizException = ReflectUtils.forName(throwstr);
Constructor<?> constructor;
constructor = ReflectUtils.findConstructor(bizException, String.class);
t = (Throwable) constructor.newInstance(new Object[] {"mocked exception for service degradation."});
if (THROWABLE_MAP.size() < 1000) {
THROWABLE_MAP.put(throwstr, t);
}
return t;
} catch (Exception e) {
throw new RpcException("mock throw error :" + throwstr + " argument error.", e);
}
}
@SuppressWarnings("unchecked")
private Invoker<T> getInvoker(String mock) {
Class<T> serviceType = (Class<T>) ReflectUtils.forName(url.getServiceInterface());
String mockService = ConfigUtils.isDefault(mock) ? serviceType.getName() + "Mock" : mock;
Invoker<T> invoker = (Invoker<T>) MOCK_MAP.get(mockService);
if (invoker != null) {
return invoker;
}
T mockObject = (T) getMockObject(url.getOrDefaultApplicationModel().getExtensionDirector(), mock, serviceType);
invoker = proxyFactory.getInvoker(mockObject, serviceType, url);
if (MOCK_MAP.size() < 10000) {
MOCK_MAP.put(mockService, invoker);
}
return invoker;
}
@SuppressWarnings("unchecked")
public static Object getMockObject(ExtensionDirector extensionDirector, String mockService, Class serviceType) {
boolean isDefault = ConfigUtils.isDefault(mockService);
if (isDefault) {
mockService = serviceType.getName() + "Mock";
}
Class<?> mockClass;
try {
mockClass = ReflectUtils.forName(mockService);
} catch (Exception e) {
if (!isDefault) { // does not check Spring bean if it is default config.
ExtensionInjector extensionFactory = extensionDirector
.getExtensionLoader(ExtensionInjector.class)
.getAdaptiveExtension();
Object obj = extensionFactory.getInstance(serviceType, mockService);
if (obj != null) {
return obj;
}
}
throw new IllegalStateException(
"Did not find mock class or instance "
+ mockService
+ ", please check if there's mock class or instance implementing interface "
+ serviceType.getName(),
e);
}
if (mockClass == null || !serviceType.isAssignableFrom(mockClass)) {
throw new IllegalStateException(
"The mock class " + mockClass.getName() + " not implement interface " + serviceType.getName());
}
try {
return mockClass.newInstance();
} catch (InstantiationException e) {
throw new IllegalStateException("No default constructor from mock class " + mockClass.getName(), e);
} catch (IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
/**
* Normalize mock string:
*
* <ol>
* <li>return => return null</li>
* <li>fail => default</li>
* <li>force => default</li>
* <li>fail:throw/return foo => throw/return foo</li>
* <li>force:throw/return foo => throw/return foo</li>
* </ol>
*
* @param mock mock string
* @return normalized mock string
*/
public static String normalizeMock(String mock) {
if (mock == null) {
return mock;
}
mock = mock.trim();
if (mock.length() == 0) {
return mock;
}
if (RETURN_KEY.equalsIgnoreCase(mock)) {
return RETURN_PREFIX + "null";
}
if (ConfigUtils.isDefault(mock) || "fail".equalsIgnoreCase(mock) || "force".equalsIgnoreCase(mock)) {
return "default";
}
if (mock.startsWith(FAIL_PREFIX)) {
mock = mock.substring(FAIL_PREFIX.length()).trim();
}
if (mock.startsWith(FORCE_PREFIX)) {
mock = mock.substring(FORCE_PREFIX.length()).trim();
}
if (mock.startsWith(RETURN_PREFIX) || mock.startsWith(THROW_PREFIX)) {
mock = mock.replace('`', '"');
}
return mock;
}
@Override
public URL getUrl() {
return this.url;
}
@Override
public boolean isAvailable() {
return true;
}
@Override
public void destroy() {
// do nothing
}
@Override
public Class<T> getInterface() {
return type;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericImplFilter.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericImplFilter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.filter;
import org.apache.dubbo.common.beanutil.JavaBeanAccessor;
import org.apache.dubbo.common.beanutil.JavaBeanDescriptor;
import org.apache.dubbo.common.beanutil.JavaBeanSerializeUtil;
import org.apache.dubbo.common.compact.Dubbo2CompactUtils;
import org.apache.dubbo.common.compact.Dubbo2GenericExceptionUtils;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.DefaultSerializeClassChecker;
import org.apache.dubbo.common.utils.PojoUtils;
import org.apache.dubbo.common.utils.ReflectUtils;
import org.apache.dubbo.rpc.Constants;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.model.ModuleModel;
import org.apache.dubbo.rpc.service.GenericService;
import org.apache.dubbo.rpc.support.ProtocolUtils;
import org.apache.dubbo.rpc.support.RpcUtils;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import static org.apache.dubbo.common.constants.CommonConstants.$INVOKE;
import static org.apache.dubbo.common.constants.CommonConstants.$INVOKE_ASYNC;
import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_PARAMETER_DESC;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_REFLECTIVE_OPERATION_FAILED;
import static org.apache.dubbo.rpc.Constants.GENERIC_KEY;
/**
* GenericImplInvokerFilter
*/
@Activate(group = CommonConstants.CONSUMER, value = GENERIC_KEY, order = 20000)
public class GenericImplFilter implements Filter, Filter.Listener {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(GenericImplFilter.class);
private static final Class<?>[] GENERIC_PARAMETER_TYPES =
new Class<?>[] {String.class, String[].class, Object[].class};
private static final String GENERIC_IMPL_MARKER = "GENERIC_IMPL";
private final ModuleModel moduleModel;
public GenericImplFilter(ModuleModel moduleModel) {
this.moduleModel = moduleModel;
}
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
String generic = invoker.getUrl().getParameter(GENERIC_KEY);
// calling a generic impl service
if (isCallingGenericImpl(generic, invocation)) {
RpcInvocation invocation2 = new RpcInvocation(invocation);
/**
* Mark this invocation as a generic impl call, this value will be removed automatically before passing on the wire.
* See {@link RpcUtils#sieveUnnecessaryAttachments(Invocation)}
*/
invocation2.put(GENERIC_IMPL_MARKER, true);
String methodName = invocation2.getMethodName();
Class<?>[] parameterTypes = invocation2.getParameterTypes();
Object[] arguments = invocation2.getArguments();
String[] types = new String[parameterTypes.length];
for (int i = 0; i < parameterTypes.length; i++) {
types[i] = ReflectUtils.getName(parameterTypes[i]);
}
Object[] args;
if (ProtocolUtils.isBeanGenericSerialization(generic)) {
args = new Object[arguments.length];
for (int i = 0; i < arguments.length; i++) {
args[i] = JavaBeanSerializeUtil.serialize(arguments[i], JavaBeanAccessor.METHOD);
}
} else {
args = PojoUtils.generalize(arguments);
}
if (RpcUtils.isReturnTypeFuture(invocation)) {
invocation2.setMethodName($INVOKE_ASYNC);
} else {
invocation2.setMethodName($INVOKE);
}
invocation2.setParameterTypes(GENERIC_PARAMETER_TYPES);
invocation2.setParameterTypesDesc(GENERIC_PARAMETER_DESC);
invocation2.setArguments(new Object[] {methodName, types, args});
return invoker.invoke(invocation2);
}
// making a generic call to a normal service
else if (isMakingGenericCall(generic, invocation)) {
Object[] args = (Object[]) invocation.getArguments()[2];
if (ProtocolUtils.isJavaGenericSerialization(generic)) {
for (Object arg : args) {
if (byte[].class != arg.getClass()) {
error(generic, byte[].class.getName(), arg.getClass().getName());
}
}
} else if (ProtocolUtils.isBeanGenericSerialization(generic)) {
for (Object arg : args) {
if (arg != null && !(arg instanceof JavaBeanDescriptor)) {
error(
generic,
JavaBeanDescriptor.class.getName(),
arg.getClass().getName());
}
}
}
invocation.setAttachment(GENERIC_KEY, invoker.getUrl().getParameter(GENERIC_KEY));
}
return invoker.invoke(invocation);
}
private void error(String generic, String expected, String actual) throws RpcException {
throw new RpcException("Generic serialization [" + generic + "] only support message type " + expected
+ " and your message type is " + actual);
}
@Override
public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) {
String generic = invoker.getUrl().getParameter(GENERIC_KEY);
String methodName = invocation.getMethodName();
Class<?>[] parameterTypes = invocation.getParameterTypes();
Object genericImplMarker = invocation.get(GENERIC_IMPL_MARKER);
if (genericImplMarker != null && (boolean) invocation.get(GENERIC_IMPL_MARKER)) {
if (!appResponse.hasException()) {
Object value = appResponse.getValue();
try {
Class<?> invokerInterface = invoker.getInterface();
if (!$INVOKE.equals(methodName)
&& !$INVOKE_ASYNC.equals(methodName)
&& invokerInterface.isAssignableFrom(GenericService.class)) {
try {
// find the real interface from url
String realInterface = invoker.getUrl().getParameter(Constants.INTERFACE);
invokerInterface = ReflectUtils.forName(realInterface);
} catch (Exception e) {
// ignore
}
}
Method method = invokerInterface.getMethod(methodName, parameterTypes);
if (ProtocolUtils.isBeanGenericSerialization(generic)) {
if (value == null) {
appResponse.setValue(value);
} else if (value instanceof JavaBeanDescriptor) {
appResponse.setValue(JavaBeanSerializeUtil.deserialize((JavaBeanDescriptor) value));
} else {
throw new RpcException("The type of result value is "
+ value.getClass().getName() + " other than " + JavaBeanDescriptor.class.getName()
+ ", and the result is " + value);
}
} else {
Type[] types = ReflectUtils.getReturnTypes(method);
appResponse.setValue(PojoUtils.realize(value, (Class<?>) types[0], types[1]));
}
} catch (NoSuchMethodException e) {
throw new RpcException(e.getMessage(), e);
}
} else if (Dubbo2CompactUtils.isEnabled()
&& Dubbo2GenericExceptionUtils.isGenericExceptionClassLoaded()
&& Dubbo2GenericExceptionUtils.getGenericExceptionClass()
.isAssignableFrom(appResponse.getException().getClass())) {
// TODO we should cast if is apache GenericException or not?
org.apache.dubbo.rpc.service.GenericException exception =
(org.apache.dubbo.rpc.service.GenericException) appResponse.getException();
try {
String className = exception.getExceptionClass();
DefaultSerializeClassChecker classChecker = moduleModel
.getApplicationModel()
.getFrameworkModel()
.getBeanFactory()
.getBean(DefaultSerializeClassChecker.class);
Class<?> clazz =
classChecker.loadClass(Thread.currentThread().getContextClassLoader(), className);
Throwable targetException = null;
Throwable lastException = null;
try {
targetException =
(Throwable) clazz.getDeclaredConstructor().newInstance();
} catch (Throwable e) {
lastException = e;
for (Constructor<?> constructor : clazz.getConstructors()) {
try {
targetException = (Throwable)
constructor.newInstance(new Object[constructor.getParameterTypes().length]);
break;
} catch (Throwable e1) {
lastException = e1;
}
}
}
if (targetException != null) {
try {
Field field = Throwable.class.getDeclaredField("detailMessage");
if (!field.isAccessible()) {
field.setAccessible(true);
}
field.set(targetException, exception.getExceptionMessage());
} catch (Throwable e) {
logger.warn(COMMON_REFLECTIVE_OPERATION_FAILED, "", "", e.getMessage(), e);
}
appResponse.setException(targetException);
} else if (lastException != null) {
throw lastException;
}
} catch (Throwable e) {
throw new RpcException(
"Can not deserialize exception " + exception.getExceptionClass() + ", message: "
+ exception.getExceptionMessage(),
e);
}
}
}
}
@Override
public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) {}
private boolean isCallingGenericImpl(String generic, Invocation invocation) {
return ProtocolUtils.isGeneric(generic)
&& (!$INVOKE.equals(invocation.getMethodName()) && !$INVOKE_ASYNC.equals(invocation.getMethodName()))
&& invocation instanceof RpcInvocation;
}
private boolean isMakingGenericCall(String generic, Invocation invocation) {
return (invocation.getMethodName().equals($INVOKE)
|| invocation.getMethodName().equals($INVOKE_ASYNC))
&& invocation.getArguments() != null
&& invocation.getArguments().length == 3
&& ProtocolUtils.isGeneric(generic);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ClassLoaderCallbackFilter.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ClassLoaderCallbackFilter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.filter;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.BaseFilter;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import static org.apache.dubbo.common.constants.CommonConstants.WORKING_CLASSLOADER_KEY;
/**
* Switch thread context class loader on filter callback.
*/
@Activate(group = CommonConstants.PROVIDER, order = Integer.MAX_VALUE)
public class ClassLoaderCallbackFilter implements Filter, BaseFilter.Listener {
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
return invoker.invoke(invocation);
}
@Override
public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) {
setClassLoader(invoker, invocation);
}
@Override
public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) {
setClassLoader(invoker, invocation);
}
private void setClassLoader(Invoker<?> invoker, Invocation invocation) {
ClassLoader workingClassLoader = (ClassLoader) invocation.get(WORKING_CLASSLOADER_KEY);
if (workingClassLoader != null) {
Thread.currentThread().setContextClassLoader(workingClassLoader);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ContextFilter.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ContextFilter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.filter;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.PenetrateAttachmentSelector;
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.ApplicationModel;
import org.apache.dubbo.rpc.support.RpcUtils;
import org.apache.dubbo.rpc.support.TrieTree;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_VERSION_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.PROVIDER;
import static org.apache.dubbo.common.constants.CommonConstants.REMOTE_APPLICATION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.TAG_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.common.constants.CommonConstants.VERSION_KEY;
import static org.apache.dubbo.rpc.Constants.ASYNC_KEY;
import static org.apache.dubbo.rpc.Constants.FORCE_USE_TAG;
import static org.apache.dubbo.rpc.Constants.TOKEN_KEY;
/**
* ContextFilter set the provider RpcContext with invoker, invocation, local port it is using and host for
* current execution thread.
*
* @see RpcContext
*/
@Activate(group = PROVIDER, order = Integer.MIN_VALUE)
public class ContextFilter implements Filter, Filter.Listener {
private final Set<PenetrateAttachmentSelector> supportedSelectors;
public ContextFilter(ApplicationModel applicationModel) {
ExtensionLoader<PenetrateAttachmentSelector> selectorExtensionLoader =
applicationModel.getExtensionLoader(PenetrateAttachmentSelector.class);
supportedSelectors = selectorExtensionLoader.getSupportedExtensionInstances();
}
private static final TrieTree UNLOADING_KEYS;
static {
Set<String> keySet = new HashSet<>();
keySet.add(PATH_KEY);
keySet.add(INTERFACE_KEY);
keySet.add(GROUP_KEY);
keySet.add(VERSION_KEY);
keySet.add(DUBBO_VERSION_KEY);
keySet.add(TOKEN_KEY);
keySet.add(TIMEOUT_KEY);
keySet.add(TIMEOUT_ATTACHMENT_KEY);
// Remove async property to avoid being passed to the following invoke chain.
keySet.add(ASYNC_KEY);
keySet.add(TAG_KEY);
keySet.add(FORCE_USE_TAG);
// Remove HTTP headers to avoid being passed to the following invoke chain.
keySet.add("accept");
keySet.add("accept-charset");
keySet.add("accept-datetime");
keySet.add("accept-encoding");
keySet.add("accept-language");
keySet.add("access-control-request-headers");
keySet.add("access-control-request-method");
keySet.add("authorization");
keySet.add("cache-control");
keySet.add("connection");
keySet.add("content-length");
keySet.add("content-md5");
keySet.add("content-type");
keySet.add("cookie");
keySet.add("date");
keySet.add("dnt");
keySet.add("expect");
keySet.add("forwarded");
keySet.add("from");
keySet.add("host");
keySet.add("http2-settings");
keySet.add("if-match");
keySet.add("if-modified-since");
keySet.add("if-none-match");
keySet.add("if-range");
keySet.add("if-unmodified-since");
keySet.add("max-forwards");
keySet.add("origin");
keySet.add("pragma");
keySet.add("proxy-authorization");
keySet.add("range");
keySet.add("referer");
keySet.add("sec-fetch-dest");
keySet.add("sec-fetch-mode");
keySet.add("sec-fetch-site");
keySet.add("sec-fetch-user");
keySet.add("te");
keySet.add("trailer");
keySet.add("upgrade");
keySet.add("upgrade-insecure-requests");
keySet.add("user-agent");
UNLOADING_KEYS = new TrieTree(keySet);
}
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
Map<String, Object> attachments = invocation.getObjectAttachments();
if (attachments != null) {
Map<String, Object> newAttach = new HashMap<>(attachments.size());
for (Map.Entry<String, Object> entry : attachments.entrySet()) {
String key = entry.getKey();
if (!UNLOADING_KEYS.search(key)) {
newAttach.put(key, entry.getValue());
}
}
attachments = newAttach;
}
RpcContext.getServiceContext().setInvoker(invoker).setInvocation(invocation);
RpcContext context = RpcContext.getServerAttachment();
// .setAttachments(attachments) // merged from dubbox
if (context.getLocalAddress() == null) {
context.setLocalAddress(invoker.getUrl().getHost(), invoker.getUrl().getPort());
}
String remoteApplication = invocation.getAttachment(REMOTE_APPLICATION_KEY);
if (StringUtils.isNotEmpty(remoteApplication)) {
RpcContext.getServiceContext().setRemoteApplicationName(remoteApplication);
} else {
RpcContext.getServiceContext().setRemoteApplicationName(context.getAttachment(REMOTE_APPLICATION_KEY));
}
long timeout = RpcUtils.getTimeout(invocation, -1);
if (timeout != -1) {
// pass to next hop
RpcContext.getServerAttachment()
.setObjectAttachment(
TIME_COUNTDOWN_KEY, TimeoutCountDown.newCountDown(timeout, TimeUnit.MILLISECONDS));
}
// merged from dubbox
// we may already add some attachments into RpcContext before this filter (e.g. in rest protocol)
if (CollectionUtils.isNotEmptyMap(attachments)) {
if (context.getObjectAttachments().size() > 0) {
context.getObjectAttachments().putAll(attachments);
} else {
context.setObjectAttachments(attachments);
}
}
if (invocation instanceof RpcInvocation) {
RpcInvocation rpcInvocation = (RpcInvocation) invocation;
rpcInvocation.setInvoker(invoker);
}
try {
context.clearAfterEachInvoke(false);
return invoker.invoke(invocation);
} finally {
context.clearAfterEachInvoke(true);
if (context.isAsyncStarted()) {
removeContext();
}
}
}
@Override
public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) {
// pass attachments to result
if (CollectionUtils.isNotEmpty(supportedSelectors)) {
for (PenetrateAttachmentSelector supportedSelector : supportedSelectors) {
Map<String, Object> selected = supportedSelector.selectReverse(
invocation, RpcContext.getClientResponseContext(), RpcContext.getServerResponseContext());
if (CollectionUtils.isNotEmptyMap(selected)) {
appResponse.addObjectAttachments(selected);
}
}
} else {
appResponse.addObjectAttachments(
RpcContext.getClientResponseContext().getObjectAttachments());
}
appResponse.addObjectAttachments(RpcContext.getServerResponseContext().getObjectAttachments());
removeContext();
}
@Override
public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) {
removeContext();
}
private void removeContext() {
RpcContext.removeServerAttachment();
RpcContext.removeClientAttachment();
RpcContext.removeServiceContext();
RpcContext.removeClientResponseContext();
RpcContext.removeServerResponseContext();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ClassLoaderFilter.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ClassLoaderFilter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.filter;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.BaseFilter;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import static org.apache.dubbo.common.constants.CommonConstants.STAGED_CLASSLOADER_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.WORKING_CLASSLOADER_KEY;
/**
* Set the current execution thread class loader to service interface's class loader.
*/
@Activate(group = CommonConstants.PROVIDER, order = -30000)
public class ClassLoaderFilter implements Filter, BaseFilter.Listener {
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
ClassLoader stagedClassLoader = Thread.currentThread().getContextClassLoader();
ClassLoader effectiveClassLoader;
if (invocation.getServiceModel() != null) {
effectiveClassLoader = invocation.getServiceModel().getClassLoader();
} else {
effectiveClassLoader = invoker.getClass().getClassLoader();
}
if (effectiveClassLoader != null) {
invocation.put(STAGED_CLASSLOADER_KEY, stagedClassLoader);
invocation.put(WORKING_CLASSLOADER_KEY, effectiveClassLoader);
Thread.currentThread().setContextClassLoader(effectiveClassLoader);
}
try {
return invoker.invoke(invocation);
} finally {
Thread.currentThread().setContextClassLoader(stagedClassLoader);
}
}
@Override
public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) {
resetClassLoader(invoker, invocation);
}
@Override
public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) {
resetClassLoader(invoker, invocation);
}
private void resetClassLoader(Invoker<?> invoker, Invocation invocation) {
ClassLoader stagedClassLoader = (ClassLoader) invocation.get(STAGED_CLASSLOADER_KEY);
if (stagedClassLoader != null) {
Thread.currentThread().setContextClassLoader(stagedClassLoader);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TokenFilter.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TokenFilter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.filter;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.utils.ConfigUtils;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.support.RpcUtils;
import static org.apache.dubbo.rpc.Constants.TOKEN_KEY;
/**
* Perform check whether given provider token is matching with remote token or not. If it does not match
* it will not allow invoking remote method.
*
* @see Filter
*/
@Activate(group = CommonConstants.PROVIDER, value = TOKEN_KEY)
public class TokenFilter implements Filter {
@Override
public Result invoke(Invoker<?> invoker, Invocation inv) throws RpcException {
String token = invoker.getUrl().getParameter(TOKEN_KEY);
if (ConfigUtils.isNotEmpty(token)) {
Class<?> serviceType = invoker.getInterface();
String remoteToken = (String) inv.getObjectAttachmentWithoutConvert(TOKEN_KEY);
if (!token.equals(remoteToken)) {
throw new RpcException("Invalid token! Forbid invoke remote service " + serviceType + " method "
+ RpcUtils.getMethodName(inv) + "() from consumer "
+ RpcContext.getServiceContext().getRemoteHost() + " to provider "
+ RpcContext.getServiceContext().getLocalHost()
+ ", consumer incorrect token is " + remoteToken);
}
}
return invoker.invoke(inv);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ExecuteLimitFilter.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ExecuteLimitFilter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.filter;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.RpcStatus;
import org.apache.dubbo.rpc.service.GenericService;
import org.apache.dubbo.rpc.support.RpcUtils;
import static org.apache.dubbo.common.constants.CommonConstants.$INVOKE;
import static org.apache.dubbo.common.constants.CommonConstants.$INVOKE_ASYNC;
import static org.apache.dubbo.rpc.Constants.EXECUTES_KEY;
/**
* The maximum parallel execution request count per method per service for the provider.If the max configured
* <b>executes</b> is set to 10 and if invoke request where it is already 10 then it will throw exception. It
* continues the same behaviour un till it is <10.
*/
@Activate(group = CommonConstants.PROVIDER, value = EXECUTES_KEY)
public class ExecuteLimitFilter implements Filter, Filter.Listener {
private static final String EXECUTE_LIMIT_FILTER_START_TIME = "execute_limit_filter_start_time";
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
URL url = invoker.getUrl();
String methodName = RpcUtils.getMethodName(invocation);
int max = url.getMethodParameter(methodName, EXECUTES_KEY, 0);
if (!RpcStatus.beginCount(url, methodName, max)) {
throw new RpcException(
RpcException.LIMIT_EXCEEDED_EXCEPTION,
"Failed to invoke method " + RpcUtils.getMethodName(invocation) + " in provider " + url
+ ", cause: The service using threads greater than <dubbo:service executes=\"" + max
+ "\" /> limited.");
}
invocation.put(EXECUTE_LIMIT_FILTER_START_TIME, System.currentTimeMillis());
try {
return invoker.invoke(invocation);
} catch (Throwable t) {
if (t instanceof RuntimeException) {
throw (RuntimeException) t;
} else {
throw new RpcException("unexpected exception when ExecuteLimitFilter", t);
}
}
}
@Override
public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) {
RpcStatus.endCount(invoker.getUrl(), getRealMethodName(invoker, invocation), getElapsed(invocation), true);
}
@Override
public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) {
if (t instanceof RpcException) {
RpcException rpcException = (RpcException) t;
if (rpcException.isLimitExceed()) {
return;
}
}
RpcStatus.endCount(invoker.getUrl(), getRealMethodName(invoker, invocation), getElapsed(invocation), false);
}
private String getRealMethodName(Invoker<?> invoker, Invocation invocation) {
if ((invocation.getMethodName().equals($INVOKE)
|| invocation.getMethodName().equals($INVOKE_ASYNC))
&& invocation.getArguments() != null
&& invocation.getArguments().length == 3
&& !GenericService.class.isAssignableFrom(invoker.getInterface())) {
return ((String) invocation.getArguments()[0]).trim();
}
return invocation.getMethodName();
}
private long getElapsed(Invocation invocation) {
Object beginTime = invocation.get(EXECUTE_LIMIT_FILTER_START_TIME);
return beginTime != null ? System.currentTimeMillis() - (Long) beginTime : 0;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/DeprecatedFilter.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/DeprecatedFilter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.filter;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.ConcurrentHashSet;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.support.RpcUtils;
import java.util.Set;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNSUPPORTED_INVOKER;
import static org.apache.dubbo.rpc.Constants.DEPRECATED_KEY;
/**
* DeprecatedFilter logs error message if a invoked method has been marked as deprecated. To check whether a method
* is deprecated or not it looks for <b>deprecated</b> attribute value and consider it is deprecated it value is <b>true</b>
*
* @see Filter
*/
@Activate(group = CommonConstants.CONSUMER, value = DEPRECATED_KEY)
public class DeprecatedFilter implements Filter {
private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(DeprecatedFilter.class);
private static final Set<String> LOGGED = new ConcurrentHashSet<>();
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
String key = invoker.getInterface().getName() + "." + RpcUtils.getMethodName(invocation);
if (!LOGGED.contains(key)) {
LOGGED.add(key);
if (invoker.getUrl().getMethodParameter(RpcUtils.getMethodName(invocation), DEPRECATED_KEY, false)) {
LOGGER.error(
COMMON_UNSUPPORTED_INVOKER,
"",
"",
"The service method " + invoker.getInterface().getName() + "." + getMethodSignature(invocation)
+ " is DEPRECATED! Declare from " + invoker.getUrl());
}
}
return invoker.invoke(invocation);
}
private String getMethodSignature(Invocation invocation) {
StringBuilder buf = new StringBuilder(RpcUtils.getMethodName(invocation));
buf.append('(');
Class<?>[] types = invocation.getParameterTypes();
if (types != null && types.length > 0) {
boolean first = true;
for (Class<?> type : types) {
if (first) {
first = false;
} else {
buf.append(", ");
}
buf.append(type.getSimpleName());
}
}
buf.append(')');
return buf.toString();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TokenHeaderFilter.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TokenHeaderFilter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.filter;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.utils.ConfigUtils;
import org.apache.dubbo.rpc.HeaderFilter;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.support.RpcUtils;
import static org.apache.dubbo.rpc.Constants.TOKEN_KEY;
import static org.apache.dubbo.rpc.RpcException.FORBIDDEN_EXCEPTION;
@Activate
public class TokenHeaderFilter implements HeaderFilter {
@Override
public RpcInvocation invoke(Invoker<?> invoker, RpcInvocation invocation) throws RpcException {
String token = invoker.getUrl().getParameter(TOKEN_KEY);
if (ConfigUtils.isNotEmpty(token)) {
Class<?> serviceType = invoker.getInterface();
String remoteToken = (String) invocation.getObjectAttachmentWithoutConvert(TOKEN_KEY);
if (!token.equals(remoteToken)) {
throw new RpcException(
FORBIDDEN_EXCEPTION,
"Forbid invoke remote service " + serviceType + " method " + RpcUtils.getMethodName(invocation)
+ "() from consumer "
+ RpcContext.getServiceContext().getRemoteHost() + " to provider "
+ RpcContext.getServiceContext().getLocalHost()
+ ", consumer incorrect token is " + remoteToken);
}
}
return invocation;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ActiveLimitFilter.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ActiveLimitFilter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.filter;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.RpcStatus;
import org.apache.dubbo.rpc.support.RpcUtils;
import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER;
import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY;
import static org.apache.dubbo.rpc.Constants.ACTIVES_KEY;
/**
* ActiveLimitFilter restrict the concurrent client invocation for a service or service's method from client side.
* To use active limit filter, configured url with <b>actives</b> and provide valid >0 integer value.
* <pre>
* e.g. <dubbo:reference id="demoService" check="false" interface="org.apache.dubbo.demo.DemoService" "actives"="2"/>
* In the above example maximum 2 concurrent invocation is allowed.
* If there are more than configured (in this example 2) is trying to invoke remote method, then rest of invocation
* will wait for configured timeout(default is 0 second) before invocation gets kill by dubbo.
* </pre>
*
* @see Filter
*/
@Activate(group = CONSUMER, value = ACTIVES_KEY)
public class ActiveLimitFilter implements Filter, Filter.Listener {
private static final String ACTIVE_LIMIT_FILTER_START_TIME = "active_limit_filter_start_time";
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
URL url = invoker.getUrl();
String methodName = RpcUtils.getMethodName(invocation);
int max = invoker.getUrl().getMethodParameter(methodName, ACTIVES_KEY, 0);
final RpcStatus rpcStatus = RpcStatus.getStatus(invoker.getUrl(), RpcUtils.getMethodName(invocation));
if (!RpcStatus.beginCount(url, methodName, max)) {
long timeout = invoker.getUrl().getMethodParameter(RpcUtils.getMethodName(invocation), TIMEOUT_KEY, 0);
long start = System.currentTimeMillis();
long remain = timeout;
synchronized (rpcStatus) {
while (!RpcStatus.beginCount(url, methodName, max)) {
try {
rpcStatus.wait(remain);
} catch (InterruptedException e) {
// ignore
}
long elapsed = System.currentTimeMillis() - start;
remain = timeout - elapsed;
if (remain <= 0) {
throw new RpcException(
RpcException.LIMIT_EXCEEDED_EXCEPTION,
"Waiting concurrent invoke timeout in client-side for service: "
+ invoker.getInterface().getName()
+ ", method: " + RpcUtils.getMethodName(invocation) + ", elapsed: "
+ elapsed + ", timeout: " + timeout + ". concurrent invokes: "
+ rpcStatus.getActive()
+ ". max concurrent invoke limit: " + max);
}
}
}
}
invocation.put(ACTIVE_LIMIT_FILTER_START_TIME, System.currentTimeMillis());
return invoker.invoke(invocation);
}
@Override
public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) {
String methodName = RpcUtils.getMethodName(invocation);
URL url = invoker.getUrl();
int max = invoker.getUrl().getMethodParameter(methodName, ACTIVES_KEY, 0);
RpcStatus.endCount(url, methodName, getElapsed(invocation), true);
notifyFinish(RpcStatus.getStatus(url, methodName), max);
}
@Override
public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) {
String methodName = RpcUtils.getMethodName(invocation);
URL url = invoker.getUrl();
int max = invoker.getUrl().getMethodParameter(methodName, ACTIVES_KEY, 0);
if (t instanceof RpcException) {
RpcException rpcException = (RpcException) t;
if (rpcException.isLimitExceed()) {
return;
}
}
RpcStatus.endCount(url, methodName, getElapsed(invocation), false);
notifyFinish(RpcStatus.getStatus(url, methodName), max);
}
private long getElapsed(Invocation invocation) {
Object beginTime = invocation.get(ACTIVE_LIMIT_FILTER_START_TIME);
return beginTime != null ? System.currentTimeMillis() - (Long) beginTime : 0;
}
private void notifyFinish(final RpcStatus rpcStatus, int max) {
if (max > 0) {
synchronized (rpcStatus) {
rpcStatus.notifyAll();
}
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/AccessLogFilter.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/AccessLogFilter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.filter;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository;
import org.apache.dubbo.common.utils.ConcurrentHashMapUtils;
import org.apache.dubbo.common.utils.ConfigUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.common.utils.SystemPropertyConfigUtils;
import org.apache.dubbo.rpc.Constants;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.support.AccessLogData;
import org.apache.dubbo.rpc.support.RpcUtils;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Optional;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER;
import static org.apache.dubbo.common.constants.CommonConstants.SystemProperty.SYSTEM_LINE_SEPARATOR;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FILTER_VALIDATION_EXCEPTION;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.VULNERABILITY_WARNING;
import static org.apache.dubbo.rpc.Constants.ACCESS_LOG_FIXED_PATH_KEY;
/**
* Record access log for the service.
* <p>
* Logger key is <code><b>dubbo.accesslog</b></code>.
* In order to configure access log appear in the specified appender only, additivity need to be configured in log4j's
* config file, for example:
* <code>
* <pre>
* <logger name="<b>dubbo.accesslog</b>" <font color="red">additivity="false"</font>>
* <level value="info" />
* <appender-ref ref="foo" />
* </logger>
* </pre></code>
*/
@Activate(group = PROVIDER)
public class AccessLogFilter implements Filter {
public static ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(AccessLogFilter.class);
private static final String LOG_KEY = "dubbo.accesslog";
private static final int LOG_MAX_BUFFER = 5000;
private static long LOG_OUTPUT_INTERVAL = 5000;
private static final String FILE_DATE_FORMAT = "yyyyMMdd";
// It's safe to declare it as singleton since it runs on single thread only
private final DateFormat fileNameFormatter = new SimpleDateFormat(FILE_DATE_FORMAT);
private final ConcurrentMap<String, Queue<AccessLogData>> logEntries = new ConcurrentHashMap<>();
private final AtomicBoolean scheduled = new AtomicBoolean();
private ScheduledFuture<?> future;
/**
* Default constructor initialize demon thread for writing into access log file with names with access log key
* defined in url <b>accesslog</b>
*/
public AccessLogFilter() {}
/**
* This method logs the access log for service method invocation call.
*
* @param invoker service
* @param inv Invocation service method.
* @return Result from service method.
* @throws RpcException
*/
@Override
public Result invoke(Invoker<?> invoker, Invocation inv) throws RpcException {
String accessLogKey = invoker.getUrl().getParameter(Constants.ACCESS_LOG_KEY);
boolean isFixedPath = invoker.getUrl().getParameter(ACCESS_LOG_FIXED_PATH_KEY, true);
if (StringUtils.isEmpty(accessLogKey) || "false".equalsIgnoreCase(accessLogKey)) {
// Notice that disable accesslog of one service may cause the whole application to stop collecting
// accesslog.
// It's recommended to use application level configuration to enable or disable accesslog if dynamically
// configuration is needed .
if (future != null && !future.isCancelled()) {
future.cancel(true);
logger.info("Access log task cancelled ...");
}
return invoker.invoke(inv);
}
if (scheduled.compareAndSet(false, true)) {
future = inv.getModuleModel()
.getApplicationModel()
.getFrameworkModel()
.getBeanFactory()
.getBean(FrameworkExecutorRepository.class)
.getSharedScheduledExecutor()
.scheduleWithFixedDelay(
new AccesslogRefreshTask(isFixedPath),
LOG_OUTPUT_INTERVAL,
LOG_OUTPUT_INTERVAL,
TimeUnit.MILLISECONDS);
logger.info("Access log task started ...");
}
Optional<AccessLogData> optionalAccessLogData = Optional.empty();
try {
optionalAccessLogData = Optional.of(buildAccessLogData(invoker, inv));
} catch (Throwable t) {
logger.warn(
CONFIG_FILTER_VALIDATION_EXCEPTION,
"",
"",
"Exception in AccessLogFilter of service(" + invoker + " -> " + inv + ")",
t);
}
try {
return invoker.invoke(inv);
} finally {
String finalAccessLogKey = accessLogKey;
optionalAccessLogData.ifPresent(logData -> {
logData.setOutTime(new Date());
log(finalAccessLogKey, logData, isFixedPath);
});
}
}
private void log(String accessLog, AccessLogData accessLogData, boolean isFixedPath) {
Queue<AccessLogData> logQueue =
ConcurrentHashMapUtils.computeIfAbsent(logEntries, accessLog, k -> new ConcurrentLinkedQueue<>());
if (logQueue.size() < LOG_MAX_BUFFER) {
logQueue.add(accessLogData);
} else {
logger.warn(
CONFIG_FILTER_VALIDATION_EXCEPTION,
"",
"",
"AccessLog buffer is full. Do a force writing to file to clear buffer.");
// just write current logSet to file.
writeLogSetToFile(accessLog, logQueue, isFixedPath);
// after force writing, add accessLogData to current logSet
logQueue.add(accessLogData);
}
}
private void writeLogSetToFile(String accessLog, Queue<AccessLogData> logSet, boolean isFixedPath) {
try {
if (ConfigUtils.isDefault(accessLog)) {
processWithServiceLogger(logSet);
} else {
if (isFixedPath) {
logger.warn(
VULNERABILITY_WARNING,
"Change of accesslog file path not allowed. ",
"",
"Will write to the default location, \" +\n"
+ " \"please enable this feature by setting 'accesslog.fixed.path=true' and restart the process. \" +\n"
+ " \"We highly recommend to not enable this feature in production for security concerns, \" +\n"
+ " \"please be fully aware of the potential risks before doing so!");
processWithServiceLogger(logSet);
} else {
logger.warn(
VULNERABILITY_WARNING,
"Accesslog file path changed to " + accessLog + ", be aware of possible vulnerabilities!",
"",
"");
File file = new File(accessLog);
createIfLogDirAbsent(file);
if (logger.isDebugEnabled()) {
logger.debug("Append log to " + accessLog);
}
renameFile(file);
processWithAccessKeyLogger(logSet, file);
}
}
} catch (Exception e) {
logger.error(CONFIG_FILTER_VALIDATION_EXCEPTION, "", "", e.getMessage(), e);
}
}
private void processWithAccessKeyLogger(Queue<AccessLogData> logQueue, File file) throws IOException {
FileWriter writer = new FileWriter(file, true);
try {
while (!logQueue.isEmpty()) {
writer.write(logQueue.poll().getLogMessage());
writer.write(SystemPropertyConfigUtils.getSystemProperty(SYSTEM_LINE_SEPARATOR));
}
} finally {
writer.flush();
writer.close();
}
}
private AccessLogData buildAccessLogData(Invoker<?> invoker, Invocation inv) {
AccessLogData logData = AccessLogData.newLogData();
logData.setServiceName(invoker.getInterface().getName());
logData.setMethodName(RpcUtils.getMethodName(inv));
logData.setVersion(invoker.getUrl().getVersion());
logData.setGroup(invoker.getUrl().getGroup());
logData.setInvocationTime(new Date());
logData.setTypes(inv.getParameterTypes());
logData.setArguments(inv.getArguments());
return logData;
}
private void processWithServiceLogger(Queue<AccessLogData> logQueue) {
while (!logQueue.isEmpty()) {
AccessLogData logData = logQueue.poll();
LoggerFactory.getLogger(LOG_KEY + "." + logData.getServiceName()).info(logData.getLogMessage());
}
}
private void createIfLogDirAbsent(File file) {
File dir = file.getParentFile();
if (null != dir && !dir.exists()) {
dir.mkdirs();
}
}
private void renameFile(File file) {
if (file.exists()) {
String now = fileNameFormatter.format(new Date());
String last = fileNameFormatter.format(new Date(file.lastModified()));
if (!now.equals(last)) {
File archive = new File(file.getAbsolutePath() + "." + now);
file.renameTo(archive);
}
}
}
class AccesslogRefreshTask implements Runnable {
private final boolean isFixedPath;
public AccesslogRefreshTask(boolean isFixedPath) {
this.isFixedPath = isFixedPath;
}
@Override
public void run() {
if (!AccessLogFilter.this.logEntries.isEmpty()) {
for (Map.Entry<String, Queue<AccessLogData>> entry : AccessLogFilter.this.logEntries.entrySet()) {
String accessLog = entry.getKey();
Queue<AccessLogData> logSet = entry.getValue();
writeLogSetToFile(accessLog, logSet, isFixedPath);
}
}
}
}
// test purpose only
public static void setInterval(long interval) {
LOG_OUTPUT_INTERVAL = interval;
}
// test purpose only
public static long getInterval() {
return LOG_OUTPUT_INTERVAL;
}
// test purpose only
public void destroy() {
future.cancel(true);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/CompatibleFilter.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/CompatibleFilter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.filter;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.CompatibleTypeUtils;
import org.apache.dubbo.common.utils.PojoUtils;
import org.apache.dubbo.remoting.utils.UrlUtils;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FILTER_VALIDATION_EXCEPTION;
/**
* CompatibleFilter make the remote method's return value compatible to invoker's version of object.
* To make return object compatible it does
* <pre>
* 1)If the url contain serialization key of type <b>json</b> or <b>fastjson</b> then transform
* the return value to instance of {@link java.util.Map}
* 2)If the return value is not a instance of invoked method's return type available at
* local jvm then POJO conversion.
* 3)If return value is other than above return value as it is.
* </pre>
*
* @see Filter
*/
@Deprecated
public class CompatibleFilter implements Filter, Filter.Listener {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(CompatibleFilter.class);
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
return invoker.invoke(invocation);
}
@Override
public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) {
if (!invocation.getMethodName().startsWith("$") && !appResponse.hasException()) {
Object value = appResponse.getValue();
if (value != null) {
try {
Method method = invoker.getInterface()
.getMethod(invocation.getMethodName(), invocation.getParameterTypes());
Class<?> type = method.getReturnType();
Object newValue;
String serialization = UrlUtils.serializationOrDefault(invoker.getUrl());
if ("json".equals(serialization) || "fastjson".equals(serialization)) {
// If the serialization key is json or fastjson
Type gtype = method.getGenericReturnType();
newValue = PojoUtils.realize(value, type, gtype);
} else if (!type.isInstance(value)) {
// if local service interface's method's return type is not instance of return value
newValue = PojoUtils.isPojo(type)
? PojoUtils.realize(value, type)
: CompatibleTypeUtils.compatibleTypeConvert(value, type);
} else {
newValue = value;
}
if (newValue != value) {
appResponse.setValue(newValue);
}
} catch (Throwable t) {
logger.warn(CONFIG_FILTER_VALIDATION_EXCEPTION, "", "", t.getMessage(), t);
}
}
}
}
@Override
public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) {}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/EchoFilter.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/EchoFilter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.filter;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.AsyncRpcResult;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import static org.apache.dubbo.rpc.Constants.$ECHO;
/**
* Dubbo provided default Echo echo service, which is available for all dubbo provider service interface.
*/
@Activate(group = CommonConstants.PROVIDER, order = -110000)
public class EchoFilter implements Filter {
@Override
public Result invoke(Invoker<?> invoker, Invocation inv) throws RpcException {
if (inv.getMethodName().equals($ECHO) && inv.getArguments() != null && inv.getArguments().length == 1) {
return AsyncRpcResult.newDefaultAsyncResult(inv.getArguments()[0], inv);
}
return invoker.invoke(inv);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/AdaptiveLoadBalanceFilter.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/AdaptiveLoadBalanceFilter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.filter;
import org.apache.dubbo.common.constants.LoadbalanceRules;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.resource.GlobalResourcesRepository;
import org.apache.dubbo.common.threadlocal.NamedInternalThreadFactory;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.AdaptiveMetrics;
import org.apache.dubbo.rpc.Constants;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN;
import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER;
import static org.apache.dubbo.common.constants.CommonConstants.LOADBALANCE_KEY;
/**
* if the load balance is adaptive ,set attachment to get the metrics of the server
* @see Filter
* @see org.apache.dubbo.rpc.RpcContext
*/
@Activate(
group = CONSUMER,
order = -200000,
value = {"loadbalance:adaptive"})
public class AdaptiveLoadBalanceFilter implements Filter, Filter.Listener {
/**
* uses a single worker thread operating off an bounded queue
*/
private volatile ThreadPoolExecutor executor = null;
private final AdaptiveMetrics adaptiveMetrics;
public AdaptiveLoadBalanceFilter(ApplicationModel scopeModel) {
adaptiveMetrics = scopeModel.getBeanFactory().getBean(AdaptiveMetrics.class);
}
private ThreadPoolExecutor getExecutor() {
if (null == executor) {
synchronized (this) {
if (null == executor) {
executor = new ThreadPoolExecutor(
1,
1,
0L,
TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>(1024),
new NamedInternalThreadFactory("Dubbo-framework-loadbalance-adaptive", true),
new ThreadPoolExecutor.DiscardOldestPolicy());
GlobalResourcesRepository.getInstance().registerDisposable(() -> this.executor.shutdown());
}
}
}
return executor;
}
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
return invoker.invoke(invocation);
}
private String buildServiceKey(Invocation invocation) {
StringBuilder sb = new StringBuilder(128);
sb.append(invocation.getInvoker().getUrl().getAddress()).append(":").append(invocation.getProtocolServiceKey());
return sb.toString();
}
private String getServiceKey(Invocation invocation) {
String key = (String) invocation.getAttributes().get(invocation.getInvoker());
if (StringUtils.isNotEmpty(key)) {
return key;
}
key = buildServiceKey(invocation);
invocation.getAttributes().put(invocation.getInvoker(), key);
return key;
}
@Override
public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) {
try {
String loadBalance = (String) invocation.getAttributes().get(LOADBALANCE_KEY);
if (StringUtils.isEmpty(loadBalance) || !LoadbalanceRules.ADAPTIVE.equals(loadBalance)) {
return;
}
adaptiveMetrics.addConsumerSuccess(getServiceKey(invocation));
String attachment = appResponse.getAttachment(Constants.ADAPTIVE_LOADBALANCE_ATTACHMENT_KEY);
if (StringUtils.isNotEmpty(attachment)) {
String[] parties = COMMA_SPLIT_PATTERN.split(attachment);
if (parties.length == 0) {
return;
}
Map<String, String> metricsMap = new HashMap<>();
for (String party : parties) {
String[] groups = party.split(":");
if (groups.length != 2) {
continue;
}
metricsMap.put(groups[0], groups[1]);
}
Long startTime = (Long) invocation.getAttributes().get(Constants.ADAPTIVE_LOADBALANCE_START_TIME);
if (null != startTime) {
metricsMap.put("rt", String.valueOf(System.currentTimeMillis() - startTime));
}
getExecutor().execute(() -> {
adaptiveMetrics.setProviderMetrics(getServiceKey(invocation), metricsMap);
});
}
} finally {
appResponse.getAttachments().remove(Constants.ADAPTIVE_LOADBALANCE_ATTACHMENT_KEY);
}
}
@Override
public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) {
String loadBalance = (String) invocation.getAttributes().get(LOADBALANCE_KEY);
if (StringUtils.isNotEmpty(loadBalance) && LoadbalanceRules.ADAPTIVE.equals(loadBalance)) {
getExecutor().execute(() -> {
adaptiveMetrics.addErrorReq(getServiceKey(invocation));
});
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ExceptionFilter.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ExceptionFilter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.filter;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.extension.DisableInject;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.ReflectUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.service.GenericService;
import org.apache.dubbo.rpc.support.RpcUtils;
import java.lang.reflect.Method;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FILTER_VALIDATION_EXCEPTION;
/**
* ExceptionInvokerFilter
* <p>
* Functions:
* <ol>
* <li>unexpected exception will be logged in ERROR level on provider side. Unexpected exception are unchecked
* exception not declared on the interface</li>
* <li>Wrap the exception not introduced in API package into RuntimeException. Framework will serialize the outer exception but stringnize its cause in order to avoid of possible serialization problem on client side</li>
* </ol>
*/
@Activate(group = CommonConstants.PROVIDER)
public class ExceptionFilter implements Filter, Filter.Listener {
private ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ExceptionFilter.class);
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
return invoker.invoke(invocation);
}
@Override
public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) {
if (appResponse.hasException() && GenericService.class != invoker.getInterface()) {
try {
Throwable exception = appResponse.getException();
// directly throw if it's checked exception
if (!(exception instanceof RuntimeException) && (exception instanceof Exception)) {
return;
}
// directly throw if the exception appears in the signature
try {
Method method = invoker.getInterface()
.getMethod(RpcUtils.getMethodName(invocation), invocation.getParameterTypes());
Class<?>[] exceptionClasses = method.getExceptionTypes();
for (Class<?> exceptionClass : exceptionClasses) {
if (exception.getClass().equals(exceptionClass)) {
return;
}
}
} catch (NoSuchMethodException e) {
return;
}
// for the exception not found in method's signature, print ERROR message in server's log.
logger.error(
CONFIG_FILTER_VALIDATION_EXCEPTION,
"",
"",
"Got unchecked and undeclared exception which called by "
+ RpcContext.getServiceContext().getRemoteHost() + ". service: "
+ invoker.getInterface().getName() + ", method: " + RpcUtils.getMethodName(invocation)
+ ", exception: "
+ exception.getClass().getName() + ": " + exception.getMessage(),
exception);
// directly throw if exception class and interface class are in the same jar file.
String serviceFile = ReflectUtils.getCodeBase(invoker.getInterface());
String exceptionFile = ReflectUtils.getCodeBase(exception.getClass());
if (serviceFile == null || exceptionFile == null || serviceFile.equals(exceptionFile)) {
return;
}
// directly throw if it's JDK exception
String className = exception.getClass().getName();
if (className.startsWith("java.")
|| className.startsWith("javax.")
|| className.startsWith("jakarta.")) {
return;
}
// directly throw if it's dubbo exception
if (exception instanceof RpcException) {
return;
}
// otherwise, wrap with RuntimeException and throw back to the client
appResponse.setException(new RuntimeException(StringUtils.toString(exception)));
} catch (Throwable e) {
logger.warn(
CONFIG_FILTER_VALIDATION_EXCEPTION,
"",
"",
"Fail to ExceptionFilter when called by "
+ RpcContext.getServiceContext().getRemoteHost() + ". service: "
+ invoker.getInterface().getName() + ", method: " + RpcUtils.getMethodName(invocation)
+ ", exception: "
+ e.getClass().getName() + ": " + e.getMessage(),
e);
}
}
}
@Override
public void onError(Throwable e, Invoker<?> invoker, Invocation invocation) {
logger.error(
CONFIG_FILTER_VALIDATION_EXCEPTION,
"",
"",
"Got unchecked and undeclared exception which called by "
+ RpcContext.getServiceContext().getRemoteHost() + ". service: "
+ invoker.getInterface().getName() + ", method: " + RpcUtils.getMethodName(invocation)
+ ", exception: "
+ e.getClass().getName() + ": " + e.getMessage(),
e);
}
// For test purpose
@DisableInject
public void mockLogger(ErrorTypeAwareLogger logger) {
this.logger = logger;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/RpcExceptionFilter.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/RpcExceptionFilter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.filter;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
/**
* RpcExceptionFilter
* <p>
* Functions:
* <ol>
* <li> The RpcException will be rethrown on consumer side.</li>
* </ol>
*/
@Activate(group = CommonConstants.CONSUMER)
public class RpcExceptionFilter implements Filter, Filter.Listener {
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
return invoker.invoke(invocation);
}
@Override
public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) {
if (appResponse.hasException()) {
Throwable exception = appResponse.getException();
// directly throw if it's RpcException
if ((exception instanceof RpcException)) {
throw (RpcException) exception;
}
}
}
@Override
public void onError(Throwable e, Invoker<?> invoker, Invocation invocation) {}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TimeoutFilter.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TimeoutFilter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.filter;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.TimeoutCountDown;
import org.apache.dubbo.rpc.support.RpcUtils;
import static org.apache.dubbo.common.constants.CommonConstants.TIME_COUNTDOWN_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROXY_TIMEOUT_REQUEST;
/**
* Log any invocation timeout, but don't stop server from running
*/
@Activate(group = CommonConstants.PROVIDER)
public class TimeoutFilter implements Filter, Filter.Listener {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(TimeoutFilter.class);
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
return invoker.invoke(invocation);
}
@Override
public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) {
Object obj = RpcContext.getServerAttachment().getObjectAttachment(TIME_COUNTDOWN_KEY);
if (obj != null) {
TimeoutCountDown countDown = (TimeoutCountDown) obj;
if (countDown.isExpired()) {
if (logger.isWarnEnabled()) {
logger.warn(
PROXY_TIMEOUT_REQUEST,
"",
"",
"invoke timed out. method: " + RpcUtils.getMethodName(invocation) + " url is "
+ invoker.getUrl() + ", invoke elapsed " + countDown.elapsedMillis() + " ms.");
}
}
}
}
@Override
public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) {}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TpsLimitFilter.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TpsLimitFilter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.filter;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.AsyncRpcResult;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.filter.tps.DefaultTPSLimiter;
import org.apache.dubbo.rpc.filter.tps.TPSLimiter;
import org.apache.dubbo.rpc.support.RpcUtils;
import static org.apache.dubbo.rpc.Constants.TPS_LIMIT_RATE_KEY;
/**
* TpsLimitFilter limit the TPS (transaction per second) for all method of a service or a particular method.
* Service or method url can define <b>tps</b> or <b>tps.interval</b> to control this control.It use {@link DefaultTPSLimiter}
* as it limit checker. If a provider service method is configured with <b>tps</b>(optionally with <b>tps.interval</b>),then
* if invocation count exceed the configured <b>tps</b> value (default is -1 which means unlimited) then invocation will get
* RpcException.
*/
@Activate(group = CommonConstants.PROVIDER, value = TPS_LIMIT_RATE_KEY)
public class TpsLimitFilter implements Filter {
private final TPSLimiter tpsLimiter = new DefaultTPSLimiter();
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
if (!tpsLimiter.isAllowable(invoker.getUrl(), invocation)) {
return AsyncRpcResult.newDefaultAsyncResult(
new RpcException(
"Failed to invoke service " + invoker.getInterface().getName() + "."
+ RpcUtils.getMethodName(invocation) + " because exceed max service tps."),
invocation);
}
return invoker.invoke(invocation);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericFilter.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericFilter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.filter;
import org.apache.dubbo.common.beanutil.JavaBeanAccessor;
import org.apache.dubbo.common.beanutil.JavaBeanDescriptor;
import org.apache.dubbo.common.beanutil.JavaBeanSerializeUtil;
import org.apache.dubbo.common.compact.Dubbo2CompactUtils;
import org.apache.dubbo.common.compact.Dubbo2GenericExceptionUtils;
import org.apache.dubbo.common.config.Configuration;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.constants.LoggerCodeConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.io.UnsafeByteArrayInputStream;
import org.apache.dubbo.common.io.UnsafeByteArrayOutputStream;
import org.apache.dubbo.common.json.GsonUtils;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.serialize.Serialization;
import org.apache.dubbo.common.utils.ClassUtils;
import org.apache.dubbo.common.utils.PojoUtils;
import org.apache.dubbo.common.utils.ReflectUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.MethodDescriptor;
import org.apache.dubbo.rpc.model.ScopeModelAware;
import org.apache.dubbo.rpc.model.ServiceModel;
import org.apache.dubbo.rpc.service.GenericException;
import org.apache.dubbo.rpc.service.GenericService;
import org.apache.dubbo.rpc.support.ProtocolUtils;
import java.io.IOException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.IntStream;
import static org.apache.dubbo.common.constants.CommonConstants.$INVOKE;
import static org.apache.dubbo.common.constants.CommonConstants.$INVOKE_ASYNC;
import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_SERIALIZATION_BEAN;
import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_SERIALIZATION_NATIVE_JAVA;
import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_SERIALIZATION_PROTOBUF;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FILTER_VALIDATION_EXCEPTION;
import static org.apache.dubbo.rpc.Constants.GENERIC_KEY;
/**
* GenericInvokerFilter.
*/
@Activate(group = CommonConstants.PROVIDER, order = -20000)
public class GenericFilter implements Filter, Filter.Listener, ScopeModelAware {
private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(GenericFilter.class);
private ApplicationModel applicationModel;
private final Map<ClassLoader, Map<String, Class<?>>> classCache = new ConcurrentHashMap<>();
@Override
public void setApplicationModel(ApplicationModel applicationModel) {
this.applicationModel = applicationModel;
}
@Override
public Result invoke(Invoker<?> invoker, Invocation inv) throws RpcException {
if ((inv.getMethodName().equals($INVOKE) || inv.getMethodName().equals($INVOKE_ASYNC))
&& inv.getArguments() != null
&& inv.getArguments().length == 3
&& !GenericService.class.isAssignableFrom(invoker.getInterface())) {
String name = ((String) inv.getArguments()[0]).trim();
String[] types = (String[]) inv.getArguments()[1];
Object[] args = (Object[]) inv.getArguments()[2];
try {
Method method = findMethodByMethodSignature(invoker.getInterface(), name, types, inv.getServiceModel());
Class<?>[] params = method.getParameterTypes();
if (args == null) {
args = new Object[params.length];
}
if (types == null) {
types = new String[params.length];
}
if (args.length != types.length) {
throw new RpcException(
"GenericFilter#invoke args.length != types.length, please check your " + "params");
}
String generic = inv.getAttachment(GENERIC_KEY);
if (StringUtils.isBlank(generic)) {
generic = getGenericValueFromRpcContext();
}
if (StringUtils.isEmpty(generic)
|| ProtocolUtils.isDefaultGenericSerialization(generic)
|| ProtocolUtils.isGenericReturnRawResult(generic)) {
try {
args = PojoUtils.realize(args, params, method.getGenericParameterTypes());
} catch (Exception e) {
logger.error(
LoggerCodeConstants.PROTOCOL_ERROR_DESERIALIZE,
"",
"",
"Deserialize generic invocation failed. ServiceKey: "
+ inv.getTargetServiceUniqueName(),
e);
throw new RpcException(e);
}
} else if (ProtocolUtils.isGsonGenericSerialization(generic)) {
args = getGsonGenericArgs(args, method.getGenericParameterTypes());
} else if (ProtocolUtils.isJavaGenericSerialization(generic)) {
Configuration configuration = ApplicationModel.ofNullable(applicationModel)
.modelEnvironment()
.getConfiguration();
if (!configuration.getBoolean(CommonConstants.ENABLE_NATIVE_JAVA_GENERIC_SERIALIZE, false)) {
String notice = "Trigger the safety barrier! "
+ "Native Java Serializer is not allowed by default."
+ "This means currently maybe being attacking by others. "
+ "If you are sure this is a mistake, "
+ "please set `"
+ CommonConstants.ENABLE_NATIVE_JAVA_GENERIC_SERIALIZE + "` enable in configuration! "
+ "Before doing so, please make sure you have configure JEP290 to prevent serialization attack.";
logger.error(CONFIG_FILTER_VALIDATION_EXCEPTION, "", "", notice);
throw new RpcException(new IllegalStateException(notice));
}
for (int i = 0; i < args.length; i++) {
if (byte[].class == args[i].getClass()) {
try (UnsafeByteArrayInputStream is = new UnsafeByteArrayInputStream((byte[]) args[i])) {
args[i] = applicationModel
.getExtensionLoader(Serialization.class)
.getExtension(GENERIC_SERIALIZATION_NATIVE_JAVA)
.deserialize(null, is)
.readObject();
} catch (Exception e) {
throw new RpcException("Deserialize argument [" + (i + 1) + "] failed.", e);
}
} else {
throw new RpcException("Generic serialization [" + GENERIC_SERIALIZATION_NATIVE_JAVA
+ "] only support message type "
+ byte[].class
+ " and your message type is "
+ args[i].getClass());
}
}
} else if (ProtocolUtils.isBeanGenericSerialization(generic)) {
for (int i = 0; i < args.length; i++) {
if (args[i] != null) {
if (args[i] instanceof JavaBeanDescriptor) {
args[i] = JavaBeanSerializeUtil.deserialize((JavaBeanDescriptor) args[i]);
} else {
throw new RpcException("Generic serialization [" + GENERIC_SERIALIZATION_BEAN
+ "] only support message type "
+ JavaBeanDescriptor.class.getName()
+ " and your message type is "
+ args[i].getClass().getName());
}
}
}
} else if (ProtocolUtils.isProtobufGenericSerialization(generic)) {
// as proto3 only accept one protobuf parameter
if (args.length == 1 && args[0] instanceof String) {
try (UnsafeByteArrayInputStream is =
new UnsafeByteArrayInputStream(((String) args[0]).getBytes(StandardCharsets.UTF_8))) {
args[0] = applicationModel
.getExtensionLoader(Serialization.class)
.getExtension(GENERIC_SERIALIZATION_PROTOBUF)
.deserialize(null, is)
.readObject(method.getParameterTypes()[0]);
} catch (Exception e) {
throw new RpcException("Deserialize argument failed.", e);
}
} else {
throw new RpcException("Generic serialization [" + GENERIC_SERIALIZATION_PROTOBUF
+ "] only support one "
+ String.class.getName() + " argument and your message size is "
+ args.length
+ " and type is" + args[0].getClass().getName());
}
}
RpcInvocation rpcInvocation = new RpcInvocation(
inv.getTargetServiceUniqueName(),
invoker.getUrl().getServiceModel(),
method.getName(),
invoker.getInterface().getName(),
invoker.getUrl().getProtocolServiceKey(),
method.getParameterTypes(),
args,
inv.getObjectAttachments(),
inv.getInvoker(),
inv.getAttributes(),
inv instanceof RpcInvocation ? ((RpcInvocation) inv).getInvokeMode() : null);
return invoker.invoke(rpcInvocation);
} catch (NoSuchMethodException | ClassNotFoundException e) {
throw new RpcException(e.getMessage(), e);
}
}
return invoker.invoke(inv);
}
private Object[] getGsonGenericArgs(final Object[] args, Type[] types) {
return IntStream.range(0, args.length)
.mapToObj(i -> {
if (args[i] == null) {
return null;
}
if (!(args[i] instanceof String)) {
throw new RpcException(
"When using GSON to deserialize generic dubbo request arguments, the arguments must be of type String");
}
String str = args[i].toString();
try {
return GsonUtils.fromJson(str, types[i]);
} catch (RuntimeException ex) {
throw new RpcException(ex.getMessage());
}
})
.toArray();
}
private String getGenericValueFromRpcContext() {
String generic = RpcContext.getServerAttachment().getAttachment(GENERIC_KEY);
if (StringUtils.isBlank(generic)) {
generic = RpcContext.getClientAttachment().getAttachment(GENERIC_KEY);
}
return generic;
}
public Method findMethodByMethodSignature(
Class<?> clazz, String methodName, String[] parameterTypes, ServiceModel serviceModel)
throws NoSuchMethodException, ClassNotFoundException {
Method method;
if (parameterTypes == null) {
List<Method> found = new ArrayList<>();
for (Method m : clazz.getMethods()) {
if (m.getName().equals(methodName)) {
found.add(m);
}
}
if (found.isEmpty()) {
throw new NoSuchMethodException("No such method " + methodName + " in class " + clazz);
}
if (found.size() > 1) {
String msg = String.format(
"Not unique method for method name(%s) in class(%s), find %d methods.",
methodName, clazz.getName(), found.size());
throw new IllegalStateException(msg);
}
method = found.get(0);
} else {
Class<?>[] types = new Class<?>[parameterTypes.length];
for (int i = 0; i < parameterTypes.length; i++) {
ClassLoader classLoader = ClassUtils.getClassLoader();
Map<String, Class<?>> cacheMap = classCache.get(classLoader);
if (cacheMap == null) {
cacheMap = new ConcurrentHashMap<>();
classCache.putIfAbsent(classLoader, cacheMap);
cacheMap = classCache.get(classLoader);
}
types[i] = cacheMap.get(parameterTypes[i]);
if (types[i] == null) {
types[i] = ReflectUtils.name2class(parameterTypes[i]);
cacheMap.put(parameterTypes[i], types[i]);
}
}
if (serviceModel != null) {
MethodDescriptor methodDescriptor =
serviceModel.getServiceModel().getMethod(methodName, types);
if (methodDescriptor == null) {
throw new NoSuchMethodException("No such method " + methodName + " in class " + clazz);
}
method = methodDescriptor.getMethod();
} else {
method = clazz.getMethod(methodName, types);
}
}
return method;
}
@Override
public void onResponse(Result appResponse, Invoker<?> invoker, Invocation inv) {
if ((inv.getMethodName().equals($INVOKE) || inv.getMethodName().equals($INVOKE_ASYNC))
&& inv.getArguments() != null
&& inv.getArguments().length == 3
&& !GenericService.class.isAssignableFrom(invoker.getInterface())) {
String generic = inv.getAttachment(GENERIC_KEY);
if (StringUtils.isBlank(generic)) {
generic = getGenericValueFromRpcContext();
}
if (appResponse.hasException()
&& Dubbo2CompactUtils.isEnabled()
&& Dubbo2GenericExceptionUtils.isGenericExceptionClassLoaded()) {
Throwable appException = appResponse.getException();
if (appException instanceof GenericException) {
GenericException tmp = (GenericException) appException;
GenericException recreated = Dubbo2GenericExceptionUtils.newGenericException(
tmp.getMessage(), tmp.getCause(), tmp.getExceptionClass(), tmp.getExceptionMessage());
if (recreated != null) {
appException = recreated;
}
appException.setStackTrace(tmp.getStackTrace());
}
if (!(Dubbo2GenericExceptionUtils.getGenericExceptionClass()
.isAssignableFrom(appException.getClass()))) {
GenericException recreated = Dubbo2GenericExceptionUtils.newGenericException(appException);
if (recreated != null) {
appException = recreated;
}
}
appResponse.setException(appException);
}
if (ProtocolUtils.isGenericReturnRawResult(generic)) {
return;
}
if (ProtocolUtils.isJavaGenericSerialization(generic)) {
try {
UnsafeByteArrayOutputStream os = new UnsafeByteArrayOutputStream(512);
applicationModel
.getExtensionLoader(Serialization.class)
.getExtension(GENERIC_SERIALIZATION_NATIVE_JAVA)
.serialize(null, os)
.writeObject(appResponse.getValue());
appResponse.setValue(os.toByteArray());
} catch (IOException e) {
throw new RpcException(
"Generic serialization [" + GENERIC_SERIALIZATION_NATIVE_JAVA
+ "] serialize result failed.",
e);
}
} else if (ProtocolUtils.isBeanGenericSerialization(generic)) {
appResponse.setValue(JavaBeanSerializeUtil.serialize(appResponse.getValue(), JavaBeanAccessor.METHOD));
} else if (ProtocolUtils.isProtobufGenericSerialization(generic)) {
try {
UnsafeByteArrayOutputStream os = new UnsafeByteArrayOutputStream(512);
applicationModel
.getExtensionLoader(Serialization.class)
.getExtension(GENERIC_SERIALIZATION_PROTOBUF)
.serialize(null, os)
.writeObject(appResponse.getValue());
appResponse.setValue(os.toString());
} catch (IOException e) {
throw new RpcException(
"Generic serialization [" + GENERIC_SERIALIZATION_PROTOBUF + "] serialize result failed.",
e);
}
} else if (ProtocolUtils.isGsonGenericSerialization(generic)) {
appResponse.setValue(GsonUtils.toJson(appResponse.getValue()));
} else {
appResponse.setValue(PojoUtils.generalize(appResponse.getValue()));
}
}
}
@Override
public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) {}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ProfilerServerFilter.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ProfilerServerFilter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.filter;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.profiler.Profiler;
import org.apache.dubbo.common.profiler.ProfilerEntry;
import org.apache.dubbo.common.profiler.ProfilerSwitch;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.BaseFilter;
import org.apache.dubbo.rpc.Constants;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.support.RpcUtils;
import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SEPARATOR;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT;
import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER;
import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROXY_TIMEOUT_RESPONSE;
@Activate(group = PROVIDER, order = Integer.MIN_VALUE)
public class ProfilerServerFilter implements Filter, BaseFilter.Listener {
private static final String CLIENT_IP_KEY = "client_ip";
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(ProfilerServerFilter.class);
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
if (ProfilerSwitch.isEnableSimpleProfiler()) {
ProfilerEntry bizProfiler;
Object localInvokeProfiler = invocation.get(Profiler.PROFILER_KEY);
if (localInvokeProfiler instanceof ProfilerEntry) {
bizProfiler = Profiler.enter(
(ProfilerEntry) localInvokeProfiler, "Receive request. Local server invoke begin.");
} else {
bizProfiler = Profiler.start("Receive request. Server invoke begin.");
}
invocation.put(Profiler.PROFILER_KEY, bizProfiler);
invocation.put(CLIENT_IP_KEY, RpcContext.getServiceContext().getRemoteAddressString());
}
return invoker.invoke(invocation);
}
@Override
public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) {
afterInvoke(invoker, invocation);
addAdaptiveResponse(appResponse, invocation);
}
@Override
public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) {
afterInvoke(invoker, invocation);
}
private void afterInvoke(Invoker<?> invoker, Invocation invocation) {
if (ProfilerSwitch.isEnableSimpleProfiler()) {
Object fromInvocation = invocation.get(Profiler.PROFILER_KEY);
if (fromInvocation instanceof ProfilerEntry) {
ProfilerEntry profiler = Profiler.release((ProfilerEntry) fromInvocation);
invocation.put(Profiler.PROFILER_KEY, profiler);
dumpIfNeed(invoker, invocation, (ProfilerEntry) fromInvocation);
}
}
}
private void addAdaptiveResponse(Result appResponse, Invocation invocation) {
String adaptiveLoadAttachment = invocation.getAttachment(Constants.ADAPTIVE_LOADBALANCE_ATTACHMENT_KEY);
if (StringUtils.isNotEmpty(adaptiveLoadAttachment)) {
OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
StringBuilder sb = new StringBuilder(64);
sb.append("curTime:").append(System.currentTimeMillis());
sb.append(COMMA_SEPARATOR)
.append("load:")
.append(operatingSystemMXBean.getSystemLoadAverage()
* 100
/ operatingSystemMXBean.getAvailableProcessors());
appResponse.setAttachment(Constants.ADAPTIVE_LOADBALANCE_ATTACHMENT_KEY, sb.toString());
}
}
private void dumpIfNeed(Invoker<?> invoker, Invocation invocation, ProfilerEntry profiler) {
Long timeout = RpcUtils.convertToNumber(invocation.getObjectAttachmentWithoutConvert(TIMEOUT_KEY));
if (timeout == null) {
timeout = (long) invoker.getUrl()
.getMethodPositiveParameter(RpcUtils.getMethodName(invocation), TIMEOUT_KEY, DEFAULT_TIMEOUT);
}
long usage = profiler.getEndTime() - profiler.getStartTime();
if (((usage / (1000_000L * ProfilerSwitch.getWarnPercent())) > timeout) && timeout != -1) {
StringBuilder attachment = new StringBuilder();
invocation.foreachAttachment((entry) -> {
attachment
.append(entry.getKey())
.append("=")
.append(entry.getValue())
.append(";\n");
});
logger.warn(
PROXY_TIMEOUT_RESPONSE,
"",
"",
String.format(
"[Dubbo-Provider] execute service %s#%s cost %d.%06d ms, this invocation almost (maybe already) timeout. Timeout: %dms\n"
+ "client: %s\n"
+ "invocation context:\n%s"
+ "thread info: \n%s",
invocation.getTargetServiceUniqueName(),
RpcUtils.getMethodName(invocation),
usage / 1000_000,
usage % 1000_000,
timeout,
invocation.get(CLIENT_IP_KEY),
attachment,
Profiler.buildDetail(profiler)));
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/tps/StatItem.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/tps/StatItem.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.filter.tps;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
/**
* Judge whether a particular invocation of service provider method should be allowed within a configured time interval.
* As a state it contain name of key ( e.g. method), last invocation time, interval and rate count.
*/
class StatItem {
private final String name;
private final AtomicLong lastResetTime;
private final long interval;
private final AtomicInteger token;
private final int rate;
StatItem(String name, int rate, long interval) {
this.name = name;
this.rate = rate;
this.interval = interval;
this.lastResetTime = new AtomicLong(System.currentTimeMillis());
this.token = new AtomicInteger(rate);
}
public boolean isAllowable() {
long now = System.currentTimeMillis();
if (now > lastResetTime.get() + interval) {
token.set(rate);
lastResetTime.set(now);
}
return token.decrementAndGet() >= 0;
}
public long getInterval() {
return interval;
}
public int getRate() {
return rate;
}
long getLastResetTime() {
return lastResetTime.get();
}
int getToken() {
return token.get();
}
@Override
public String toString() {
return "StatItem " + "[name=" + name + ", " + "rate = " + rate + ", " + "interval = " + interval + ']';
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/tps/DefaultTPSLimiter.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/tps/DefaultTPSLimiter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.filter.tps;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.support.RpcUtils;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import static org.apache.dubbo.rpc.Constants.DEFAULT_TPS_LIMIT_INTERVAL;
import static org.apache.dubbo.rpc.Constants.TPS_LIMIT_INTERVAL_KEY;
import static org.apache.dubbo.rpc.Constants.TPS_LIMIT_RATE_KEY;
/**
* DefaultTPSLimiter is a default implementation for tps filter. It is an in memory based implementation for storing
* tps information. It internally use
*
* @see org.apache.dubbo.rpc.filter.TpsLimitFilter
*/
public class DefaultTPSLimiter implements TPSLimiter {
private final ConcurrentMap<String, StatItem> stats = new ConcurrentHashMap<>();
@Override
public boolean isAllowable(URL url, Invocation invocation) {
boolean isMethodLevelTpsConfigured =
url.hasMethodParameter(RpcUtils.getMethodName(invocation), TPS_LIMIT_RATE_KEY);
String key = isMethodLevelTpsConfigured
? url.getServiceKey() + "#" + RpcUtils.getMethodName(invocation)
: url.getServiceKey();
int rate = url.getMethodParameter(RpcUtils.getMethodName(invocation), TPS_LIMIT_RATE_KEY, -1);
long interval = url.getMethodParameter(
RpcUtils.getMethodName(invocation), TPS_LIMIT_INTERVAL_KEY, DEFAULT_TPS_LIMIT_INTERVAL);
if (rate > 0) {
StatItem statItem = stats.get(key);
if (statItem == null) {
stats.putIfAbsent(key, new StatItem(key, rate, interval));
statItem = stats.get(key);
} else {
// rate or interval has changed, rebuild
if (statItem.getRate() != rate || statItem.getInterval() != interval) {
stats.put(key, new StatItem(key, rate, interval));
statItem = stats.get(key);
}
}
return statItem.isAllowable();
} else {
StatItem statItem = stats.get(key);
if (statItem != null) {
stats.remove(key);
}
}
return true;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/tps/TPSLimiter.java | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/tps/TPSLimiter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.filter.tps;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invocation;
/**
* Provide boolean information whether a invocation of a provider service's methods or a particular method
* is allowed within a last invocation and current invocation.
* <pre>
* e.g. if tps for a method m1 is 5 for a minute then if 6th call is made within the span of 1 minute then 6th
* should not be allowed <b>isAllowable</b> will return false.
* </pre>
*/
public interface TPSLimiter {
/**
* judge if the current invocation is allowed by TPS rule
*
* @param url url
* @param invocation invocation
* @return true allow the current invocation, otherwise, return false
*/
boolean isAllowable(URL url, Invocation invocation);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.