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