forked from RPCS3/discord-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStatsStorage.cs
102 lines (97 loc) · 4.29 KB
/
StatsStorage.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using CompatBot.Utils;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
namespace CompatBot.Database.Providers
{
internal static class StatsStorage
{
internal static readonly TimeSpan CacheTime = TimeSpan.FromDays(1);
internal static readonly MemoryCache CmdStatCache = new MemoryCache(new MemoryCacheOptions { ExpirationScanFrequency = TimeSpan.FromDays(1) });
internal static readonly MemoryCache ExplainStatCache = new MemoryCache(new MemoryCacheOptions { ExpirationScanFrequency = TimeSpan.FromDays(1) });
internal static readonly MemoryCache GameStatCache = new MemoryCache(new MemoryCacheOptions { ExpirationScanFrequency = TimeSpan.FromDays(1) });
private static readonly SemaphoreSlim barrier = new SemaphoreSlim(1, 1);
private static readonly (string name, MemoryCache cache)[] AllCaches =
{
(nameof(CmdStatCache), CmdStatCache),
(nameof(ExplainStatCache), ExplainStatCache),
(nameof(GameStatCache), GameStatCache),
};
public static async Task SaveAsync(bool wait = false)
{
if (await barrier.WaitAsync(0).ConfigureAwait(false))
{
try
{
Config.Log.Debug("Got stats saving lock");
using (var db = new BotDb())
{
db.Stats.RemoveRange(db.Stats);
await db.SaveChangesAsync().ConfigureAwait(false);
foreach (var cache in AllCaches)
{
var category = cache.name;
var entries = cache.cache.GetCacheEntries<string>();
var savedKeys = new HashSet<string>();
foreach (var entry in entries)
if (savedKeys.Add(entry.Key))
await db.Stats.AddAsync(new Stats
{
Category = category,
Key = entry.Key,
Value = ((int?) entry.Value.Value) ?? 0,
ExpirationTimestamp = entry.Value.AbsoluteExpiration?.ToUniversalTime().Ticks ?? 0
}).ConfigureAwait(false);
else
Config.Log.Warn($"Somehow there's another '{entry.Key}' in the {category} cache");
}
await db.SaveChangesAsync().ConfigureAwait(false);
}
}
catch(Exception e)
{
Config.Log.Error(e, "Failed to save user stats");
}
finally
{
barrier.Release();
Config.Log.Debug("Released stats saving lock");
}
}
else if (wait)
{
await barrier.WaitAsync().ConfigureAwait(false);
barrier.Release();
}
}
public static async Task RestoreAsync()
{
var now = DateTime.UtcNow;
using (var db = new BotDb())
foreach (var cache in AllCaches)
{
var category = cache.name;
var entries = await db.Stats.Where(e => e.Category == category).ToListAsync().ConfigureAwait(false);
foreach (var entry in entries)
{
var time = entry.ExpirationTimestamp.AsUtc();
if (time > now)
cache.cache.Set(entry.Key, entry.Value, time);
}
}
}
public static async Task BackgroundSaveAsync()
{
while (!Config.Cts.IsCancellationRequested)
{
await Task.Delay(60 * 60 * 1000, Config.Cts.Token).ConfigureAwait(false);
if (!Config.Cts.IsCancellationRequested)
await SaveAsync().ConfigureAwait(false);
}
}
}
}