-
Notifications
You must be signed in to change notification settings - Fork 11
/
ScoreStatisticsQueueProcessor.cs
254 lines (206 loc) · 9.61 KB
/
ScoreStatisticsQueueProcessor.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using Dapper;
using Dapper.Contrib.Extensions;
using MySqlConnector;
using osu.Framework.Extensions.TypeExtensions;
using osu.Game.Online.API.Requests.Responses;
using osu.Game.Rulesets;
using osu.Server.QueueProcessor;
using osu.Server.Queues.ScoreStatisticsProcessor.Helpers;
using osu.Server.Queues.ScoreStatisticsProcessor.Models;
using osu.Server.Queues.ScoreStatisticsProcessor.Models.Messages;
namespace osu.Server.Queues.ScoreStatisticsProcessor
{
public class ScoreStatisticsQueueProcessor : QueueProcessor<ScoreItem>
{
/// <summary>
/// version 1: basic playcount
/// version 2: total score, hit statistics, beatmap playcount, monthly playcount, max combo
/// version 3: fixed incorrect revert condition for beatmap/monthly playcount
/// version 4: uses SoloScore"V2" (moving all content to json data block)
/// version 5: added performance processor
/// version 6: added play time processor
/// version 7: added user rank count processor
/// version 8: switched total score processor from standardised score to classic score
/// version 9: added ranked score processor
/// version 10: modified play count and time processors to only track valid scores
/// version 11: modified total score processor to only count valid scores
/// </summary>
public const int VERSION = 11;
public static readonly List<Ruleset> AVAILABLE_RULESETS = getRulesets();
private readonly List<IProcessor> processors = new List<IProcessor>();
private readonly ElasticQueuePusher elasticQueueProcessor = new ElasticQueuePusher();
public ScoreStatisticsQueueProcessor(string[]? disabledProcessors = null)
: base(new QueueConfiguration { InputQueueName = "score-statistics" })
{
DapperExtensions.InstallDateTimeOffsetMapper();
List<Type> enabledTypes = createProcessors(disabledProcessors);
foreach (var t in enabledTypes)
{
if (Activator.CreateInstance(t) is IProcessor processor)
processors.Add(processor);
}
processors = processors.OrderBy(p => p.Order).ToList();
}
private List<Type> createProcessors(string[]? disabledProcessors)
{
List<Type> enabledTypes = typeof(ScoreStatisticsQueueProcessor)
.Assembly
.GetTypes()
.Where(t => !t.IsInterface && typeof(IProcessor).IsAssignableFrom(t))
.ToList();
List<Type> disabledTypes = new List<Type>();
if (disabledProcessors?.Length > 0)
{
foreach (string s in disabledProcessors)
{
var match = enabledTypes.FirstOrDefault(t => t.ReadableName() == s);
if (match == null)
throw new ArgumentException($"Could not find matching processor to disable (\"{s}\")");
enabledTypes.Remove(match);
disabledTypes.Add(match);
}
}
Console.WriteLine("Active processors:");
foreach (var type in enabledTypes)
Console.WriteLine($"- {type.ReadableName()}");
Console.WriteLine();
Console.WriteLine("Disabled processors:");
foreach (var type in disabledTypes)
Console.WriteLine($"- {type.ReadableName()}");
Console.WriteLine();
return enabledTypes;
}
protected override void ProcessResult(ScoreItem item)
{
var tags = new List<string>();
if (item.Score.legacy_score_id != null)
tags.Add("type:legacy");
if (item.ProcessHistory?.processed_version == VERSION)
{
item.Tags = tags.Append("type:skipped").ToArray();
return;
}
try
{
using (var conn = GetDatabaseConnection())
{
var scoreRow = item.Score;
var score = scoreRow.ToScoreInfo();
score.Beatmap = conn.QuerySingleOrDefault<Beatmap>("SELECT * FROM osu_beatmaps WHERE `beatmap_id` = @BeatmapId", new
{
BeatmapId = score.BeatmapID
})?.ToAPIBeatmap();
using (var transaction = conn.BeginTransaction())
{
var userStats = DatabaseHelper.GetUserStatsAsync(score, conn, transaction).Result;
if (userStats == null)
{
// ruleset could be invalid
// TODO: add check in client and server to not submit unsupported rulesets
item.Tags = tags.Append("type:no-stats").ToArray();
return;
}
// if required, we can rollback any previous version of processing then reapply with the latest.
if (item.ProcessHistory != null)
{
item.Tags = tags.Append("type:upgraded").ToArray();
byte version = item.ProcessHistory.processed_version;
foreach (var p in enumerateValidProcessors(score))
p.RevertFromUserStats(score, userStats, version, conn, transaction);
}
else
{
item.Tags = tags.Append("type:new").ToArray();
}
foreach (var p in enumerateValidProcessors(score))
p.ApplyToUserStats(score, userStats, conn, transaction);
DatabaseHelper.UpdateUserStatsAsync(userStats, conn, transaction).Wait();
updateHistoryEntry(item, conn, transaction);
transaction.Commit();
}
// Intentionally not part of the transaction to avoid deadlocks.
// See https://discord.com/channels/90072389919997952/983550677794050108/1199725169573380136
if (score.Passed)
{
// For now, just assume all passing scores are to be preserved.
conn.Execute("UPDATE scores SET preserve = 1 WHERE id = @Id", new { Id = score.ID });
}
foreach (var p in enumerateValidProcessors(score))
p.ApplyGlobal(score, conn);
}
elasticQueueProcessor.PushToQueue(new ElasticQueuePusher.ElasticScoreItem
{
ScoreId = (long)item.Score.id,
});
publishScoreProcessed(item);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
throw;
}
}
private IEnumerable<IProcessor> enumerateValidProcessors(SoloScoreInfo score)
{
IEnumerable<IProcessor> result = processors;
if (!score.Passed)
result = result.Where(p => p.RunOnFailedScores);
if (score.IsLegacyScore)
result = result.Where(p => p.RunOnLegacyScores);
return result;
}
private static void updateHistoryEntry(ScoreItem item, MySqlConnection db, MySqlTransaction transaction)
{
bool hadHistory = item.ProcessHistory != null;
item.MarkProcessed();
if (hadHistory)
db.Update(item.ProcessHistory, transaction);
else
db.Insert(item.ProcessHistory, transaction);
}
private void publishScoreProcessed(ScoreItem item)
{
Debug.Assert(item.ProcessHistory != null);
try
{
PublishMessage("osu-channel:score:processed", new ScoreProcessed
{
ScoreId = item.ProcessHistory.score_id,
ProcessedVersion = item.ProcessHistory.processed_version
});
}
catch (Exception ex)
{
// failure to deliver this message is not critical, so catch locally.
Console.WriteLine($"Error publishing {nameof(ScoreProcessed)} event: {ex}");
}
}
private static List<Ruleset> getRulesets()
{
const string ruleset_library_prefix = "osu.Game.Rulesets";
var rulesetsToProcess = new List<Ruleset>();
foreach (string file in Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, $"{ruleset_library_prefix}.*.dll"))
{
try
{
var assembly = Assembly.LoadFrom(file);
Type type = assembly.GetTypes().First(t => t.IsPublic && t.IsSubclassOf(typeof(Ruleset)));
rulesetsToProcess.Add((Ruleset)Activator.CreateInstance(type)!);
}
catch
{
throw new Exception($"Failed to load ruleset ({file})");
}
}
return rulesetsToProcess;
}
}
}