Repository navigation
Expand file tree
/
Copy pathGenerator.cs
More file actions
424 lines (345 loc) · 18.2 KB
/
Copy pathGenerator.cs
File metadata and controls
424 lines (345 loc) · 18.2 KB
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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
using System.Net.Http;
using System;
using System.Data;
using System.IO;
using Amazon;
using Amazon.Runtime;
using Amazon.S3;
using Amazon.S3.Model;
using Dapper;
using Microsoft.Data.Sqlite;
using MySqlConnector;
using SharpCompress.Compressors;
using SharpCompress.Compressors.BZip2;
namespace osu.Server.OnlineDbGenerator
{
public class Generator
{
/// <summary>
/// Path to the output online.db cache file.
/// </summary>
private static string sqliteFilePath => Environment.GetEnvironmentVariable("SQLITE_PATH") ?? "sqlite/online.db";
/// <summary>
/// Path to the bz2-compressed online.db cache file.
/// </summary>
private static string sqliteBz2FilePath => $"{sqliteFilePath}.bz2";
/// <summary>
/// Conditional to filter beatmaps and beatmapsets by.
/// </summary>
private const string beatmap_filter_conditions = "approved IN (1, 2, 4)";
private const string beatmap_id_in_filter = $" WHERE `beatmap_id` IN (SELECT `beatmap_id` FROM `osu_beatmaps` WHERE {beatmap_filter_conditions})";
/// <summary>
/// Start generating the online.db file.
/// </summary>
public void Run()
{
using (var sqlite = getSqliteConnection())
using (var mysql = getMySqlConnection())
{
Console.WriteLine("Starting generator...");
createSchema(sqlite);
Console.WriteLine("Created schema.");
copyBeatmapSets(mysql, sqlite);
copyBeatmaps(mysql, sqlite);
copyTags(mysql, sqlite);
copyBeatmapTags(mysql, sqlite);
copyUsernames(mysql, sqlite);
copyBeatmapOwners(mysql, sqlite);
Console.WriteLine("Compressing...");
using (var inStream = File.OpenRead(sqliteFilePath))
using (var outStream = File.OpenWrite(sqliteBz2FilePath))
using (var bz2 = BZip2Stream.Create(outStream, CompressionMode.Compress, false))
inStream.CopyTo(bz2);
if (Environment.GetEnvironmentVariable("S3_KEY") != null)
{
Console.WriteLine("Uploading to S3...");
using (var stream = File.OpenRead(sqliteBz2FilePath))
Upload("assets.ppy.sh", "client-resources/online.db.bz2", stream, stream.Length, "application/x-bzip2");
if (Environment.GetEnvironmentVariable("S3_PROXY_CACHE_PURGE_KEY") != null)
{
Console.WriteLine("Purging s3-nginx-proxy cache...");
PurgeCache("https://assets.ppy.sh/client-resources/online.db.bz2", Environment.GetEnvironmentVariable("S3_PROXY_CACHE_PURGE_KEY"));
}
}
}
Console.WriteLine("All done!");
}
/// <summary>
/// Create the schema inside the online.db SQLite database.
/// </summary>
/// <param name="sqlite"></param>
private void createSchema(SqliteConnection sqlite)
{
sqlite.Execute("CREATE TABLE `schema_version` (`number` smallint unsigned NOT NULL)");
sqlite.Execute("INSERT INTO `schema_version` (`number`) VALUES (4)");
sqlite.Execute(
"""
CREATE TABLE `osu_beatmapsets` (
`beatmapset_id` mediumint unsigned NOT NULL,
`user_id` mediumint unsigned NOT NULL,
`submit_date` timestamp NOT NULL DEFAULT NULL,
`approved_date` timestamp NULL DEFAULT NULL,
`approved` timestamp NULL DEFAULT NULL,
`nsfw` tinyint(1) NOT NULL DEFAULT 0,
`anime_cover` tinyint(1) NOT NULL DEFAULT 0,
`offset` smallint NOT NULL DEFAULT 0,
PRIMARY KEY (`beatmapset_id`))
""");
sqlite.Execute(
"""
CREATE TABLE `osu_beatmaps` (
`beatmap_id` mediumint unsigned NOT NULL,
`beatmapset_id` mediumint unsigned DEFAULT NULL,
`user_id` int unsigned NOT NULL DEFAULT '0',
`filename` varchar(150) DEFAULT NULL,
`checksum` varchar(32) DEFAULT NULL,
`approved` tinyint NOT NULL DEFAULT '0',
`last_update` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`beatmap_id`))
""");
sqlite.Execute("CREATE INDEX `beatmapset_id` ON osu_beatmaps (`beatmapset_id`)");
sqlite.Execute("CREATE INDEX `filename` ON osu_beatmaps (`filename`)");
sqlite.Execute("CREATE INDEX `checksum` ON osu_beatmaps (`checksum`)");
sqlite.Execute("CREATE INDEX `user_id` ON osu_beatmaps (`user_id`)");
sqlite.Execute(
"""
CREATE TABLE `tags` (
`id` bigint unsigned NOT NULL,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`))
""");
sqlite.Execute(
"""
CREATE TABLE `beatmap_tags` (
`beatmap_id` int unsigned NOT NULL,
`tag_id` int unsigned NOT NULL,
PRIMARY KEY (`beatmap_id`, `tag_id`))
""");
sqlite.Execute(
"""
CREATE TABLE `users` (
`user_id` int unsigned NOT NULL,
`username` varchar(255) DEFAULT NULL,
PRIMARY KEY (`user_id`))
""");
sqlite.Execute(
"""
CREATE TABLE `beatmap_owners` (
`beatmap_id` mediumint unsigned NOT NULL,
`user_id` int unsigned NOT NULL,
PRIMARY KEY (`beatmap_id`, `user_id`))
""");
}
/// <summary>
/// Copy all beatmaps from online MySQL database to cache SQLite database.
/// </summary>
private void copyBeatmapSets(IDbConnection source, IDbConnection destination)
{
int sourceCount = source.QuerySingle<int>($"SELECT COUNT(beatmapset_id) FROM osu_beatmapsets WHERE {beatmap_filter_conditions}", commandTimeout: 600_000);
Console.WriteLine($"Copying {sourceCount} beatmap sets...");
var start = DateTime.Now;
int processedItems = 0;
// only include "permanent" states – ranked, approved, loved.
// this cache may be preferred for initial metadata fetches in lazer so we don't want to include any beatmaps which are still shifting in state.
var sourceBeatmapSets = source.Query<BeatmapSetRow>($"SELECT beatmapset_id, user_id, approved, approved_date, submit_date, nsfw, anime_cover, offset FROM osu_beatmapsets WHERE {beatmap_filter_conditions}",
commandTimeout: 600_000);
foreach (var beatmapset in sourceBeatmapSets)
{
destination.Execute("INSERT INTO osu_beatmapsets VALUES(@beatmapset_id, @user_id, @submit_date, @approved_date, @approved, @nsfw, @anime_cover, @offset)", beatmapset);
if (++processedItems % 1000 == 0)
Console.WriteLine($"Copied {processedItems} beatmap sets...");
}
var timespan = (DateTime.Now - start).TotalMilliseconds;
int destinationCount = destination.QuerySingle<int>("SELECT COUNT(beatmapset_id) FROM osu_beatmapsets");
Console.WriteLine($"Copied beatmap sets in {timespan}ms! (mysql:{sourceCount} sqlite:{destinationCount})");
if (destinationCount != sourceCount)
throw new Exception($"Expected {sourceCount} beatmap sets, but found {destinationCount} in sqlite! Aborting");
}
/// <summary>
/// Copy all beatmaps from online MySQL database to cache SQLite database.
/// </summary>
private void copyBeatmaps(IDbConnection source, IDbConnection destination)
{
int sourceCount = source.QuerySingle<int>($"SELECT COUNT(beatmap_id) FROM osu_beatmaps WHERE {beatmap_filter_conditions}", commandTimeout: 600_000);
Console.WriteLine($"Copying {sourceCount} beatmaps...");
var start = DateTime.Now;
int processedItems = 0;
var sourceBeatmaps = source.Query<BeatmapRow>($"SELECT beatmap_id, beatmapset_id, user_id, filename, checksum, approved, last_update FROM osu_beatmaps WHERE {beatmap_filter_conditions}",
commandTimeout: 600_000);
foreach (var beatmap in sourceBeatmaps)
{
destination.Execute("INSERT INTO osu_beatmaps VALUES(@beatmap_id, @beatmapset_id, @user_id, @filename, @checksum, @approved, @last_update)", beatmap);
if (++processedItems % 1000 == 0)
Console.WriteLine($"Copied {processedItems} beatmaps...");
}
var timespan = (DateTime.Now - start).TotalMilliseconds;
int destinationCount = destination.QuerySingle<int>($"SELECT COUNT(beatmap_id) FROM osu_beatmaps");
Console.WriteLine($"Copied beatmaps in {timespan}ms! (mysql:{sourceCount} sqlite:{destinationCount})");
if (destinationCount != sourceCount)
throw new Exception($"Expected {sourceCount} beatmaps, but found {destinationCount} in sqlite! Aborting");
}
private void copyTags(IDbConnection source, IDbConnection destination)
{
int sourceCount = source.QuerySingle<int>("SELECT COUNT(`id`) FROM `tags`", commandTimeout: 600_000);
Console.WriteLine($"Copying {sourceCount} tags...");
var start = DateTime.Now;
int processedItems = 0;
var sourceTags = source.Query<TagRow>("SELECT `id`, `name` FROM `tags`", commandTimeout: 600_000);
foreach (var tag in sourceTags)
{
destination.Execute("INSERT INTO `tags` VALUES(@id, @name)", tag);
if (++processedItems % 1000 == 0)
Console.WriteLine($"Copied {processedItems} tags...");
}
var timespan = (DateTime.Now - start).TotalMilliseconds;
int destinationCount = destination.QuerySingle<int>("SELECT COUNT(`id`) FROM tags");
Console.WriteLine($"Copied tags in {timespan}ms! (mysql:{sourceCount} sqlite:{destinationCount})");
if (destinationCount != sourceCount)
throw new Exception($"Expected {sourceCount} tags, but found {destinationCount} in sqlite! Aborting");
}
private void copyBeatmapTags(IDbConnection source, IDbConnection destination)
{
int sourceCount = source.QuerySingle<int>(
// subquery is required to get the count of rows post-grouping-and-filtering-on-vote-count
$"""
SELECT COUNT(*) FROM
(
SELECT 1 FROM `beatmap_tags`
{beatmap_id_in_filter}
GROUP BY `beatmap_id`, `tag_id`
HAVING COUNT(1) >= 5
) AS `tags`;
""", commandTimeout: 600_000);
Console.WriteLine($"Copying {sourceCount} beatmap tag pairs...");
var start = DateTime.Now;
int processedItems = 0;
var sourceBeatmapTags = source.Query<BeatmapTagRow>(
$"""
SELECT `beatmap_id`, `tag_id` FROM `beatmap_tags`
{beatmap_id_in_filter}
GROUP BY `beatmap_id`, `tag_id`
HAVING COUNT(1) >= 5
""", commandTimeout: 600_000);
foreach (var beatmapTag in sourceBeatmapTags)
{
destination.Execute("INSERT INTO `beatmap_tags` VALUES(@beatmap_id, @tag_id)", beatmapTag);
if (++processedItems % 1000 == 0)
Console.WriteLine($"Copied {processedItems} tags...");
}
var timespan = (DateTime.Now - start).TotalMilliseconds;
int destinationCount = destination.QuerySingle<int>("SELECT COUNT(1) FROM `beatmap_tags`");
Console.WriteLine($"Copied beatmap tags in {timespan}ms! (mysql:{sourceCount} sqlite:{destinationCount})");
if (destinationCount != sourceCount)
throw new Exception($"Expected {sourceCount} beatmap tags, but found {destinationCount} in sqlite! Aborting");
}
private void copyUsernames(IDbConnection source, IDbConnection destination)
{
int sourceCount = source.QuerySingle<int>(
$"""
SELECT COUNT(`user_id`) FROM `phpbb_users`
WHERE `user_id` IN (SELECT `user_id` FROM `osu_beatmaps` WHERE {beatmap_filter_conditions} UNION SELECT `user_id` FROM `beatmap_owners` {beatmap_id_in_filter})
""", commandTimeout: 600_000);
Console.WriteLine($"Copying {sourceCount} usernames...");
var start = DateTime.Now;
int processedItems = 0;
var sourceUsers = source.Query<UserRow>(
$"""
SELECT `user_id`, `username` FROM `phpbb_users`
WHERE `user_id` IN (SELECT `user_id` FROM `osu_beatmaps` WHERE {beatmap_filter_conditions} UNION SELECT `user_id` FROM `beatmap_owners` {beatmap_id_in_filter})
""", commandTimeout: 600_000);
foreach (var user in sourceUsers)
{
destination.Execute("INSERT INTO `users` VALUES(@user_id, @username)", user);
if (++processedItems % 1000 == 0)
Console.WriteLine($"Copied {processedItems} usernames...");
}
var timespan = (DateTime.Now - start).TotalMilliseconds;
int destinationCount = destination.QuerySingle<int>("SELECT COUNT(`user_id`) FROM `users`");
Console.WriteLine($"Copied usernames in {timespan}ms! (mysql:{sourceCount} sqlite:{destinationCount})");
if (destinationCount != sourceCount)
throw new Exception($"Expected {sourceCount} usernames, but found {destinationCount} in sqlite! Aborting");
}
private void copyBeatmapOwners(IDbConnection source, IDbConnection destination)
{
int sourceCount = source.QuerySingle<int>($"SELECT COUNT(1) FROM `beatmap_owners` {beatmap_id_in_filter}", commandTimeout: 600_000);
Console.WriteLine($"Copying {sourceCount} beatmap owners...");
var start = DateTime.Now;
int processedItems = 0;
var sourceBeatmapOwners = source.Query<BeatmapOwnerRow>($"SELECT `beatmap_id`, `user_id` FROM `beatmap_owners` {beatmap_id_in_filter}", commandTimeout: 600_000);
foreach (var owner in sourceBeatmapOwners)
{
destination.Execute("INSERT INTO `beatmap_owners` VALUES(@beatmap_id, @user_id)", owner);
if (++processedItems % 1000 == 0)
Console.WriteLine($"Copied {processedItems} beatmap owners...");
}
var timespan = (DateTime.Now - start).TotalMilliseconds;
int destinationCount = destination.QuerySingle<int>("SELECT COUNT(1) FROM `beatmap_owners`");
Console.WriteLine($"Copied beatmap owners in {timespan}ms! (mysql:{sourceCount} sqlite:{destinationCount})");
if (destinationCount != sourceCount)
throw new Exception($"Expected {sourceCount} beatmap owners, but found {destinationCount} in sqlite! Aborting");
}
/// <summary>
/// Get a connection to the offline SQLite cache database.
/// </summary>
/// <param name="erase">Whether to start fresh.</param>
private static SqliteConnection getSqliteConnection(bool erase = true)
{
if (erase && File.Exists(sqliteFilePath))
File.Delete(sqliteFilePath);
Directory.CreateDirectory(Path.GetDirectoryName(sqliteFilePath));
var connection = new SqliteConnection($"Data Source={sqliteFilePath}");
connection.Open();
return connection;
}
/// <summary>
/// Get a connection to the online MySQL database.
/// </summary>
private static MySqlConnection getMySqlConnection()
{
string host = (Environment.GetEnvironmentVariable("DB_HOST") ?? "localhost");
string user = (Environment.GetEnvironmentVariable("DB_USER") ?? "root");
var connection = new MySqlConnection($"Server={host};Database=osu;User ID={user};ConnectionTimeout=5;ConnectionReset=false;Pooling=true;");
connection.Open();
return connection;
}
private static AmazonS3Client getClient(RegionEndpoint endpoint = null)
{
string key = Environment.GetEnvironmentVariable("S3_KEY");
string secret = Environment.GetEnvironmentVariable("S3_SECRET");
return new AmazonS3Client(new BasicAWSCredentials(key, secret), new AmazonS3Config
{
CacheHttpClient = true,
HttpClientCacheSize = 32,
RegionEndpoint = endpoint ?? RegionEndpoint.USWest1,
UseHttp = true,
ForcePathStyle = true
});
}
public static void Upload(string bucket, string key, Stream stream, long contentLength, string contentType = null)
{
using (var client = getClient())
{
client.PutObjectAsync(new PutObjectRequest
{
BucketName = bucket,
Key = key,
CannedACL = S3CannedACL.PublicRead,
Headers =
{
ContentLength = contentLength,
ContentType = contentType,
},
InputStream = stream
}).Wait();
}
}
public static void PurgeCache(string url, string key)
{
var client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", key);
var request = client.DeleteAsync(url);
request.Wait();
request.Result.EnsureSuccessStatusCode();
}
}
}