RegexBot/Kerobot/Services/GuildState/StateInfo.cs

51 lines
1.5 KiB
C#
Raw Normal View History

using Newtonsoft.Json.Linq;
using System;
namespace Kerobot.Services.GuildState
{
/// <summary>
/// Contains a guild state object and other useful metadata in regards to it.
/// </summary>
class StateInfo : IDisposable
{
static readonly TimeSpan TimeUntilStale = new TimeSpan(0, 15, 0);
2018-06-06 22:19:21 +00:00
/// <summary>
/// Module-provided data.
/// </summary>
2018-06-06 22:19:21 +00:00
public object Data { get; }
/// <summary>
/// Hash of the JToken used to generate the data. In certain casaes, it is used to check
/// if the configuration may be stale and needs to be reloaded.
/// </summary>
private readonly int _configHash;
2018-06-06 22:19:21 +00:00
private DateTimeOffset _lastStaleCheck;
public StateInfo(object data, int configHash)
{
2018-06-06 22:19:21 +00:00
Data = data;
_configHash = configHash;
2018-06-06 22:19:21 +00:00
_lastStaleCheck = DateTimeOffset.UtcNow;
}
public void Dispose()
{
2018-06-06 22:19:21 +00:00
if (Data is IDisposable dd) { dd.Dispose(); }
}
/// <summary>
2018-06-06 22:19:21 +00:00
/// Checks if the current data may be stale, based on the last staleness check or
/// if the underlying configuration has changed.
/// </summary>
public bool IsStale(JToken comparison)
{
2018-06-06 22:19:21 +00:00
if (DateTimeOffset.UtcNow - _lastStaleCheck > TimeUntilStale) return true;
if (comparison.GetHashCode() != _configHash) return true;
2018-06-06 22:19:21 +00:00
_lastStaleCheck = DateTimeOffset.UtcNow;
return false;
}
}
}