b7c4ec66689e82e961438d09c4f9e1aa40a1fc13
[nonrtric.git] / dmaap-adaptor-java / src / main / java / org / oran / dmaapadapter / tasks / DmaapMessageConsumer.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 DmaapMessageConsumer {
43     private static final Duration TIME_BETWEEN_DMAAP_RETRIES = Duration.ofSeconds(10);
44     private static final Logger logger = LoggerFactory.getLogger(DmaapMessageConsumer.class);
45     private final ApplicationConfig applicationConfig;
46     private final AsyncRestClient dmaapRestClient;
47     private final AsyncRestClient consumerRestClient;
48     private final InfoType type;
49     private final Jobs jobs;
50     private final InfiniteFlux infiniteSubmitter = new InfiniteFlux();
51
52     /** Submits new elements until stopped */
53     private static class InfiniteFlux {
54         private FluxSink<Integer> sink;
55         private int counter = 0;
56
57         public synchronized Flux<Integer> start() {
58             stop();
59             return Flux.create(this::next).doOnRequest(this::onRequest);
60         }
61
62         public synchronized void stop() {
63             if (this.sink != null) {
64                 this.sink.complete();
65                 this.sink = null;
66             }
67         }
68
69         void onRequest(long no) {
70             logger.debug("InfiniteFlux.onRequest {}", no);
71             for (long i = 0; i < no; ++i) {
72                 sink.next(counter++);
73             }
74         }
75
76         void next(FluxSink<Integer> sink) {
77             logger.debug("InfiniteFlux.next");
78             this.sink = sink;
79             sink.next(counter++);
80         }
81     }
82
83     public DmaapMessageConsumer(ApplicationConfig applicationConfig, InfoType type, Jobs jobs) {
84         this.applicationConfig = applicationConfig;
85         AsyncRestClientFactory restclientFactory = new AsyncRestClientFactory(applicationConfig.getWebClientConfig());
86         this.dmaapRestClient = restclientFactory.createRestClientNoHttpProxy("");
87         this.consumerRestClient = type.isUseHttpProxy() ? restclientFactory.createRestClientUseHttpProxy("")
88                 : restclientFactory.createRestClientNoHttpProxy("");
89         this.type = type;
90         this.jobs = jobs;
91     }
92
93     public void start() {
94         infiniteSubmitter.start() //
95                 .flatMap(notUsed -> getFromMessageRouter(getDmaapUrl()), 1) //
96                 .flatMap(this::handleReceivedMessage, 5) //
97                 .subscribe(//
98                         value -> logger.debug("DmaapMessageConsumer next: {} {}", value, type.getId()), //
99                         throwable -> logger.error("DmaapMessageConsumer error: {}", throwable.getMessage()), //
100                         () -> logger.warn("DmaapMessageConsumer stopped {}", type.getId()) //
101                 );
102     }
103
104     private String getDmaapUrl() {
105
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) //
112                 .flatMap(notUsed -> Mono.empty());
113     }
114
115     private Mono<String> handleConsumerErrorResponse(Throwable t) {
116         logger.warn("error from CONSUMER {}", t.getMessage());
117         return Mono.empty();
118     }
119
120     protected Mono<String> getFromMessageRouter(String topicUrl) {
121         logger.trace("getFromMessageRouter {}", topicUrl);
122         return dmaapRestClient.get(topicUrl) //
123                 .filter(body -> body.length() > 3) // DMAAP will return "[]" sometimes. That is thrown away.
124                 .doOnNext(message -> logger.debug("Message from DMAAP topic: {} : {}", topicUrl, message)) //
125                 .onErrorResume(this::handleDmaapErrorResponse); //
126     }
127
128     protected Flux<String> handleReceivedMessage(String body) {
129         logger.debug("Received from DMAAP {}", body);
130         final int CONCURRENCY = 5;
131
132         // Distibute the body to all jobs for this type
133         return Flux.fromIterable(this.jobs.getJobsForType(this.type)) //
134                 .doOnNext(job -> logger.debug("Sending to consumer {}", job.getCallbackUrl()))
135                 .flatMap(job -> consumerRestClient.post(job.getCallbackUrl(), body), CONCURRENCY) //
136                 .onErrorResume(this::handleConsumerErrorResponse);
137     }
138
139 }