Add time at start of filtering during which no delay will occur.
[sonitus.git] / src / main / java / net / pterodactylus / sonitus / data / filter / RateLimitingFilter.java
1 /*
2  * Sonitus - DelayFilter.java - Copyright © 2013 David Roden
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
16  */
17
18 package net.pterodactylus.sonitus.data.filter;
19
20 import java.io.EOFException;
21 import java.io.IOException;
22 import java.util.logging.Logger;
23
24 import net.pterodactylus.sonitus.data.ConnectException;
25 import net.pterodactylus.sonitus.data.Filter;
26 import net.pterodactylus.sonitus.data.Metadata;
27 import net.pterodactylus.sonitus.data.Source;
28
29 import com.google.common.base.Preconditions;
30
31 /**
32  * Rate limiting filter that only passes a specified amount of data per second
33  * from its {@link Source} to its {@link net.pterodactylus.sonitus.data.Sink}.
34  *
35  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
36  */
37 public class RateLimitingFilter implements Filter {
38
39         /** The logger. */
40         private static final Logger logger = Logger.getLogger(RateLimitingFilter.class.getName());
41
42         /** The limiting rate in bytes/second. */
43         private final int rate;
44
45         /** The fast start time. */
46         private final long fastStartTime;
47
48         /** The source. */
49         private Source source;
50
51         /** The remaining fast start time. */
52         private long remainingFastStartTime;
53
54         /**
55          * Creates a new rate limiting filter.
56          *
57          * @param rate
58          *              The limiting rate (in bytes/second)
59          */
60         public RateLimitingFilter(int rate) {
61                 this(rate, 0);
62         }
63
64         /**
65          * Creates a new rate limiting filter.
66          *
67          * @param rate
68          *              The limiting rate (in bytes/second)
69          * @param fastStartTime
70          *              The amount of time at the start of the filtering during which no delay
71          *              will occur (in milliseconds)
72          */
73         public RateLimitingFilter(int rate, long fastStartTime) {
74                 this.rate = rate;
75                 this.fastStartTime = fastStartTime;
76                 remainingFastStartTime = fastStartTime;
77         }
78
79         //
80         // FILTER METHODS
81         //
82
83         @Override
84         public Metadata metadata() {
85                 return source.metadata();
86         }
87
88         @Override
89         public byte[] get(int bufferSize) throws EOFException, IOException {
90                 long now = System.currentTimeMillis();
91                 byte[] buffer = source.get(bufferSize);
92                 /* delay. */
93                 long waitTime = 1000 * buffer.length / rate;
94                 remainingFastStartTime = Math.max(remainingFastStartTime - waitTime, 0);
95                 while ((remainingFastStartTime == 0) && (System.currentTimeMillis() - now) < waitTime) {
96                         try {
97                                 long limitDelay = waitTime - (System.currentTimeMillis() - now);
98                                 logger.finest(String.format("Waiting %d ms...", limitDelay));
99                                 Thread.sleep(limitDelay);
100                         } catch (InterruptedException ie1) {
101                                 /* ignore, keep looping. */
102                         }
103                 }
104                 return buffer;
105         }
106
107         @Override
108         public void connect(Source source) throws ConnectException {
109                 Preconditions.checkNotNull(source, "source must not be null");
110
111                 this.source = source;
112         }
113
114         @Override
115         public void metadataUpdated() {
116                 /* ignore. */
117         }
118
119 }