Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature : mock server #6205

Merged
merged 16 commits into from
Jan 23, 2024
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion changes/en-us/2.x.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ Add changes here for all PR submitted to the 2.x branch.
<!-- Please add the `changes` to the following location(feature/bugfix/optimize/test) based on the type of PR -->

### feature:
- [[#PR_NO](https://github.com/apache/incubator-seata/pull/PR_NO)] A brief and accurate description of PR
- [[#6205](https://github.com/apache/incubator-seata/pull/6205)] mock server

### bugfix:
- [[#6090](https://github.com/apache/incubator-seata/pull/6090)] fix the TCC aspect exception handling process, do not wrapping the internal call exceptions
Expand Down
2 changes: 1 addition & 1 deletion changes/zh-cn/2.x.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<!-- 请根据PR的类型添加 `变更记录` 到以下对应位置(feature/bugfix/optimize/test) 下 -->

### feature:
- [[#PR_NO](https://github.com/apache/incubator-seata/pull/PR_NO)] 准确简要的PR描述
- [[#6205](https://github.com/apache/incubator-seata/pull/6205)] 提供mock server

### bugfix:
- [[#6090](https://github.com/apache/incubator-seata/pull/6090)] 修复tcc切面异常处理过程,不对内部调用异常做包装处理,直接向外抛出
Expand Down
1 change: 1 addition & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@
<module>spring</module>
<module>tcc</module>
<module>test</module>
<module>test-mock-server</module>
<module>tm</module>
<module>metrics</module>
<module>serializer</module>
Expand Down
62 changes: 62 additions & 0 deletions test-mock-server/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--

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.

-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>io.seata</groupId>
<artifactId>seata-parent</artifactId>
<version>${revision}</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>seata-mock-server</artifactId>
<packaging>jar</packaging>
<name>seata-mock-server</name>
xingfudeshi marked this conversation as resolved.
Show resolved Hide resolved
<description>Seata mock server</description>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
</plugin>
</plugins>
</build>

<dependencies>
<dependency>
<groupId>io.seata</groupId>
<artifactId>seata-server</artifactId>
<version>${project.version}</version>
<exclusions>
<exclusion>
<artifactId>slf4j-log4j12</artifactId>
<groupId>org.slf4j</groupId>
</exclusion>
<exclusion>
<artifactId>log4j</artifactId>
<groupId>log4j</groupId>
</exclusion>
</exclusions>
</dependency>
</dependencies>


</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/*
* 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 io.seata.mockserver;

/**
* The enum Expect transaction result.
*
*/
public enum ExpectTransactionResult {

AllCommitted(0, "all success"),
AllRollbacked(1, "all rollback"),
PhaseOneTimeoutRollbacked(2, "phase one failed");

private final int code;
private final String desc;

ExpectTransactionResult(int code, String desc) {
this.code = code;
this.desc = desc;
}

/**
* Gets code.
*
* @return the code
*/
public int getCode() {
return code;
}

public static ExpectTransactionResult covert(int code) {
for (ExpectTransactionResult result : ExpectTransactionResult.values()) {
if (result.getCode() == code) {
return result;
}
}
return null;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,232 @@
/*
* 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 io.seata.mockserver;

import io.seata.common.util.CollectionUtils;
import io.seata.core.exception.TransactionException;
import io.seata.core.model.BranchStatus;
import io.seata.core.model.GlobalStatus;
import io.seata.core.protocol.AbstractMessage;
import io.seata.core.protocol.AbstractResultMessage;
import io.seata.core.protocol.ResultCode;
import io.seata.core.protocol.transaction.AbstractTransactionRequestToTC;
import io.seata.core.protocol.transaction.BranchRegisterRequest;
import io.seata.core.protocol.transaction.BranchRegisterResponse;
import io.seata.core.protocol.transaction.BranchReportRequest;
import io.seata.core.protocol.transaction.BranchReportResponse;
import io.seata.core.protocol.transaction.GlobalBeginRequest;
import io.seata.core.protocol.transaction.GlobalBeginResponse;
import io.seata.core.protocol.transaction.GlobalCommitRequest;
import io.seata.core.protocol.transaction.GlobalCommitResponse;
import io.seata.core.protocol.transaction.GlobalLockQueryRequest;
import io.seata.core.protocol.transaction.GlobalLockQueryResponse;
import io.seata.core.protocol.transaction.GlobalReportRequest;
import io.seata.core.protocol.transaction.GlobalReportResponse;
import io.seata.core.protocol.transaction.GlobalRollbackRequest;
import io.seata.core.protocol.transaction.GlobalRollbackResponse;
import io.seata.core.protocol.transaction.GlobalStatusRequest;
import io.seata.core.protocol.transaction.GlobalStatusResponse;
import io.seata.core.rpc.Disposable;
import io.seata.core.rpc.RemotingServer;
import io.seata.core.rpc.RpcContext;
import io.seata.core.rpc.TransactionMessageHandler;
import io.seata.mockserver.call.CallRm;
import io.seata.server.AbstractTCInboundHandler;
import io.seata.server.UUIDGenerator;
import io.seata.server.session.BranchSession;
import io.seata.server.session.GlobalSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.IntStream;

/**
* Mock Coordinator
**/
public class MockCoordinator extends AbstractTCInboundHandler implements TransactionMessageHandler, Disposable {

protected static final Logger LOGGER = LoggerFactory.getLogger(MockCoordinator.class);

RemotingServer remotingServer;

private static MockCoordinator coordinator;

private Map<String, ExpectTransactionResult> expectTransactionResultMap;
private Map<String, Integer> expectRetryTimesMap;
private Map<String, List<BranchSession>> branchMap;

private MockCoordinator() {
}


public static MockCoordinator getInstance() {
if (coordinator == null) {
synchronized (MockCoordinator.class) {
if (coordinator == null) {
coordinator = new MockCoordinator();
coordinator.expectTransactionResultMap = new ConcurrentHashMap<>();
coordinator.expectRetryTimesMap = new ConcurrentHashMap<>();
coordinator.branchMap = new ConcurrentHashMap<>();
}
}
}
return coordinator;
}


@Override
public void destroy() {

}

@Override
public AbstractResultMessage onRequest(AbstractMessage request, RpcContext context) {
if (!(request instanceof AbstractTransactionRequestToTC)) {
throw new IllegalArgumentException();
}
AbstractTransactionRequestToTC transactionRequest = (AbstractTransactionRequestToTC) request;
transactionRequest.setTCInboundHandler(this);

return transactionRequest.handle(context);
}

@Override
public void onResponse(AbstractResultMessage response, RpcContext context) {
response.setResultCode(ResultCode.Success);
}

@Override
protected void doGlobalBegin(GlobalBeginRequest request, GlobalBeginResponse response, RpcContext rpcContext) throws TransactionException {
GlobalSession session = GlobalSession.createGlobalSession(rpcContext.getApplicationId(),
rpcContext.getTransactionServiceGroup(), request.getTransactionName(), request.getTimeout());
expectTransactionResultMap.putIfAbsent(session.getXid(), ExpectTransactionResult.AllCommitted);
response.setXid(session.getXid());
response.setResultCode(ResultCode.Success);
}

@Override
protected void doGlobalCommit(GlobalCommitRequest request, GlobalCommitResponse response, RpcContext rpcContext) throws TransactionException {
response.setGlobalStatus(GlobalStatus.Committed);
response.setResultCode(ResultCode.Success);

int retry = expectRetryTimesMap.getOrDefault(request.getXid(), 0);
List<BranchSession> branchSessions = branchMap.get(request.getXid());
if (CollectionUtils.isEmpty(branchSessions)) {
LOGGER.info("branchSessions is empty,XID=" + request.getXid());
}
branchSessions.forEach(branch -> {
CallRm.branchCommit(remotingServer, branch.getResourceId(), branch.getClientId());
IntStream.range(0, retry).forEach(i ->
CallRm.branchCommit(remotingServer, branch.getResourceId(), branch.getClientId()));
});
}

@Override
protected void doGlobalRollback(GlobalRollbackRequest request, GlobalRollbackResponse response, RpcContext rpcContext) throws TransactionException {
response.setGlobalStatus(GlobalStatus.Rollbacked);
response.setResultCode(ResultCode.Success);


int retry = expectRetryTimesMap.getOrDefault(request.getXid(), 0);
List<BranchSession> branchSessions = branchMap.get(request.getXid());
if (CollectionUtils.isEmpty(branchSessions)) {
LOGGER.info("branchSessions is empty,XID=" + request.getXid());
}
branchSessions.forEach(branch -> {
CallRm.branchRollback(remotingServer, branch.getResourceId(), branch.getClientId());
IntStream.range(0, retry).forEach(i ->
CallRm.branchRollback(remotingServer, branch.getResourceId(), branch.getClientId()));
});
}

@Override
protected void doBranchRegister(BranchRegisterRequest request, BranchRegisterResponse response, RpcContext rpcContext) throws TransactionException {

BranchSession branchSession = new BranchSession(request.getBranchType());

String xid = request.getXid();
branchSession.setXid(xid);
// branchSession.setTransactionId(request.getTransactionId());
branchSession.setBranchId(UUIDGenerator.generateUUID());
branchSession.setResourceId(request.getResourceId());
branchSession.setLockKey(request.getLockKey());
branchSession.setClientId(rpcContext.getClientId());
branchSession.setApplicationData(request.getApplicationData());
branchSession.setStatus(BranchStatus.Registered);
branchMap.compute(xid, (key, val) -> {
if (val == null) {
val = new ArrayList<>();
}
val.add(branchSession);
return val;
});

response.setBranchId(branchSession.getBranchId());
response.setResultCode(ResultCode.Success);

// Thread thread = new Thread(() -> {
// try {
// Thread.sleep(1000);
// if (ProtocolConstants.VERSION_0 != Version.calcProtocolVersion(rpcContext.getVersion())) {
// CallRm.deleteUndoLog(remotingServer, resourceId, clientId);
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
// });
// thread.start();
}

@Override
protected void doBranchReport(BranchReportRequest request, BranchReportResponse response, RpcContext rpcContext) throws TransactionException {
response.setResultCode(ResultCode.Success);
}

@Override
protected void doLockCheck(GlobalLockQueryRequest request, GlobalLockQueryResponse response, RpcContext rpcContext) throws TransactionException {
response.setResultCode(ResultCode.Success);
}

@Override
protected void doGlobalStatus(GlobalStatusRequest request, GlobalStatusResponse response, RpcContext rpcContext) throws TransactionException {
response.setGlobalStatus(GlobalStatus.Committed);
response.setResultCode(ResultCode.Success);
}

@Override
protected void doGlobalReport(GlobalReportRequest request, GlobalReportResponse response, RpcContext rpcContext) throws TransactionException {
response.setGlobalStatus(GlobalStatus.Committed);
response.setResultCode(ResultCode.Success);
}

public void setRemotingServer(RemotingServer remotingServer) {
this.remotingServer = remotingServer;
}


public void setExpectedResult(String xid, ExpectTransactionResult expected) {
expectTransactionResultMap.put(xid, expected);
}

public void setExpectedRetry(String xid, int times) {
expectRetryTimesMap.put(xid, times);
}
}
Loading
Loading