|
| 1 | +/* |
| 2 | + * Licensed to the Apache Software Foundation (ASF) under one or more |
| 3 | + * contributor license agreements. See the NOTICE file distributed with |
| 4 | + * this work for additional information regarding copyright ownership. |
| 5 | + * The ASF licenses this file to You under the Apache License, Version 2.0 |
| 6 | + * (the "License"); you may not use this file except in compliance with |
| 7 | + * the License. You may obtain a copy of the License at |
| 8 | + * |
| 9 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | + * |
| 11 | + * Unless required by applicable law or agreed to in writing, software |
| 12 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | + * See the License for the specific language governing permissions and |
| 15 | + * limitations under the License. |
| 16 | + */ |
| 17 | + |
| 18 | +package org.apache.commons.io.input; |
| 19 | + |
| 20 | +import java.io.IOException; |
| 21 | +import java.io.InputStream; |
| 22 | +import java.io.InterruptedIOException; |
| 23 | +import java.time.Duration; |
| 24 | +import java.time.temporal.ChronoUnit; |
| 25 | +import java.util.concurrent.TimeUnit; |
| 26 | + |
| 27 | +import org.apache.commons.io.build.AbstractStreamBuilder; |
| 28 | + |
| 29 | +/** |
| 30 | + * Provides bandwidth throttling on a specified InputStream. It is implemented as a wrapper on top of another InputStream instance. The throttling works by |
| 31 | + * examining the number of bytes read from the underlying InputStream from the beginning, and sleep()ing for a time interval if the byte-transfer is found |
| 32 | + * exceed the specified tolerable maximum. (Thus, while the read-rate might exceed the maximum for a given short interval, the average tends towards the |
| 33 | + * specified maximum, overall.) |
| 34 | + * <p> |
| 35 | + * Inspired by Apache HBase's class of the same name. |
| 36 | + * </p> |
| 37 | + * |
| 38 | + * @since 2.16.0 |
| 39 | + */ |
| 40 | +public final class ThrottledInputStream extends CountingInputStream { |
| 41 | + |
| 42 | + /** |
| 43 | + * Builds a new {@link QueueInputStream} instance. |
| 44 | + * <h2>Using NIO</h2> |
| 45 | + * |
| 46 | + * <pre>{@code |
| 47 | + * ThrottledInputStream s = ThrottledInputStream.builder().setPath(Paths.get("MyFile.xml")).setMaxBytesPerSecond(100_000).get(); |
| 48 | + * } |
| 49 | + * </pre> |
| 50 | + * |
| 51 | + * <h2>Using IO</h2> |
| 52 | + * |
| 53 | + * <pre>{@code |
| 54 | + * ThrottledInputStream s = ThrottledInputStream.builder().setFile(new File("MyFile.xml")).setMaxBytesPerSecond(100_000).get(); |
| 55 | + * } |
| 56 | + * </pre> |
| 57 | + * |
| 58 | + * <pre>{@code |
| 59 | + * ThrottledInputStream s = ThrottledInputStream.builder().setInputStream(inputStream).setMaxBytesPerSecond(100_000).get(); |
| 60 | + * } |
| 61 | + * </pre> |
| 62 | + */ |
| 63 | + public static class Builder extends AbstractStreamBuilder<ThrottledInputStream, Builder> { |
| 64 | + |
| 65 | + /** |
| 66 | + * Effectively not throttled. |
| 67 | + */ |
| 68 | + private long maxBytesPerSecond = Long.MAX_VALUE; |
| 69 | + |
| 70 | + @SuppressWarnings("resource") |
| 71 | + @Override |
| 72 | + public ThrottledInputStream get() throws IOException { |
| 73 | + return new ThrottledInputStream(getInputStream(), maxBytesPerSecond); |
| 74 | + } |
| 75 | + |
| 76 | + /** |
| 77 | + * Sets the maximum bytes per second. |
| 78 | + * |
| 79 | + * @param maxBytesPerSecond the maximum bytes per second. |
| 80 | + */ |
| 81 | + public void setMaxBytesPerSecond(final long maxBytesPerSecond) { |
| 82 | + this.maxBytesPerSecond = maxBytesPerSecond; |
| 83 | + } |
| 84 | + |
| 85 | + } |
| 86 | + |
| 87 | + /** |
| 88 | + * Constructs a new {@link Builder}. |
| 89 | + * |
| 90 | + * @return a new {@link Builder}. |
| 91 | + */ |
| 92 | + public static Builder builder() { |
| 93 | + return new Builder(); |
| 94 | + } |
| 95 | + |
| 96 | + static long toSleepMillis(final long bytesRead, final long maxBytesPerSec, final long elapsedMillis) { |
| 97 | + assert elapsedMillis >= 0 : "The elapsed time should be greater or equal to zero"; |
| 98 | + if (bytesRead <= 0 || maxBytesPerSec <= 0 || elapsedMillis == 0) { |
| 99 | + return 0; |
| 100 | + } |
| 101 | + // We use this class to load the single source file, so the bytesRead |
| 102 | + // and maxBytesPerSec aren't greater than Double.MAX_VALUE. |
| 103 | + // We can get the precise sleep time by using the double value. |
| 104 | + final long millis = (long) ((double) bytesRead / (double) maxBytesPerSec * 1000 - elapsedMillis); |
| 105 | + if (millis <= 0) { |
| 106 | + return 0; |
| 107 | + } |
| 108 | + return millis; |
| 109 | + } |
| 110 | + |
| 111 | + private final long maxBytesPerSecond; |
| 112 | + private final long startTime = System.currentTimeMillis(); |
| 113 | + private Duration totalSleepDuration = Duration.ZERO; |
| 114 | + |
| 115 | + private ThrottledInputStream(final InputStream proxy, final long maxBytesPerSecond) { |
| 116 | + super(proxy); |
| 117 | + assert maxBytesPerSecond > 0 : "Bandwidth " + maxBytesPerSecond + " is invalid."; |
| 118 | + this.maxBytesPerSecond = maxBytesPerSecond; |
| 119 | + } |
| 120 | + |
| 121 | + /** |
| 122 | + * Gets the read-rate from this stream, since creation. Calculated as bytesRead/elapsedTimeSinceStart. |
| 123 | + * |
| 124 | + * @return Read rate, in bytes/sec. |
| 125 | + */ |
| 126 | + public long getBytesPerSecond() { |
| 127 | + final long elapsedSeconds = (System.currentTimeMillis() - startTime) / 1000; |
| 128 | + if (elapsedSeconds == 0) { |
| 129 | + return getByteCount(); |
| 130 | + } |
| 131 | + return getByteCount() / elapsedSeconds; |
| 132 | + } |
| 133 | + |
| 134 | + private long getSleepMillis() { |
| 135 | + return toSleepMillis(getByteCount(), maxBytesPerSecond, System.currentTimeMillis() - startTime); |
| 136 | + } |
| 137 | + |
| 138 | + /** |
| 139 | + * Gets the total duration spent in sleep. |
| 140 | + * |
| 141 | + * @return Duration spent in sleep. |
| 142 | + */ |
| 143 | + public Duration getTotalSleepDuration() { |
| 144 | + return totalSleepDuration; |
| 145 | + } |
| 146 | + |
| 147 | + @Override |
| 148 | + protected void beforeRead(final int n) throws IOException { |
| 149 | + throttle(); |
| 150 | + } |
| 151 | + |
| 152 | + private void throttle() throws InterruptedIOException { |
| 153 | + final long sleepMillis = getSleepMillis(); |
| 154 | + if (sleepMillis > 0) { |
| 155 | + totalSleepDuration = totalSleepDuration.plus(sleepMillis, ChronoUnit.MILLIS); |
| 156 | + try { |
| 157 | + TimeUnit.MILLISECONDS.sleep(sleepMillis); |
| 158 | + } catch (final InterruptedException e) { |
| 159 | + throw new InterruptedIOException("Thread aborted"); |
| 160 | + } |
| 161 | + } |
| 162 | + } |
| 163 | + |
| 164 | + /** {@inheritDoc} */ |
| 165 | + @Override |
| 166 | + public String toString() { |
| 167 | + return "ThrottledInputStream[bytesRead=" + getCount() + ", maxBytesPerSec=" + maxBytesPerSecond + ", bytesPerSec=" + getBytesPerSecond() |
| 168 | + + ", totalSleepDuration=" + totalSleepDuration + ']'; |
| 169 | + } |
| 170 | +} |
0 commit comments