Search in sources :

Example 1 with StateMachineInstance

use of io.seata.saga.statelang.domain.StateMachineInstance in project seata by seata.

the class ServiceTaskHandlerInterceptor method preProcess.

@Override
public void preProcess(ProcessContext context) throws EngineExecutionException {
    StateInstruction instruction = context.getInstruction(StateInstruction.class);
    StateMachineInstance stateMachineInstance = (StateMachineInstance) context.getVariable(DomainConstants.VAR_NAME_STATEMACHINE_INST);
    StateMachineConfig stateMachineConfig = (StateMachineConfig) context.getVariable(DomainConstants.VAR_NAME_STATEMACHINE_CONFIG);
    if (EngineUtils.isTimeout(stateMachineInstance.getGmtUpdated(), stateMachineConfig.getTransOperationTimeout())) {
        String message = "Saga Transaction [stateMachineInstanceId:" + stateMachineInstance.getId() + "] has timed out, stop execution now.";
        LOGGER.error(message);
        EngineExecutionException exception = ExceptionUtils.createEngineExecutionException(null, FrameworkErrorCode.StateMachineExecutionTimeout, message, stateMachineInstance, instruction.getStateName());
        EngineUtils.failStateMachine(context, exception);
        throw exception;
    }
    StateInstanceImpl stateInstance = new StateInstanceImpl();
    Map<String, Object> contextVariables = (Map<String, Object>) context.getVariable(DomainConstants.VAR_NAME_STATEMACHINE_CONTEXT);
    ServiceTaskStateImpl state = (ServiceTaskStateImpl) instruction.getState(context);
    List<Object> serviceInputParams = null;
    if (contextVariables != null) {
        try {
            serviceInputParams = ParameterUtils.createInputParams(stateMachineConfig.getExpressionFactoryManager(), stateInstance, state, contextVariables);
        } catch (Exception e) {
            String message = "Task [" + state.getName() + "] input parameters assign failed, please check 'Input' expression:" + e.getMessage();
            EngineExecutionException exception = ExceptionUtils.createEngineExecutionException(e, FrameworkErrorCode.VariablesAssignError, message, stateMachineInstance, state.getName());
            EngineUtils.failStateMachine(context, exception);
            throw exception;
        }
    }
    ((HierarchicalProcessContext) context).setVariableLocally(DomainConstants.VAR_NAME_INPUT_PARAMS, serviceInputParams);
    stateInstance.setMachineInstanceId(stateMachineInstance.getId());
    stateInstance.setStateMachineInstance(stateMachineInstance);
    Object isForCompensation = state.isForCompensation();
    if (context.hasVariable(DomainConstants.VAR_NAME_IS_LOOP_STATE) && !Boolean.TRUE.equals(isForCompensation)) {
        stateInstance.setName(LoopTaskUtils.generateLoopStateName(context, state.getName()));
        StateInstance lastRetriedStateInstance = LoopTaskUtils.findOutLastRetriedStateInstance(stateMachineInstance, stateInstance.getName());
        stateInstance.setStateIdRetriedFor(lastRetriedStateInstance == null ? null : lastRetriedStateInstance.getId());
    } else {
        stateInstance.setName(state.getName());
        stateInstance.setStateIdRetriedFor((String) context.getVariable(state.getName() + DomainConstants.VAR_NAME_RETRIED_STATE_INST_ID));
    }
    stateInstance.setGmtStarted(new Date());
    stateInstance.setGmtUpdated(stateInstance.getGmtStarted());
    stateInstance.setStatus(ExecutionStatus.RU);
    if (StringUtils.hasLength(stateInstance.getBusinessKey())) {
        ((Map<String, Object>) context.getVariable(DomainConstants.VAR_NAME_STATEMACHINE_CONTEXT)).put(state.getName() + DomainConstants.VAR_NAME_BUSINESSKEY, stateInstance.getBusinessKey());
    }
    stateInstance.setType(state.getType());
    stateInstance.setForUpdate(state.isForUpdate());
    stateInstance.setServiceName(state.getServiceName());
    stateInstance.setServiceMethod(state.getServiceMethod());
    stateInstance.setServiceType(state.getServiceType());
    if (isForCompensation != null && (Boolean) isForCompensation) {
        CompensationHolder compensationHolder = CompensationHolder.getCurrent(context, true);
        StateInstance stateToBeCompensated = compensationHolder.getStatesNeedCompensation().get(state.getName());
        if (stateToBeCompensated != null) {
            stateToBeCompensated.setCompensationState(stateInstance);
            stateInstance.setStateIdCompensatedFor(stateToBeCompensated.getId());
        } else {
            LOGGER.error("Compensation State[{}] has no state to compensate, maybe this is a bug.", state.getName());
        }
        CompensationHolder.getCurrent(context, true).addForCompensationState(stateInstance.getName(), stateInstance);
    }
    if (DomainConstants.OPERATION_NAME_FORWARD.equals(context.getVariable(DomainConstants.VAR_NAME_OPERATION_NAME)) && StringUtils.isEmpty(stateInstance.getStateIdRetriedFor()) && !state.isForCompensation()) {
        List<StateInstance> stateList = stateMachineInstance.getStateList();
        if (CollectionUtils.isNotEmpty(stateList)) {
            for (int i = stateList.size() - 1; i >= 0; i--) {
                StateInstance executedState = stateList.get(i);
                if (stateInstance.getName().equals(executedState.getName())) {
                    stateInstance.setStateIdRetriedFor(executedState.getId());
                    executedState.setIgnoreStatus(true);
                    break;
                }
            }
        }
    }
    stateInstance.setInputParams(serviceInputParams);
    if (stateMachineInstance.getStateMachine().isPersist() && state.isPersist() && stateMachineConfig.getStateLogStore() != null) {
        try {
            stateMachineConfig.getStateLogStore().recordStateStarted(stateInstance, context);
        } catch (Exception e) {
            String message = "Record state[" + state.getName() + "] started failed, stateMachineInstance[" + stateMachineInstance.getId() + "], Reason: " + e.getMessage();
            EngineExecutionException exception = ExceptionUtils.createEngineExecutionException(e, FrameworkErrorCode.ExceptionCaught, message, stateMachineInstance, state.getName());
            EngineUtils.failStateMachine(context, exception);
            throw exception;
        }
    }
    if (StringUtils.isEmpty(stateInstance.getId())) {
        stateInstance.setId(stateMachineConfig.getSeqGenerator().generate(DomainConstants.SEQ_ENTITY_STATE_INST));
    }
    stateMachineInstance.putStateInstance(stateInstance.getId(), stateInstance);
    ((HierarchicalProcessContext) context).setVariableLocally(DomainConstants.VAR_NAME_STATE_INST, stateInstance);
}
Also used : CompensationHolder(io.seata.saga.engine.pcext.utils.CompensationHolder) StateInstruction(io.seata.saga.engine.pcext.StateInstruction) StateInstanceImpl(io.seata.saga.statelang.domain.impl.StateInstanceImpl) HierarchicalProcessContext(io.seata.saga.proctrl.HierarchicalProcessContext) EngineExecutionException(io.seata.saga.engine.exception.EngineExecutionException) EngineExecutionException(io.seata.saga.engine.exception.EngineExecutionException) Date(java.util.Date) StateMachineInstance(io.seata.saga.statelang.domain.StateMachineInstance) ServiceTaskStateImpl(io.seata.saga.statelang.domain.impl.ServiceTaskStateImpl) StateMachineConfig(io.seata.saga.engine.StateMachineConfig) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) StateInstance(io.seata.saga.statelang.domain.StateInstance)

Example 2 with StateMachineInstance

use of io.seata.saga.statelang.domain.StateMachineInstance in project seata by seata.

the class LoopTaskUtils method isForSubStateMachineForward.

/**
 * forward with subStateMachine should check each loop state's status
 *
 * @param context
 * @return
 */
public static boolean isForSubStateMachineForward(ProcessContext context) {
    StateMachineInstance stateMachineInstance = (StateMachineInstance) context.getVariable(DomainConstants.VAR_NAME_STATEMACHINE_INST);
    StateInstruction instruction = context.getInstruction(StateInstruction.class);
    StateMachineConfig stateMachineConfig = (StateMachineConfig) context.getVariable(DomainConstants.VAR_NAME_STATEMACHINE_CONFIG);
    StateInstance lastRetriedStateInstance = LoopTaskUtils.findOutLastRetriedStateInstance(stateMachineInstance, LoopTaskUtils.generateLoopStateName(context, instruction.getStateName()));
    if (null != lastRetriedStateInstance && DomainConstants.STATE_TYPE_SUB_STATE_MACHINE.equals(lastRetriedStateInstance.getType()) && !ExecutionStatus.SU.equals(lastRetriedStateInstance.getCompensationStatus())) {
        while (StringUtils.isNotBlank(lastRetriedStateInstance.getStateIdRetriedFor())) {
            lastRetriedStateInstance = stateMachineConfig.getStateLogStore().getStateInstance(lastRetriedStateInstance.getStateIdRetriedFor(), lastRetriedStateInstance.getMachineInstanceId());
        }
        List<StateMachineInstance> subInst = stateMachineConfig.getStateLogStore().queryStateMachineInstanceByParentId(EngineUtils.generateParentId(lastRetriedStateInstance));
        if (CollectionUtils.isNotEmpty(subInst)) {
            if (ExecutionStatus.SU.equals(subInst.get(0).getCompensationStatus())) {
                return false;
            }
        }
        if (ExecutionStatus.UN.equals(subInst.get(0).getCompensationStatus())) {
            throw new ForwardInvalidException("Last forward execution state instance is SubStateMachine and compensation status is " + "[UN], Operation[forward] denied, stateInstanceId:" + lastRetriedStateInstance.getId(), FrameworkErrorCode.OperationDenied);
        }
        return true;
    }
    return false;
}
Also used : StateInstruction(io.seata.saga.engine.pcext.StateInstruction) ForwardInvalidException(io.seata.saga.engine.exception.ForwardInvalidException) StateMachineConfig(io.seata.saga.engine.StateMachineConfig) StateMachineInstance(io.seata.saga.statelang.domain.StateMachineInstance) StateInstance(io.seata.saga.statelang.domain.StateInstance)

Example 3 with StateMachineInstance

use of io.seata.saga.statelang.domain.StateMachineInstance in project seata by seata.

the class LoopTaskUtils method findOutLastNeedForwardStateInstance.

public static StateInstance findOutLastNeedForwardStateInstance(ProcessContext context) {
    StateMachineInstance stateMachineInstance = (StateMachineInstance) context.getVariable(DomainConstants.VAR_NAME_STATEMACHINE_INST);
    StateInstance lastForwardState = (StateInstance) context.getVariable(DomainConstants.VAR_NAME_STATE_INST);
    List<StateInstance> actList = stateMachineInstance.getStateList();
    for (int i = actList.size() - 1; i >= 0; i--) {
        StateInstance stateInstance = actList.get(i);
        if (EngineUtils.getOriginStateName(stateInstance).equals(EngineUtils.getOriginStateName(lastForwardState)) && !ExecutionStatus.SU.equals(stateInstance.getStatus())) {
            return stateInstance;
        }
    }
    return lastForwardState;
}
Also used : StateMachineInstance(io.seata.saga.statelang.domain.StateMachineInstance) StateInstance(io.seata.saga.statelang.domain.StateInstance)

Example 4 with StateMachineInstance

use of io.seata.saga.statelang.domain.StateMachineInstance in project seata by seata.

the class LoopTaskUtils method getLoopConfig.

/**
 * get Loop Config from State
 *
 * @param context
 * @param currentState
 * @return currentState loop config if satisfied, else {@literal null}
 */
public static Loop getLoopConfig(ProcessContext context, State currentState) {
    if (matchLoop(currentState)) {
        AbstractTaskState taskState = (AbstractTaskState) currentState;
        StateMachineInstance stateMachineInstance = (StateMachineInstance) context.getVariable(DomainConstants.VAR_NAME_STATEMACHINE_INST);
        StateMachineConfig stateMachineConfig = (StateMachineConfig) context.getVariable(DomainConstants.VAR_NAME_STATEMACHINE_CONFIG);
        if (null != taskState.getLoop()) {
            Loop loop = taskState.getLoop();
            String collectionName = loop.getCollection();
            if (StringUtils.isNotBlank(collectionName)) {
                Object expression = ParameterUtils.createValueExpression(stateMachineConfig.getExpressionFactoryManager(), collectionName);
                Object collection = ParameterUtils.getValue(expression, stateMachineInstance.getContext(), null);
                if (collection instanceof Collection && ((Collection) collection).size() > 0) {
                    LoopContextHolder.getCurrent(context, true).setCollection((Collection) collection);
                    return loop;
                }
            }
            LOGGER.warn("State [{}] loop collection param [{}] invalid", currentState.getName(), collectionName);
        }
    }
    return null;
}
Also used : AbstractTaskState(io.seata.saga.statelang.domain.impl.AbstractTaskState) Loop(io.seata.saga.statelang.domain.TaskState.Loop) Collection(java.util.Collection) StateMachineConfig(io.seata.saga.engine.StateMachineConfig) StateMachineInstance(io.seata.saga.statelang.domain.StateMachineInstance)

Example 5 with StateMachineInstance

use of io.seata.saga.statelang.domain.StateMachineInstance in project seata by seata.

the class CompensationTriggerStateHandler method process.

@Override
public void process(ProcessContext context) throws EngineExecutionException {
    StateInstruction instruction = context.getInstruction(StateInstruction.class);
    StateMachineInstance stateMachineInstance = (StateMachineInstance) context.getVariable(DomainConstants.VAR_NAME_STATEMACHINE_INST);
    StateMachineConfig stateMachineConfig = (StateMachineConfig) context.getVariable(DomainConstants.VAR_NAME_STATEMACHINE_CONFIG);
    List<StateInstance> stateInstanceList = stateMachineInstance.getStateList();
    if (CollectionUtils.isEmpty(stateInstanceList)) {
        stateInstanceList = stateMachineConfig.getStateLogStore().queryStateInstanceListByMachineInstanceId(stateMachineInstance.getId());
    }
    List<StateInstance> stateListToBeCompensated = CompensationHolder.findStateInstListToBeCompensated(context, stateInstanceList);
    if (CollectionUtils.isNotEmpty(stateListToBeCompensated)) {
        // Clear exceptions that occur during forward execution
        Exception e = (Exception) context.removeVariable(DomainConstants.VAR_NAME_CURRENT_EXCEPTION);
        if (e != null) {
            stateMachineInstance.setException(e);
        }
        Stack<StateInstance> stateStackToBeCompensated = CompensationHolder.getCurrent(context, true).getStateStackNeedCompensation();
        stateStackToBeCompensated.addAll(stateListToBeCompensated);
        // and the forward state should not be modified.
        if (stateMachineInstance.getStatus() == null || ExecutionStatus.RU.equals(stateMachineInstance.getStatus())) {
            stateMachineInstance.setStatus(ExecutionStatus.UN);
        }
        // Record the status of the state machine as "compensating", and the subsequent routing logic will route
        // to the compensation state
        stateMachineInstance.setCompensationStatus(ExecutionStatus.RU);
        context.setVariable(DomainConstants.VAR_NAME_CURRENT_COMPEN_TRIGGER_STATE, instruction.getState(context));
    } else {
        EngineUtils.endStateMachine(context);
    }
}
Also used : StateInstruction(io.seata.saga.engine.pcext.StateInstruction) StateMachineConfig(io.seata.saga.engine.StateMachineConfig) EngineExecutionException(io.seata.saga.engine.exception.EngineExecutionException) StateMachineInstance(io.seata.saga.statelang.domain.StateMachineInstance) StateInstance(io.seata.saga.statelang.domain.StateInstance)

Aggregations

StateMachineInstance (io.seata.saga.statelang.domain.StateMachineInstance)113 HashMap (java.util.HashMap)80 Test (org.junit.jupiter.api.Test)76 EngineExecutionException (io.seata.saga.engine.exception.EngineExecutionException)21 GlobalTransaction (io.seata.tm.api.GlobalTransaction)17 StateMachineConfig (io.seata.saga.engine.StateMachineConfig)16 StateInstance (io.seata.saga.statelang.domain.StateInstance)16 StateInstruction (io.seata.saga.engine.pcext.StateInstruction)15 ArrayList (java.util.ArrayList)12 Map (java.util.Map)12 ForwardInvalidException (io.seata.saga.engine.exception.ForwardInvalidException)7 ProcessContext (io.seata.saga.proctrl.ProcessContext)6 People (io.seata.saga.engine.mock.DemoService.People)5 ExecutionStatus (io.seata.saga.statelang.domain.ExecutionStatus)5 Loop (io.seata.saga.statelang.domain.TaskState.Loop)5 Date (java.util.Date)5 LinkedHashMap (java.util.LinkedHashMap)5 TransactionException (io.seata.core.exception.TransactionException)4 AbstractTaskState (io.seata.saga.statelang.domain.impl.AbstractTaskState)4 List (java.util.List)4