96f0b8047ba058a430113e0e63337dd4c10f71ae
[cps/ncmp-dmi-plugin.git] /
1 /*
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2024 Nordix Foundation
4  *  ================================================================================
5  *  Licensed under the Apache License, Version 2.0 (the "License");
6  *  you may not use this file except in compliance with the License.
7  *  You may obtain a copy of the License at
8  *
9  *        http://www.apache.org/licenses/LICENSE-2.0
10  *
11  *  Unless required by applicable law or agreed to in writing, software
12  *  distributed under the License is distributed on an "AS IS" BASIS,
13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *  See the License for the specific language governing permissions and
15  *  limitations under the License.
16  *
17  *  SPDX-License-Identifier: Apache-2.0
18  *  ============LICENSE_END=========================================================
19  */
20
21 package org.onap.cps.ncmp.dmi.rest.stub.controller.aop;
22
23 import com.fasterxml.jackson.databind.JsonNode;
24 import com.fasterxml.jackson.databind.ObjectMapper;
25 import lombok.RequiredArgsConstructor;
26 import lombok.extern.slf4j.Slf4j;
27 import org.aspectj.lang.ProceedingJoinPoint;
28 import org.aspectj.lang.annotation.Around;
29 import org.aspectj.lang.annotation.Aspect;
30 import org.springframework.beans.factory.annotation.Value;
31 import org.springframework.http.HttpStatus;
32 import org.springframework.stereotype.Component;
33 import org.springframework.http.ResponseEntity;
34 import java.util.Map;
35 import java.util.concurrent.ConcurrentHashMap;
36
37 /**
38  * Aspect to handle initial processing for methods annotated with @ModuleInitialProcess.
39  */
40 @Slf4j
41 @Aspect
42 @Component
43 @RequiredArgsConstructor
44 public class ModuleInitialProcessAspect {
45
46     private final ObjectMapper objectMapper;
47     private static final Map<String, Long> firstRequestTimePerModuleSetTag = new ConcurrentHashMap<>();
48
49     @Value("${delay.module-initial-processing-delay-ms:120000}")
50     private long moduleInitialProcessingDelayMs;
51
52     /**
53      * Around advice to handle methods annotated with @ModuleInitialProcess.
54      *
55      * @param proceedingJoinPoint  the join point representing the method execution
56      * @param moduleInitialProcess the annotation containing the module set tag
57      * @return the result of the method execution or a ResponseEntity indicating that the service is unavailable
58      */
59     @Around("@annotation(moduleInitialProcess)")
60     public Object handleModuleInitialProcess(ProceedingJoinPoint proceedingJoinPoint, ModuleInitialProcess moduleInitialProcess) throws Throwable {
61         log.debug("Aspect invoked for method: {}", proceedingJoinPoint.getSignature());
62         Object moduleRequest = proceedingJoinPoint.getArgs()[1];
63         String moduleSetTag = extractModuleSetTagFromRequest(moduleRequest);
64
65         if (isModuleSetTagEmptyOrInvalid(moduleSetTag)) {
66             log.debug("Received request with an empty or null moduleSetTag. Returning default processing.");
67             return proceedingJoinPoint.proceed();
68         }
69
70         long firstRequestTimestamp = getFirstRequestTimestamp(moduleSetTag);
71         long currentTimestamp = System.currentTimeMillis();
72
73         if (isInitialProcessingCompleted(currentTimestamp, firstRequestTimestamp)) {
74             log.debug("Initial processing for moduleSetTag '{}' is completed.", moduleSetTag);
75             return proceedingJoinPoint.proceed();
76         }
77
78         long remainingProcessingTime = calculateRemainingProcessingTime(currentTimestamp, firstRequestTimestamp);
79         log.info("Initial processing for moduleSetTag '{}' is still active. Returning HTTP 503. Remaining time: {} ms.", moduleSetTag, remainingProcessingTime);
80         return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE).build();
81     }
82
83     private String extractModuleSetTagFromRequest(Object moduleRequest) {
84         JsonNode rootNode = objectMapper.valueToTree(moduleRequest);
85         return rootNode.path("moduleSetTag").asText(null);
86     }
87
88     private boolean isModuleSetTagEmptyOrInvalid(String moduleSetTag) {
89         return moduleSetTag == null || moduleSetTag.trim().isEmpty();
90     }
91
92     private long getFirstRequestTimestamp(String moduleSetTag) {
93         return firstRequestTimePerModuleSetTag.computeIfAbsent(moduleSetTag, firstRequestTime -> System.currentTimeMillis());
94     }
95
96     private boolean isInitialProcessingCompleted(long currentTimestamp, long firstRequestTimestamp) {
97         return currentTimestamp - firstRequestTimestamp > moduleInitialProcessingDelayMs;
98     }
99
100     private long calculateRemainingProcessingTime(long currentTimestamp, long firstRequestTimestamp) {
101         return moduleInitialProcessingDelayMs - (currentTimestamp - firstRequestTimestamp);
102     }
103 }