Fix of Sonar coverage for O-RU Closed Loop Consumer
[nonrtric.git] / dmaap-adaptor-java / src / main / java / org / oran / dmaapadapter / tasks / DmaapTopicConsumer.java
1 /*-
2  * ========================LICENSE_START=================================
3  * O-RAN-SC
4  * %%
5  * Copyright (C) 2021 Nordix Foundation
6  * %%
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ========================LICENSE_END===================================
19  */
20
21 package org.oran.dmaapadapter.tasks;
22
23 import java.time.Duration;
24
25 import org.oran.dmaapadapter.clients.AsyncRestClient;
26 import org.oran.dmaapadapter.clients.AsyncRestClientFactory;
27 import org.oran.dmaapadapter.configuration.ApplicationConfig;
28 import org.oran.dmaapadapter.repository.InfoType;
29 import org.oran.dmaapadapter.repository.Jobs;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
32
33 import reactor.core.publisher.Flux;
34 import reactor.core.publisher.FluxSink;
35 import reactor.core.publisher.Mono;
36
37 /**
38  * The class fetches incoming requests from DMAAP and sends them further to the
39  * consumers that has a job for this InformationType.
40  */
41
42 public class DmaapTopicConsumer {
43     private static final Duration TIME_BETWEEN_DMAAP_RETRIES = Duration.ofSeconds(10);
44     private static final Logger logger = LoggerFactory.getLogger(DmaapTopicConsumer.class);
45
46     private final AsyncRestClient dmaapRestClient;
47     private final InfiniteFlux infiniteSubmitter = new InfiniteFlux();
48     private final AsyncRestClient consumerRestClient;
49     protected final ApplicationConfig applicationConfig;
50     protected final InfoType type;
51     protected final Jobs jobs;
52
53     /** Submits new elements until stopped */
54     private static class InfiniteFlux {
55         private FluxSink<Integer> sink;
56         private int counter = 0;
57
58         public synchronized Flux<Integer> start() {
59             stop();
60             return Flux.create(this::next).doOnRequest(this::onRequest);
61         }
62
63         public synchronized void stop() {
64             if (this.sink != null) {
65                 this.sink.complete();
66                 this.sink = null;
67             }
68         }
69
70         void onRequest(long no) {
71             logger.debug("InfiniteFlux.onRequest {}", no);
72             for (long i = 0; i < no; ++i) {
73                 sink.next(counter++);
74             }
75         }
76
77         void next(FluxSink<Integer> sink) {
78             logger.debug("InfiniteFlux.next");
79             this.sink = sink;
80             sink.next(counter++);
81         }
82     }
83
84     public DmaapTopicConsumer(ApplicationConfig applicationConfig, InfoType type, Jobs jobs) {
85         AsyncRestClientFactory restclientFactory = new AsyncRestClientFactory(applicationConfig.getWebClientConfig());
86         this.dmaapRestClient = restclientFactory.createRestClientNoHttpProxy("");
87         this.applicationConfig = applicationConfig;
88         this.consumerRestClient = type.isUseHttpProxy() ? restclientFactory.createRestClientUseHttpProxy("")
89                 : restclientFactory.createRestClientNoHttpProxy("");
90         this.type = type;
91         this.jobs = jobs;
92     }
93
94     public void start() {
95         infiniteSubmitter.start() //
96                 .flatMap(notUsed -> getFromMessageRouter(getDmaapUrl()), 1) //
97                 .flatMap(this::pushDataToConsumers) //
98                 .subscribe(//
99                         null, //
100                         throwable -> logger.error("DmaapMessageConsumer error: {}", throwable.getMessage()), //
101                         () -> logger.warn("DmaapMessageConsumer stopped {}", type.getId())); //
102
103     }
104
105     private String getDmaapUrl() {
106         return this.applicationConfig.getDmaapBaseUrl() + type.getDmaapTopicUrl();
107     }
108
109     private Mono<String> handleDmaapErrorResponse(Throwable t) {
110         logger.debug("error from DMAAP {} {}", t.getMessage(), type.getDmaapTopicUrl());
111         return Mono.delay(TIME_BETWEEN_DMAAP_RETRIES).flatMap(notUsed -> Mono.empty());
112     }
113
114     private Mono<String> getFromMessageRouter(String topicUrl) {
115         logger.trace("getFromMessageRouter {}", topicUrl);
116         return dmaapRestClient.get(topicUrl) //
117                 .filter(body -> body.length() > 3) // DMAAP will return "[]" sometimes. That is thrown away.
118                 .doOnNext(message -> logger.debug("Message from DMAAP topic: {} : {}", topicUrl, message)) //
119                 .onErrorResume(this::handleDmaapErrorResponse); //
120     }
121
122     private Mono<String> handleConsumerErrorResponse(Throwable t) {
123         logger.warn("error from CONSUMER {}", t.getMessage());
124         return Mono.empty();
125     }
126
127     protected Flux<String> pushDataToConsumers(String body) {
128         logger.debug("Received data {}", body);
129         final int CONCURRENCY = 50;
130
131         // Distibute the body to all jobs for this type
132         return Flux.fromIterable(this.jobs.getJobsForType(this.type)) //
133                 .doOnNext(job -> logger.debug("Sending to consumer {}", job.getCallbackUrl()))
134                 .flatMap(job -> consumerRestClient.post(job.getCallbackUrl(), body), CONCURRENCY) //
135                 .onErrorResume(this::handleConsumerErrorResponse);
136     }
137 }