All Downloads are FREE. Search and download functionalities are using the official Maven repository.

csharp.libraries.generichost.TokenBase.mustache Maven / Gradle / Ivy

There is a newer version: 7.9.0
Show newest version
// 
{{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);
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy