You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@fineract.apache.org by GitBox <gi...@apache.org> on 2022/11/25 10:53:42 UTC

[GitHub] [fineract] galovics commented on a diff in pull request #2756: FINERACT-1744 - Idempotency support

galovics commented on code in PR #2756:
URL: https://github.com/apache/fineract/pull/2756#discussion_r1030613828


##########
fineract-provider/src/main/java/org/apache/fineract/commands/service/SynchronousCommandProcessingService.java:
##########
@@ -64,83 +67,70 @@ public class SynchronousCommandProcessingService implements CommandProcessingSer
     private final ApplicationContext applicationContext;
     private final ToApiJsonSerializer<Map<String, Object>> toApiJsonSerializer;
     private final ToApiJsonSerializer<CommandProcessingResult> toApiResultJsonSerializer;
-    private final CommandSourceRepository commandSourceRepository;
     private final ConfigurationDomainService configurationDomainService;
     private final CommandHandlerProvider commandHandlerProvider;
+    private final IdempotencyKeyResolver idempotencyKeyResolver;
     private final IdempotencyKeyGenerator idempotencyKeyGenerator;
-    private final FineractProperties fineractProperties;
+    private final CommandSourceService commandSourceService;
+    private final Gson gson = new Gson();
 
     @Override
-    @Transactional
     @Retry(name = "executeCommand", fallbackMethod = "fallbackExecuteCommand")
     public CommandProcessingResult executeCommand(final CommandWrapper wrapper, final JsonCommand command,
             final boolean isApprovedByChecker) {
+        // Do not store the idempotency key because of the exception handling
+        setIdempotencyKeyStoreFlag(false);
 
         final boolean rollbackTransaction = configurationDomainService.isMakerCheckerEnabledForTask(wrapper.taskPermissionName());
+        String idempotencyKey = idempotencyKeyResolver.resolve(wrapper);
+        checkExistingCommand(wrapper, idempotencyKey);

Review Comment:
   Well, I understand this method (checkExistingCommand) but I don't really like how this is structured in terms of execution flow. If I just look at this (executeCommand) method, it's not very clear that this checkExistingCommand will actually break the execution flow by throwing exceptions.
   
   Would be nicer to restructure this a bit so it's more cleaner.



##########
integration-tests/src/test/java/org/apache/fineract/integrationtests/common/IdempotencyHelper.java:
##########
@@ -0,0 +1,99 @@
+/**
+ * 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.fineract.integrationtests.common;
+
+import com.google.gson.Gson;
+import com.google.gson.reflect.TypeToken;
+import io.restassured.response.Response;
+import io.restassured.specification.RequestSpecification;
+import io.restassured.specification.ResponseSpecification;
+import java.util.List;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.fineract.cob.data.BusinessStep;
+import org.apache.fineract.cob.data.JobBusinessStepConfigData;
+import org.apache.fineract.cob.data.JobBusinessStepDetail;
+
+@Slf4j
+public final class IdempotencyHelper {
+
+    private static final String BUSINESS_STEPS_API_URL_START = "/fineract-provider/api/v1/jobs/";
+    private static final String BUSINESS_STEPS_API_URL_END = "/steps?" + Utils.TENANT_IDENTIFIER;
+    private static final String GET_AVAILABLE_BUSINESS_STEPS_API_URL_END = "/available-steps?" + Utils.TENANT_IDENTIFIER;
+
+    private IdempotencyHelper() {
+
+    }
+
+    public static String toJsonString(final List<BusinessStep> batchRequests) {
+        return new Gson().toJson(new BusinessStepWrapper(batchRequests));
+    }
+
+    public static JobBusinessStepConfigData configuredBusinessStepFromJsonString(final String json) {
+        return new Gson().fromJson(json, new TypeToken<JobBusinessStepConfigData>() {}.getType());
+    }
+
+    // private static ApiParameterError configuredApiParameterErrorFromJsonString(final String json) {

Review Comment:
   Comment.



##########
fineract-provider/src/main/java/org/apache/fineract/commands/handler/NewCommandSourceHandler.java:
##########
@@ -20,8 +20,12 @@
 
 import org.apache.fineract.infrastructure.core.api.JsonCommand;
 import org.apache.fineract.infrastructure.core.data.CommandProcessingResult;
+import org.springframework.transaction.annotation.Isolation;
+import org.springframework.transaction.annotation.Propagation;
+import org.springframework.transaction.annotation.Transactional;
 
 public interface NewCommandSourceHandler {
 
+    @Transactional(propagation = Propagation.REQUIRES_NEW, isolation = Isolation.REPEATABLE_READ)

Review Comment:
   I don't remember. What if the handler implementor also uses @Transactional? Does it override this behavior or not?



##########
fineract-provider/src/main/java/org/apache/fineract/commands/service/SynchronousCommandProcessingService.java:
##########
@@ -149,15 +139,39 @@ public CommandProcessingResult executeCommand(final CommandWrapper wrapper, fina
         return result;
     }
 
+    private void publishHookErrorEvent(CommandWrapper wrapper, JsonCommand command, Throwable t) {
+        ErrorInfo ex = commandSourceService.generateErrorException(t);
+        publishHookEvent(wrapper.entityName(), wrapper.actionName(), command, gson.toJson(ex));
+    }
+
+    private void checkExistingCommand(CommandWrapper wrapper, String idempotencyKey) {
+        CommandSource existingCommand = commandSourceService.findCommandSource(wrapper, idempotencyKey);
+        if (existingCommand != null) {
+            if (UNDER_PROCESSING.getValue().equals(existingCommand.getStatus())) {
+                throw new CommandUnderProcessingException(wrapper.actionName(), wrapper.entityName(), wrapper.getIdempotencyKey(),
+                        wrapper.getJson());
+            } else if (ERROR.getValue().equals(existingCommand.getStatus())) {
+                throw new CommandFailedException(wrapper.actionName(), wrapper.entityName(), wrapper.getIdempotencyKey(),
+                        existingCommand.getResult(), existingCommand.getResultStatusCode());
+            } else if (PROCESSED.getValue().equals(existingCommand.getStatus())) {
+                throw new CommandProcessedException(wrapper.actionName(), wrapper.entityName(), wrapper.getIdempotencyKey(),
+                        existingCommand.getResult());
+            }
+        }
+    }
+
+    private void setIdempotencyKeyStoreFlag(boolean flag) {
+        RequestContextHolder.currentRequestAttributes().setAttribute("storeIdempotencyKey", flag, RequestAttributes.SCOPE_REQUEST);

Review Comment:
   Magic string (the attribute key), please extract it to a constant.



##########
fineract-provider/src/main/java/org/apache/fineract/commands/service/IdempotencyKeyResolver.java:
##########
@@ -0,0 +1,52 @@
+/**
+ * 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.fineract.commands.service;
+
+import java.util.Optional;
+import org.apache.fineract.commands.domain.CommandWrapper;
+import org.apache.fineract.infrastructure.core.config.FineractProperties;
+import org.springframework.stereotype.Component;
+import org.springframework.web.context.request.RequestContextHolder;
+import org.springframework.web.context.request.ServletRequestAttributes;
+
+@Component
+public class IdempotencyKeyResolver {
+
+    private final IdempotencyKeyGenerator idempotencyKeyGenerator;
+
+    private final FineractProperties fineractProperties;
+
+    public IdempotencyKeyResolver(IdempotencyKeyGenerator idempotencyKeyGenerator, FineractProperties fineractProperties) {

Review Comment:
   Could be replaced by @RequiredArgsConstructor.



##########
fineract-provider/src/main/java/org/apache/fineract/commands/service/SynchronousCommandProcessingService.java:
##########
@@ -64,83 +67,70 @@ public class SynchronousCommandProcessingService implements CommandProcessingSer
     private final ApplicationContext applicationContext;
     private final ToApiJsonSerializer<Map<String, Object>> toApiJsonSerializer;
     private final ToApiJsonSerializer<CommandProcessingResult> toApiResultJsonSerializer;
-    private final CommandSourceRepository commandSourceRepository;
     private final ConfigurationDomainService configurationDomainService;
     private final CommandHandlerProvider commandHandlerProvider;
+    private final IdempotencyKeyResolver idempotencyKeyResolver;
     private final IdempotencyKeyGenerator idempotencyKeyGenerator;
-    private final FineractProperties fineractProperties;
+    private final CommandSourceService commandSourceService;
+    private final Gson gson = new Gson();

Review Comment:
   Replace this direct instantiation with `org.apache.fineract.infrastructure.core.serialization.GoogleGsonSerializerHelper#createSimpleGson`



##########
fineract-provider/src/main/java/org/apache/fineract/commands/service/SynchronousCommandProcessingService.java:
##########
@@ -64,83 +67,70 @@ public class SynchronousCommandProcessingService implements CommandProcessingSer
     private final ApplicationContext applicationContext;
     private final ToApiJsonSerializer<Map<String, Object>> toApiJsonSerializer;
     private final ToApiJsonSerializer<CommandProcessingResult> toApiResultJsonSerializer;
-    private final CommandSourceRepository commandSourceRepository;
     private final ConfigurationDomainService configurationDomainService;
     private final CommandHandlerProvider commandHandlerProvider;
+    private final IdempotencyKeyResolver idempotencyKeyResolver;
     private final IdempotencyKeyGenerator idempotencyKeyGenerator;
-    private final FineractProperties fineractProperties;
+    private final CommandSourceService commandSourceService;
+    private final Gson gson = new Gson();
 
     @Override
-    @Transactional
     @Retry(name = "executeCommand", fallbackMethod = "fallbackExecuteCommand")
     public CommandProcessingResult executeCommand(final CommandWrapper wrapper, final JsonCommand command,
             final boolean isApprovedByChecker) {
+        // Do not store the idempotency key because of the exception handling
+        setIdempotencyKeyStoreFlag(false);
 
         final boolean rollbackTransaction = configurationDomainService.isMakerCheckerEnabledForTask(wrapper.taskPermissionName());
+        String idempotencyKey = idempotencyKeyResolver.resolve(wrapper);
+        checkExistingCommand(wrapper, idempotencyKey);
 
-        final NewCommandSourceHandler handler = findCommandHandler(wrapper);
+        // Store idempotency key to the request attribute
+
+        CommandSource savedCommandSource = commandSourceService.saveInitial(wrapper, command, context.authenticatedUser(wrapper),
+                idempotencyKey);
+        if (savedCommandSource.getId() == null) {
+            throw new IllegalStateException("Command source not saved");
+        }
+        RequestContextHolder.currentRequestAttributes().setAttribute("commandSourceId", savedCommandSource.getId(),

Review Comment:
   `commandSourceId` is a magic string. Constant pls.



##########
fineract-provider/src/main/java/org/apache/fineract/commands/service/SynchronousCommandProcessingService.java:
##########
@@ -64,83 +67,70 @@ public class SynchronousCommandProcessingService implements CommandProcessingSer
     private final ApplicationContext applicationContext;
     private final ToApiJsonSerializer<Map<String, Object>> toApiJsonSerializer;
     private final ToApiJsonSerializer<CommandProcessingResult> toApiResultJsonSerializer;
-    private final CommandSourceRepository commandSourceRepository;
     private final ConfigurationDomainService configurationDomainService;
     private final CommandHandlerProvider commandHandlerProvider;
+    private final IdempotencyKeyResolver idempotencyKeyResolver;
     private final IdempotencyKeyGenerator idempotencyKeyGenerator;
-    private final FineractProperties fineractProperties;
+    private final CommandSourceService commandSourceService;
+    private final Gson gson = new Gson();
 
     @Override
-    @Transactional
     @Retry(name = "executeCommand", fallbackMethod = "fallbackExecuteCommand")
     public CommandProcessingResult executeCommand(final CommandWrapper wrapper, final JsonCommand command,
             final boolean isApprovedByChecker) {
+        // Do not store the idempotency key because of the exception handling
+        setIdempotencyKeyStoreFlag(false);
 
         final boolean rollbackTransaction = configurationDomainService.isMakerCheckerEnabledForTask(wrapper.taskPermissionName());
+        String idempotencyKey = idempotencyKeyResolver.resolve(wrapper);
+        checkExistingCommand(wrapper, idempotencyKey);
 
-        final NewCommandSourceHandler handler = findCommandHandler(wrapper);
+        // Store idempotency key to the request attribute
+
+        CommandSource savedCommandSource = commandSourceService.saveInitial(wrapper, command, context.authenticatedUser(wrapper),
+                idempotencyKey);
+        if (savedCommandSource.getId() == null) {
+            throw new IllegalStateException("Command source not saved");
+        }
+        RequestContextHolder.currentRequestAttributes().setAttribute("commandSourceId", savedCommandSource.getId(),

Review Comment:
   Also, would be nice to extract this line to a separate method so it can be more descriptive.



##########
fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/exceptionmapper/DuplicateCommandExceptionMapper.java:
##########
@@ -0,0 +1,61 @@
+/**
+ * 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.fineract.infrastructure.core.exceptionmapper;
+
+import static org.apache.fineract.infrastructure.core.data.ApiGlobalErrorResponse.serverSideError;
+
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.Response.Status;
+import javax.ws.rs.ext.ExceptionMapper;
+import javax.ws.rs.ext.Provider;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.fineract.infrastructure.core.exception.CommandFailedException;
+import org.apache.fineract.infrastructure.core.exception.CommandProcessedException;
+import org.apache.fineract.infrastructure.core.exception.CommandUnderProcessingException;
+import org.apache.fineract.infrastructure.core.exception.DuplicateCommandException;
+import org.springframework.stereotype.Component;
+
+@Provider
+@Component
+@Slf4j
+public class DuplicateCommandExceptionMapper implements ExceptionMapper<DuplicateCommandException> {
+
+    public static final String IDEMPOTENT_CACHE_HEADER = "x-served-from-cache";
+
+    @Override
+    public Response toResponse(final DuplicateCommandException exception) {
+        log.debug("Duplicate request: {}", exception.getMessage());
+        if (exception instanceof CommandProcessedException) {

Review Comment:
   Not a fan of this. Can we do separate ExceptionMappers for each type of Exception type?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@fineract.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org