-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmaps_repo.ts
More file actions
546 lines (518 loc) · 16.9 KB
/
Copy pathmaps_repo.ts
File metadata and controls
546 lines (518 loc) · 16.9 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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
import { checkExists } from 'base/preconditions';
import { PromisedResult, Result, wrapError } from 'base/result';
import { FilterNode } from 'schema/map_filter';
import {
MapSortableAttributes,
MapValidity,
MapVisibility,
PDMap,
mapValidityEnum,
mapVisibilityEnum,
} from 'schema/maps';
import { DbError, camelCaseKeys } from 'services/db/helpers';
import { IdDomain, generateId } from 'services/db/id_gen';
import { getDbPool } from 'services/db/pool';
import {
ValidateMapDifficultyError,
ValidateMapError,
validateMap,
} from 'services/maps/map_validator';
import { SearchIndex } from 'services/search/types';
import { getServerContext } from 'services/server_context';
import snakeCaseKeys from 'snakecase-keys';
import * as db from 'zapatos/db';
import { MapArchive, S3Error, S3Handler } from './s3_handler_types';
const exists = <T>(t: T | undefined): t is NonNullable<T> => !!t;
export type FindMapsBy =
| { by: 'id'; ids: string[] }
// This should not be allowed to be performed outside of an authorized server call. Do not allow
// users to query all maps.
| { by: 'all' };
export const enum GetMapError {
MISSING_MAP = 'missing_map',
UNKNOWN_DB_ERROR = 'unknown_db_error',
}
export const enum UpdateMapError {
UNKNOWN_DB_ERROR = 'unknown_db_error',
}
export const enum DeleteMapError {
MISSING_MAP = 'missing_map',
}
type ProcessMapOpts = {
id: string;
uploader: string;
archive: MapArchive;
};
export const enum CreateMapError {
TOO_MANY_ID_GEN_ATTEMPTS = 'too_many_id_gen_attempts',
}
export const enum SearchIndexError {
SEARCH_INDEX_ERROR = 'search-index-error',
}
export class MapsRepo {
constructor(
private readonly searchIndex: SearchIndex,
private readonly s3Handler: S3Handler
) {}
// TODO: pull `userId` out as RequestContext
async findMaps(findBy: FindMapsBy, userId?: string): PromisedResult<PDMap[], DbError> {
const pool = await getDbPool();
// TODO: validate by.by === 'all' against the user role. Only an admin or root context can
// perform a query to fetch all maps.
const whereable = findBy.by === 'id' ? { id: db.conditions.isIn(findBy.ids) } : {};
try {
const maps = await db
.select(
'maps',
// Only select publicly visible maps.
{ ...whereable, visibility: MapVisibility.PUBLIC },
{
lateral: {
difficulties: db.select(
'difficulties',
{ map_id: db.parent('id') },
{
columns: ['difficulty', 'difficulty_name'],
}
),
favorites: db.count('favorites', { map_id: db.parent('id') }),
...(userId
? {
userProjection: db.selectOne(
'favorites',
{
map_id: db.parent('id'),
user_id: userId,
},
{
columns: [],
lateral: {
isFavorited: db.selectOne(
'favorites',
{
map_id: db.parent('map_id'),
user_id: userId,
},
{ alias: 'favorites2' }
),
},
}
),
}
: {}),
},
columns: [
'id',
'visibility',
'validity',
'submission_date',
'title',
'artist',
'author',
'authoring_tool',
'uploader',
'download_count',
'description',
'tags',
'complexity',
'album_art',
],
order: { by: 'title', direction: 'ASC' },
}
)
.run(pool);
return {
success: true,
value: maps.map((m) =>
PDMap.decode({
...camelCaseKeys(m),
visibility: mapVisibilityEnum.parse(m.visibility),
validity: mapValidityEnum.parse(m.validity),
userProjection: {
isFavorited: !!m.userProjection?.isFavorited,
},
})
),
};
} catch (e) {
return { success: false, errors: [wrapError(e, DbError.UNKNOWN_DB_ERROR)] };
}
}
/** User id is used for projections (favorites, etc) */
async searchMaps(searchOptions: {
user?: string;
query: string;
sort?: MapSortableAttributes;
sortDirection?: 'asc' | 'desc';
offset: number;
limit: number;
filter?: FilterNode;
}): PromisedResult<{ maps: PDMap[]; totalCount: number }, DbError> {
const { user, query, offset, limit, sort, sortDirection, filter } = searchOptions;
const response = await this.searchIndex.search(query, {
offset,
limit,
sort: sort && sortDirection ? [{ attribute: sort, direction: sortDirection }] : undefined,
filter,
});
const searchResults = response.hits;
const ids = searchResults.map((r) => r.id);
// Note: hidden or invalid maps may be returned by the search index, but should be filtered out
// when querying further metadata via `findMaps`.
const mapsResult = await this.findMaps({ by: 'id', ids }, user);
if (!mapsResult.success) {
return mapsResult;
}
const maps = new Map(mapsResult.value.map((m) => [m.id, m]));
return {
success: true,
value: {
maps: searchResults.map((m) => maps.get(m.id)).filter(exists),
totalCount: response.totalCount,
},
};
}
async getMap(mapId: string, userId?: string): PromisedResult<PDMap, GetMapError> {
const { pool } = await getServerContext();
try {
const map = await db
.selectOne(
'maps',
{ id: mapId, visibility: MapVisibility.PUBLIC },
{
lateral: {
difficulties: db.select(
'difficulties',
{ map_id: db.parent('id') },
{
columns: ['difficulty', 'difficulty_name'],
}
),
favorites: db.count('favorites', { map_id: db.parent('id') }),
},
columns: [
'id',
'visibility',
'validity',
'submission_date',
'title',
'artist',
'author',
'authoring_tool',
'uploader',
'download_count',
'description',
'tags',
'complexity',
'album_art',
],
}
)
.run(pool);
if (map == null) {
return { success: false, errors: [{ type: GetMapError.MISSING_MAP }] };
}
const userProjection = userId
? {
isFavorited: !!(await db
.selectOne('favorites', { map_id: mapId, user_id: userId })
.run(pool)),
}
: undefined;
return {
success: true,
value: PDMap.decode({
...camelCaseKeys({
...map,
visibility: mapVisibilityEnum.parse(map.visibility),
validity: mapValidityEnum.parse(map.validity),
}),
userProjection,
}),
};
} catch (e) {
return { success: false, errors: [wrapError(e, GetMapError.UNKNOWN_DB_ERROR)] };
}
}
async changeMapVisibility(
id: string,
visibility: MapVisibility
): Promise<Result<undefined, UpdateMapError>> {
const { pool } = await getServerContext();
try {
await db.update('maps', { visibility }, { id }).run(pool);
return { success: true, value: undefined };
} catch (e) {
return { success: false, errors: [wrapError(e, UpdateMapError.UNKNOWN_DB_ERROR)] };
}
}
async setValidity(id: string, validity: MapValidity): PromisedResult<undefined, UpdateMapError> {
const pool = await getDbPool();
try {
await db.update('maps', { validity }, { id }).run(pool);
return { success: true, value: undefined };
} catch (e) {
return { success: false, errors: [wrapError(e, UpdateMapError.UNKNOWN_DB_ERROR)] };
}
}
private async updateSearchIndex(
map: Partial<PDMap> & { id: string }
): PromisedResult<void, SearchIndexError> {
try {
await this.searchIndex.updateDocuments([map]);
} catch (e) {
return {
success: false,
errors: [{ type: SearchIndexError.SEARCH_INDEX_ERROR, internalMessage: JSON.stringify(e) }],
};
}
return { success: true, value: undefined };
}
async incrementMapDownloadCount(mapId: string): PromisedResult<void, GetMapError> {
const { pool } = await getServerContext();
try {
return db.serializable<Result<void, GetMapError>>(pool, async (client) => {
const map = await db
.selectOne('maps', { id: mapId }, { columns: ['download_count'] })
.run(client);
if (map == null) {
// TODO: wire a proper ResultError out of the `db.serializable`
return {
success: false,
errors: [
{
type: GetMapError.MISSING_MAP,
internalMessage: `Could not find map id ${mapId} to increment download count`,
},
],
};
}
const updatedMap = await db
.update('maps', snakeCaseKeys({ downloadCount: map.download_count + 1 }), { id: mapId })
.run(client);
const searchIndexResp = await this.updateSearchIndex({
...PDMap.partial().parse(camelCaseKeys(updatedMap[0])),
id: updatedMap[0].id,
});
if (!searchIndexResp.success) {
return {
success: false,
errors: [
{
type: GetMapError.MISSING_MAP,
internalMessage: `Could not update search index for map id ${mapId}`,
},
],
};
}
return { success: true, value: undefined };
});
} catch (e) {
return { success: false, errors: [wrapError(e, GetMapError.UNKNOWN_DB_ERROR)] };
}
}
async deleteMap({
id,
}: {
id: string;
}): PromisedResult<undefined, DbError | DeleteMapError | S3Error> {
const { pool } = await getServerContext();
try {
// Delete dependent tables / foreign keys first
await Promise.all([
db.deletes('difficulties', { map_id: id }).run(pool),
db.deletes('favorites', { map_id: id }).run(pool),
]);
// Delete the map
// TODO: soft deletion
const deleted = await db.deletes('maps', { id }).run(pool);
if (deleted.length === 0) {
return { success: false, errors: [{ type: DeleteMapError.MISSING_MAP }] };
}
await this.searchIndex.deleteDocument(id);
// Attempt to delete any orphaned S3 temp files just in case
await Promise.all([
this.s3Handler.deleteFiles(id, true),
this.s3Handler.deleteFiles(id, false),
]);
return { success: true, value: undefined };
} catch (e) {
return { success: false, errors: [wrapError(e, DbError.UNKNOWN_DB_ERROR)] };
}
}
async createNewMap({
title,
uploader,
}: {
title: string;
uploader: string;
}): PromisedResult<{ id: string }, CreateMapError | DbError> {
const pool = await getDbPool();
const id = await generateId(
IdDomain.MAPS,
async (id) => !!(await db.selectOne('maps', { id }).run(pool))
);
if (id == null) {
return { success: false, errors: [{ type: CreateMapError.TOO_MANY_ID_GEN_ATTEMPTS }] };
}
try {
await db
.insert('maps', [
snakeCaseKeys({
id,
visibility: MapVisibility.HIDDEN,
validity: MapValidity.PENDING_UPLOAD,
uploader,
submissionDate: new Date(),
title,
artist: '',
complexity: 0,
}),
])
.run(pool);
return { success: true, value: { id } };
} catch (e) {
return { success: false, errors: [wrapError(e, DbError.UNKNOWN_DB_ERROR)] };
}
}
async validateUploadedMap(
opts: ProcessMapOpts
): PromisedResult<
PDMap,
| S3Error
| DbError
| CreateMapError
| ValidateMapError
| ValidateMapDifficultyError
| SearchIndexError
> {
const { id, archive, uploader } = opts;
const existingMap = await this.getMap(id);
const isExistingMap =
existingMap.success && existingMap.value.validity === MapValidity.REUPLOADED;
await this.setValidity(id, MapValidity.VALIDATING);
const validatedMapResult = await validateMap({ id, archive });
if (!validatedMapResult.success) {
return validatedMapResult;
}
const {
title,
artist,
author,
authoringTool,
description,
complexity,
difficulties,
albumArtFiles,
} = validatedMapResult.value;
// We are updating a map; delete the old file off S3 first
const uploadResult = await this.s3Handler.uploadAlbumArtFiles(id, albumArtFiles, true);
if (!uploadResult.success) {
return uploadResult;
}
const albumArt = uploadResult.value;
const now = new Date();
const pool = await getDbPool();
try {
const insertedMap = await db
.upsert(
'maps',
snakeCaseKeys({
id,
visibility: MapVisibility.PUBLIC,
validity: MapValidity.VALID,
submissionDate: now,
title: title,
artist: artist,
author: author || null,
authoringTool: authoringTool || null,
uploader,
albumArt: albumArt || null,
description: description || null,
complexity: checkExists(complexity, 'complexity'),
}),
['id']
)
.run(pool);
if (isExistingMap) {
await db.deletes('difficulties', snakeCaseKeys({ mapId: id })).run(pool);
}
const insertedDifficulties = await db
.insert(
'difficulties',
difficulties.map((d) =>
snakeCaseKeys({
mapId: id,
difficulty: d.difficulty || null,
difficultyName: checkExists(d.difficultyName, 'difficultyName'),
})
)
)
.run(pool);
await this.s3Handler.promoteTempMapFiles(id);
const mapResult = PDMap.decode(
camelCaseKeys({
...insertedMap,
validity: mapValidityEnum.parse(insertedMap.validity),
visibility: mapVisibilityEnum.parse(insertedMap.visibility),
difficulties: insertedDifficulties,
favorites: (existingMap.success && existingMap.value.favorites) || 0,
userProjection: {
isFavorited: !!(await db
.selectOne('favorites', { map_id: id, user_id: uploader })
.run(pool)),
},
})
);
const searchIndexResp = await this.updateSearchIndex(mapResult);
if (!searchIndexResp.success) {
return searchIndexResp;
}
return { success: true, value: mapResult };
} catch (e) {
return { success: false, errors: [wrapError(e, DbError.UNKNOWN_DB_ERROR)] };
}
}
}
const internalError: [number, string] = [500, 'Could not submit map'];
export const submitErrorMap: Record<
| S3Error
| DbError
| CreateMapError
| ValidateMapError
| ValidateMapDifficultyError
| SearchIndexError,
[number, string]
> = {
[S3Error.S3_GET_ERROR]: internalError,
[S3Error.S3_WRITE_ERROR]: internalError,
[S3Error.S3_DELETE_ERROR]: internalError,
[DbError.UNKNOWN_DB_ERROR]: internalError,
[CreateMapError.TOO_MANY_ID_GEN_ATTEMPTS]: internalError,
[ValidateMapError.INCORRECT_FOLDER_NAME]: [
400,
'The top-level folder name needs to match the names of the rlrr files',
],
[ValidateMapError.INCORRECT_FOLDER_STRUCTURE]: [
400,
'Incorrect folder structure. There needs to be exactly one top-level folder containing all of the files, and the folder needs to match the song title.',
],
[ValidateMapError.MISMATCHED_DIFFICULTY_METADATA]: [
400,
'All difficulties need to have identical metadata (excluding complexity)',
],
[ValidateMapError.MISSING_ALBUM_ART]: [400, 'Missing album art'],
[ValidateMapError.NO_DATA]: [400, 'Invalid map archive; could not find map data'],
[ValidateMapError.DESCRIPTION_TOO_LONG]: [400, 'Description is too long'],
[ValidateMapError.FILE_TOO_LARGE]: [400, 'File is over the filesize limit for this song length'],
[ValidateMapDifficultyError.NO_AUDIO]: [400, 'Invalid map archive; missing audio files'],
[ValidateMapDifficultyError.INVALID_FORMAT]: [
400,
'Invalid map data; could not process the map .rlrr files',
],
[ValidateMapDifficultyError.MISSING_VALUES]: [
400,
'Invalid map data; a map .rlrr is missing a required field (title, artist or complexity)',
],
[SearchIndexError.SEARCH_INDEX_ERROR]: internalError,
};