2cecc145b4dba62455f02a6b98805b4f5416e225
[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 java.util.Map;
26 import java.util.concurrent.ConcurrentHashMap;
27 import lombok.RequiredArgsConstructor;
28 import lombok.extern.slf4j.Slf4j;
29 import org.aspectj.lang.ProceedingJoinPoint;
30 import org.aspectj.lang.annotation.Around;
31 import org.aspectj.lang.annotation.Aspect;
32 import org.springframework.beans.factory.annotation.Value;
33 import org.springframework.http.HttpStatus;
34 import org.springframework.http.ResponseEntity;
35 import org.springframework.stereotype.Component;
36
37
38 /**
39  * Aspect to handle initial processing for methods annotated with @ModuleInitialProcess.
40  */
41 @Slf4j
42 @Aspect
43 @Component
44 @RequiredArgsConstructor
45 public class ModuleInitialProcessAspect {
46
47     private final ObjectMapper objectMapper;
48     private static final Map<String, Long> firstRequestTimePerModuleSetTag = new ConcurrentHashMap<>();
49
50     @Value("${delay.module-initial-processing-delay-ms:120000}")
51     private long moduleInitialProcessingDelayMs;
52
53     /**
54      * Around advice to handle methods annotated with @ModuleInitialProcess.
55      *
56      * @param proceedingJoinPoint  the join point representing the method execution
57      * @param moduleInitialProcess the annotation containing the module set tag
58      * @return the result of the method execution or a ResponseEntity indicating that the service is unavailable
59      */
60     @Around("@annotation(moduleInitialProcess)")
61     public Object handleModuleInitialProcess(final ProceedingJoinPoint proceedingJoinPoint,
62                                              final ModuleInitialProcess moduleInitialProcess) throws Throwable {
63         log.debug("Aspect invoked for method: {}", proceedingJoinPoint.getSignature());
64         final Object moduleRequest = proceedingJoinPoint.getArgs()[1];
65         final String moduleSetTag = extractModuleSetTagFromRequest(moduleRequest);
66
67         if (isModuleSetTagEmptyOrInvalid(moduleSetTag)) {
68             log.debug("Received request with an empty or null moduleSetTag. Returning default processing.");
69             return proceedingJoinPoint.proceed();
70         }
71
72         final long firstRequestTimestamp = getFirstRequestTimestamp(moduleSetTag);
73         final long currentTimestamp = System.currentTimeMillis();
74
75         if (isInitialProcessingCompleted(currentTimestamp, firstRequestTimestamp)) {
76             log.debug("Initial processing for moduleSetTag '{}' is completed.", moduleSetTag);
77             return proceedingJoinPoint.proceed();
78         }
79
80         final long remainingProcessingTime = calculateRemainingProcessingTime(currentTimestamp, firstRequestTimestamp);
81         log.info("Initial processing for moduleSetTag '{}' is still active. Returning HTTP 503. Remaining time: {} ms.",
82                 moduleSetTag, remainingProcessingTime);
83         return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE).build();
84     }
85
86     private String extractModuleSetTagFromRequest(final Object moduleRequest) {
87         final JsonNode rootNode = objectMapper.valueToTree(moduleRequest);
88         return rootNode.path("moduleSetTag").asText(null);
89     }
90
91     private boolean isModuleSetTagEmptyOrInvalid(final String moduleSetTag) {
92         return moduleSetTag == null || moduleSetTag.trim().isEmpty();
93     }
94
95     private long getFirstRequestTimestamp(final String moduleSetTag) {
96         return firstRequestTimePerModuleSetTag
97                 .computeIfAbsent(moduleSetTag, firstRequestTime -> System.currentTimeMillis());
98     }
99
100     private boolean isInitialProcessingCompleted(final long currentTimestamp, final long firstRequestTimestamp) {
101         return currentTimestamp - firstRequestTimestamp >= moduleInitialProcessingDelayMs;
102     }
103
104     private long calculateRemainingProcessingTime(final long currentTimestamp, final long firstRequestTimestamp) {
105         return moduleInitialProcessingDelayMs - (currentTimestamp - firstRequestTimestamp);
106     }
107 }