Custom detekt rule for logger usage check
[dcaegen2/collectors/hv-ves.git] / sources / hv-collector-core / src / main / kotlin / org / onap / dcae / collectors / veshv / impl / wire / WireChunkDecoder.kt
1 /*
2  * ============LICENSE_START=======================================================
3  * dcaegen2-collectors-veshv
4  * ================================================================================
5  * Copyright (C) 2018 NOKIA
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 package org.onap.dcae.collectors.veshv.impl.wire
21
22 import arrow.effects.IO
23 import io.netty.buffer.ByteBuf
24 import io.netty.buffer.ByteBufAllocator
25 import org.onap.dcae.collectors.veshv.domain.WireFrameMessage
26 import org.onap.dcae.collectors.veshv.domain.WireFrameDecoder
27 import org.onap.dcae.collectors.veshv.domain.InvalidWireFrame
28 import org.onap.dcae.collectors.veshv.domain.WireFrameDecodingError
29 import org.onap.dcae.collectors.veshv.domain.MissingWireFrameBytes
30 import org.onap.dcae.collectors.veshv.utils.logging.Logger
31 import org.onap.dcae.collectors.veshv.utils.logging.handleReactiveStreamError
32 import reactor.core.publisher.Flux
33 import reactor.core.publisher.SynchronousSink
34
35 /**
36  * @author Piotr Jaszczyk <piotr.jaszczyk@nokia.com>
37  * @since May 2018
38  */
39 internal class WireChunkDecoder(
40         private val decoder: WireFrameDecoder,
41         alloc: ByteBufAllocator = ByteBufAllocator.DEFAULT) {
42     private val streamBuffer = alloc.compositeBuffer()
43
44     fun release() {
45         streamBuffer.release()
46     }
47
48     fun decode(byteBuf: ByteBuf): Flux<WireFrameMessage> = Flux.defer {
49         logIncomingMessage(byteBuf)
50         if (byteBuf.readableBytes() == 0) {
51             byteBuf.release()
52             Flux.empty()
53         } else {
54             streamBuffer.addComponent(true, byteBuf)
55             generateFrames()
56                     .onErrorResume { logger.handleReactiveStreamError(it, Flux.error(it)) }
57                     .doFinally { streamBuffer.discardReadComponents() }
58         }
59     }
60
61     private fun generateFrames(): Flux<WireFrameMessage> = Flux.generate { next ->
62         decoder.decodeFirst(streamBuffer)
63                 .fold(onError(next), onSuccess(next))
64                 .unsafeRunSync()
65     }
66
67     private fun onError(next: SynchronousSink<WireFrameMessage>): (WireFrameDecodingError) -> IO<Unit> = { err ->
68         when (err) {
69             is InvalidWireFrame -> IO {
70                 next.error(WireFrameException(err))
71             }
72             is MissingWireFrameBytes -> IO {
73                 logEndOfData()
74                 next.complete()
75             }
76         }
77     }
78
79     private fun onSuccess(next: SynchronousSink<WireFrameMessage>): (WireFrameMessage) -> IO<Unit> = { frame ->
80         IO {
81             logDecodedWireMessage(frame)
82             next.next(frame)
83         }
84     }
85
86     private fun logIncomingMessage(wire: ByteBuf) {
87         logger.trace { "Got message with total size of ${wire.readableBytes()} B" }
88     }
89
90     private fun logDecodedWireMessage(wire: WireFrameMessage) {
91         logger.trace { "Wire payload size: ${wire.payloadSize} B" }
92     }
93
94     private fun logEndOfData() {
95         logger.trace { "End of data in current TCP buffer" }
96     }
97
98     companion object {
99         val logger = Logger(WireChunkDecoder::class)
100     }
101 }