/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.flink.streaming.runtime.tasks.bufferdebloat;

import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.TaskManagerOptions;
import org.apache.flink.runtime.io.network.partition.consumer.IndexedInputGate;

import static org.apache.flink.configuration.TaskManagerOptions.BUFFER_DEBLOAT_TARGET;
import static org.apache.flink.configuration.TaskManagerOptions.BUFFER_DEBLOAT_THRESHOLD_PERCENTAGES;
import static org.apache.flink.util.Preconditions.checkArgument;

/**
 * Class for automatic calculation of the buffer size based on the current throughput and
 * configuration.
 */
public class BufferDebloater {
    private static final double MILLIS_IN_SECOND = 1000.0;

    /**
     * How different should be the total buffer size compare to throughput (when it is 1.0 then
     * bufferSize == throughput).
     */
    private final double targetBufferSizeFactor;

    private final IndexedInputGate[] inputGates;
    private final long maxBufferSize;
    private final long minBufferSize;
    private final int bufferDebloatThresholdPercentages;

    private int lastBufferSize;

    public BufferDebloater(Configuration taskConfig, IndexedInputGate[] inputGates) {
        this.inputGates = inputGates;
        this.targetBufferSizeFactor =
                taskConfig.get(BUFFER_DEBLOAT_TARGET).toMillis() / MILLIS_IN_SECOND;
        this.maxBufferSize = taskConfig.get(TaskManagerOptions.MEMORY_SEGMENT_SIZE).getBytes();
        this.minBufferSize = taskConfig.get(TaskManagerOptions.MIN_MEMORY_SEGMENT_SIZE).getBytes();

        this.bufferDebloatThresholdPercentages =
                taskConfig.getInteger(BUFFER_DEBLOAT_THRESHOLD_PERCENTAGES);

        this.lastBufferSize = (int) maxBufferSize;

        // Right now the buffer size can not be grater than integer max value according to
        // MemorySegment and buffer implementation.
        checkArgument(maxBufferSize <= Integer.MAX_VALUE);
        checkArgument(maxBufferSize > 0);
        checkArgument(minBufferSize > 0);
        checkArgument(maxBufferSize >= minBufferSize);
        checkArgument(targetBufferSizeFactor > 0.0);
    }

    public void recalculateBufferSize(long currentThroughput) {
        long desiredTotalBufferSizeInBytes = (long) (currentThroughput * targetBufferSizeFactor);

        int totalNumber = 0;
        for (IndexedInputGate inputGate : inputGates) {
            totalNumber += Math.max(1, inputGate.getBuffersInUseCount());
        }
        int newSize =
                (int)
                        Math.max(
                                minBufferSize,
                                Math.min(
                                        desiredTotalBufferSizeInBytes / totalNumber,
                                        maxBufferSize));

        boolean skipUpdate =
                Math.abs(1 - ((double) lastBufferSize) / newSize) * 100
                        < bufferDebloatThresholdPercentages;

        // Skip update if the new value pretty close to the old one.
        if (skipUpdate) {
            return;
        }

        lastBufferSize = newSize;
        for (IndexedInputGate inputGate : inputGates) {
            inputGate.announceBufferSize(newSize);
        }
    }
}

@@ -1057,16 +1057,44 @@
 tGate;%0A%0A
+import java.time.Duration;%0A%0A
 import s
@@ -1512,22 +1512,20 @@
 c final 
-double
+long
  MILLIS_
@@ -1544,159 +1544,11 @@
 1000
-.0
 ;%0A%0A
-    /**%0A     * How different should be the total buffer size compare to throughput (when it is 1.0 then%0A     * bufferSize == throughput).%0A     */%0A
     
@@ -1565,21 +1565,28 @@
 nal 
-double
+Duration
  target
+Total
 Buff
@@ -1595,16 +1595,9 @@
 Size
-Factor;%0A
+;
 %0A   
@@ -1948,24 +1948,29 @@
  this.target
+Total
 BufferSizeFa
@@ -1971,32 +1971,10 @@
 Size
-Factor =%0A              
  
+=
  tas
@@ -2011,38 +2011,8 @@
 GET)
-.toMillis() / MILLIS_IN_SECOND
 ;%0A  
@@ -2750,24 +2750,29 @@
 ument(target
+Total
 BufferSizeFa
@@ -2769,22 +2769,27 @@
 fferSize
-Factor
+.toMillis()
  %3E 0.0);
@@ -2908,15 +2908,24 @@
 es =
- (long)
+%0A               
  (cu
@@ -2948,16 +2948,21 @@
 * target
+Total
 BufferSi
@@ -2967,15 +2967,39 @@
 Size
-Factor)
+.toMillis()) / MILLIS_IN_SECOND
 ;%0A%0A 

Rename BufferDebloater#targetBufferSizeFactor