csharp.libraries.generichost.TokenBase.mustache Maven / Gradle / Ivy
//
{{partial_header}}
{{#nrt}}
#nullable enable
{{/nrt}}
using System;
namespace {{packageName}}.{{clientPackage}}
{
///
/// The base for all tokens.
///
{{>visibility}} abstract class TokenBase
{
private DateTime _nextAvailable = DateTime.UtcNow;
private object _nextAvailableLock = new object();
private readonly System.Timers.Timer _timer = new System.Timers.Timer();
internal TimeSpan? Timeout { get; set; }
internal delegate void TokenBecameAvailableEventHandler(object sender);
internal event TokenBecameAvailableEventHandler{{nrt?}} TokenBecameAvailable;
///
/// Initialize a TokenBase object.
///
///
internal TokenBase(TimeSpan? timeout = null)
{
Timeout = timeout;
if (Timeout != null)
StartTimer(Timeout.Value);
}
///
/// Starts the token's timer
///
///
internal void StartTimer(TimeSpan timeout)
{
Timeout = timeout;
_timer.Interval = Timeout.Value.TotalMilliseconds;
_timer.Elapsed += OnTimer;
_timer.AutoReset = true;
_timer.Start();
}
///
/// Returns true while the token is rate limited.
///
public bool IsRateLimited => _nextAvailable > DateTime.UtcNow;
///
/// Triggered when the server returns status code TooManyRequests
/// Once triggered the local timeout will be extended an arbitrary length of time.
///
public void BeginRateLimit()
{
lock(_nextAvailableLock)
_nextAvailable = DateTime.UtcNow.AddSeconds(5);
}
private void OnTimer(object{{nrt?}} sender, System.Timers.ElapsedEventArgs e)
{
if (TokenBecameAvailable != null && !IsRateLimited)
TokenBecameAvailable.Invoke(this);
}
}
}