Lean  $LEAN_TAG$
TokenBucket.cs
1 /*
2  * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
3  * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14 */
15 
16 using System;
17 using System.Threading;
18 
20 {
21  /// <summary>
22  /// Provides extension methods for interacting with <see cref="ITokenBucket"/> instances as well
23  /// as access to the <see cref="NullTokenBucket"/> via <see cref="TokenBucket.Null"/>
24  /// </summary>
25  public static class TokenBucket
26  {
27  /// <summary>
28  /// Gets an <see cref="ITokenBucket"/> that always permits consumption
29  /// </summary>
30  public static ITokenBucket Null = new NullTokenBucket();
31 
32  /// <summary>
33  /// Provides an overload of <see cref="ITokenBucket.Consume"/> that accepts a <see cref="TimeSpan"/> timeout
34  /// </summary>
35  public static void Consume(this ITokenBucket bucket, long tokens, TimeSpan timeout)
36  {
37  bucket.Consume(tokens, (long) timeout.TotalMilliseconds);
38  }
39 
40  /// <summary>
41  /// Provides an implementation of <see cref="ITokenBucket"/> that does not enforce rate limiting
42  /// </summary>
43  private class NullTokenBucket : ITokenBucket
44  {
45  public long Capacity => long.MaxValue;
46  public long AvailableTokens => long.MaxValue;
47  public bool TryConsume(long tokens) { return true; }
48  public void Consume(long tokens, long timeout = Timeout.Infinite) { }
49  }
50  }
51 }