-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathabstractplay.ts
More file actions
9812 lines (9356 loc) · 331 KB
/
Copy pathabstractplay.ts
File metadata and controls
9812 lines (9356 loc) · 331 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
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint-disable @typescript-eslint/ban-ts-comment */
'use strict';
import { DynamoDBClient } from '@aws-sdk/client-dynamodb';
import { DynamoDBDocumentClient, PutCommand, GetCommand, UpdateCommand, DeleteCommand, QueryCommand, ScanCommand, BatchWriteCommand, QueryCommandInput, GetCommandOutput, PutCommandOutput, UpdateCommandOutput, DeleteCommandOutput, QueryCommandOutput } from '@aws-sdk/lib-dynamodb';
import { SQSClient, SendMessageCommand, SendMessageCommandOutput, SendMessageRequest } from "@aws-sdk/client-sqs";
import { CognitoIdentityProviderClient, CreateUserPoolClientCommand, DeleteUserPoolClientCommand } from "@aws-sdk/client-cognito-identity-provider";
import { v4 as uuid } from 'uuid';
import { gameinfo, GameFactory, GameBase, GameBaseSimultaneous, type APGamesInformation } from '@abstractplay/gameslib';
import { SESClient, SendEmailCommand } from '@aws-sdk/client-ses';
import webpush from "web-push";
import { validateToken } from '@sunknudsen/totp';
import i18n from 'i18next';
import en from '../locales/en/apback.json';
import fr from '../locales/fr/apback.json';
import de from '../locales/de/apback.json';
import it from '../locales/it/apback.json';
import pt from '../locales/pt/apback.json';
import ta from '../locales/ta/apback.json';
const LOCALE_RESOURCES = { en, fr, de, it, pt, ta } as const;
const REGISTERED_LANGUAGES = Object.keys(LOCALE_RESOURCES);
import { wsBroadcast } from '../lib/wsBroadcast';
import { checkInGameCommentAuth } from '../lib/commentAuth';
import {
isBotId,
getParticipants,
getBotRecord,
filterHumanIds,
botToFullUserStub,
toClientBot,
ClientBot,
BotRecord,
} from '../lib/participants';
import { enqueueBotOutbound, getToMovePlayerIds, loadGameRecord } from '../lib/botOutbound';
import {
beginBotSecretRotation as cognitoBeginBotSecretRotation,
finalizeBotSecretRotation as cognitoFinalizeBotSecretRotation,
} from '../lib/botSecrets';
import { buildCreateBotClientInput } from '../lib/botCognito';
import {
BotNameTakenError,
BotNameValidationError,
reserveBotDisplayName,
releaseBotDisplayName,
renameBotDisplayName,
validateBotDisplayName,
} from '../lib/botNames';
import { testBotStatus, updateTestBot } from './testBot';
import { hydrateGameState, prepareGameStateForStorage } from '../lib/gameState';
import {
type PushOptions,
deleteAllPushSubscriptions,
deletePushSubscriptionByEndpoint,
queryPushSubscriptions,
savePushSubscription,
sendPushToSubscriptions,
} from '../lib/pushSubscriptions';
const REGION = "us-east-1";
const sesClient = new SESClient({ region: REGION });
const sqsClient = new SQSClient({ region: REGION });
const cognitoClient = new CognitoIdentityProviderClient({ region: REGION });
const clnt = new DynamoDBClient({ region: REGION });
const marshallOptions = {
// Whether to automatically convert empty strings, blobs, and sets to `null`.
convertEmptyValues: false, // false, by default.
// Whether to remove undefined values while marshalling.
removeUndefinedValues: true, // false, by default.
// Whether to convert typeof object to map attribute.
convertClassInstanceToMap: false, // false, by default.
};
const unmarshallOptions = {
// Whether to return numbers as a string instead of converting them to native JavaScript numbers.
wrapNumbers: false, // false, by default.
};
const translateConfig = { marshallOptions, unmarshallOptions };
const ddbDocClient = DynamoDBDocumentClient.from(clnt, translateConfig);
const headers = {
'content-type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true,
"Access-Control-Allow-Headers": "*",
"Access-Control-Allow-Methods": "*",
};
// Types
type MetaGameCounts = {
[metaGame: string]: {
currentgames: number;
completedgames: number;
standingchallenges: number;
ratings?: string[];
stars?: number;
tags?: string[];
}
}
type Challenge = {
metaGame: string;
standing?: boolean;
challenger: User;
players: User[];
challengees?: User[];
}
type FullChallenge = {
pk?: string,
sk?: string,
metaGame: string;
numPlayers: number;
standing?: boolean;
duration?: number;
seating: string;
variants: string[];
challenger: User;
challengees?: User[]; // players who were challenged
players?: User[]; // players that have accepted
clockStart: number;
clockInc: number;
clockMax: number;
clockHard: boolean;
rated: boolean;
noExplore?: boolean;
comment?: string;
dateIssued?: number;
}
export type UserSettings = {
[k: string]: any;
all?: {
[k: string]: any;
color?: string;
annotate?: boolean;
notifications?: {
gameStart: boolean;
gameEnd: boolean;
challenges: boolean;
yourturn: boolean;
tournamentStart: boolean;
tournamentEnd: boolean;
}
}
};
export type UserLastSeen = {
id: string;
name: string;
lastSeen?: number;
};
export type User = {
id: string;
name: string;
time?: number;
settings?: UserSettings;
draw?: string;
}
type FullUser = {
pk?: string,
sk?: string,
id: string;
name: string;
email: string;
gamesUpdate?: number;
games: Game[];
challenges_issued?: Set<string>;
bots?: Set<string>;
challenges_received?: Set<string>;
challenges_accepted?: Set<string>;
challenges_standing?: Set<string>;
admin: boolean | undefined;
organizer: boolean | undefined;
language: string;
country: string;
lastSeen?: number;
settings: UserSettings;
ratings?: {
[metaGame: string]: Rating
};
stars?: string[];
tags?: TagList[];
palettes?: Palette[];
mayPush?: boolean;
bggid?: string;
about?: string;
}
export type UsersData = {
id: string;
name: string;
country: string;
lastSeen: number;
stars: string[];
bggid?: string;
about?: string;
bot: boolean;
};
type Bot = ClientBot;
type MeData = {
id: string;
name: string;
admin: boolean;
organizer: boolean;
language: string;
country: string;
games: Game[];
settings: UserSettings;
stars: string[];
bggid?: string;
about?: string;
tags?: TagList[];
palettes?: Palette[];
mayPush: boolean;
bots?: Bot[];
challengesIssued?: FullChallenge[];
challengesReceived?: FullChallenge[];
challengesAccepted?: FullChallenge[];
standingChallenges?: FullChallenge[];
realStanding?: StandingChallenge[];
customizations?: { [key: string]: any };
blocked?: string[];
}
type Rating = {
rating: number;
N: number;
wins: number;
draws: number;
}
type Note = {
pk: string;
sk: string;
note: string;
}
type Game = {
pk?: string,
sk?: string,
id: string;
metaGame: string;
players: User[];
lastMoveTime: number;
clockHard: boolean;
noExplore?: boolean;
toMove?: string | boolean[];
note?: string;
seen?: number;
winner?: number[];
numMoves?: number;
gameStarted?: number;
gameEnded?: number;
lastChat?: number;
variants?: string[];
commented?: number; // 0 or missing: no comments or post game variations, 1: has in-game comments, 2: has post game variations, 3: has post game comments. Only used in COMPLETEDGAMES#<metaGame> rows.
}
type FullGame = {
pk: string;
sk: string;
id: string;
clockHard: boolean;
clockInc: number;
clockMax: number;
clockStart: number;
gameStarted: number;
gameEnded?: number;
lastMoveTime: number;
metaGame: string;
numPlayers: number;
players: User[];
state: string;
note?: string;
toMove: string | boolean[];
partialMove?: string;
winner?: number[];
numMoves?: number;
rated?: boolean;
pieInvoked?: boolean;
variants?: string[];
published?: string[];
smevent?: string;
smeventRound?: number;
tournament?: string;
event?: string;
division?: number;
noExplore?: boolean;
commented?: number; // 0 or missing: no comments or post game variations, 1: has in-game comments (note this does NOT get updated for post-game comments/variations)
}
type Playground = {
pk: "PLAYGROUND";
sk: string;
metaGame: string;
state: string;
}
type Comment = {
comment: string;
userId: string;
moveNumber: number;
timeStamp: number;
}
type Exploration = {
version?: number;
id: string;
move: number;
comment: string;
children: Exploration[];
outcome?: number; // Optional. 0 for player1 win, 1 for player2 win, -1 for undecided.
premove?: boolean; // Optional. If true, this move will be automatically submitted when the opponent plays the parent move.
};
type Division = {
numGames: number;
numCompleted: number;
processed: boolean;
winnerid?: string;
winner?: string;
};
type Tournament = {
pk: string;
sk: string;
id: string;
metaGame: string;
variants: string[];
number: number;
started: boolean;
dateCreated: number;
datePreviousEnded: number; // 0 means either the first tournament or a restart of the series (after it stopped because not enough participants), 3000000000000 means previous tournament still running.
nextid?: string;
dateStarted?: number;
dateEnded?: number;
divisions?: {
[division: number]: Division;
};
players?: TournamentPlayer[]; // only on archived tournaments
waiting?: boolean; // tournament does not yet have 4 players
};
type TournamentPlayer = {
pk: string;
sk: string;
playerid: string;
playername: string;
once?: boolean;
division?: number;
score?: number;
tiebreak?: number;
rating?: number;
timeout?: boolean;
};
type TournamentGame = {
pk: string;
sk: string;
id: string;
player1: string;
player2: string;
winner?: string[];
};
type OrgEvent = {
pk: "ORGEVENT";
sk: string; // <eventid>
name: string;
description: string;
organizer: string;
dateStart: number;
dateEnd?: number;
winner?: string[];
visible: boolean;
maxPlayers: number;
invited?: string[];
blocked?: string[];
}
type OrgEventGame = {
pk: "ORGEVENTGAME";
sk: string; // <eventid>#<gameid>
metaGame: string;
variants?: string[];
round: number;
gameid: string;
player1: string;
player2: string;
winner?: string[];
arbitrated?: boolean;
};
type OrgEventPlayer = {
pk: "ORGEVENTPLAYER";
sk: string; // <eventid>#<playerid>
playerid: string;
division?: number;
seed?: number;
};
type TagList = {
meta: string;
tags: string[];
}
type TagRec = {
pk: "TAG";
sk: string;
tags: TagList[];
}
type Palette = {
name: string;
colours: string[];
}
type PaletteRec = {
pk: "PALETTES";
sk: string;
palettes: Palette[];
}
type Customization = {
colourContext: {
[k: string]: string;
},
palette: string[];
}
type CustomizationRec = {
pk: string;
sk: string;
settings: Customization;
}
// SDG-style standing challenges
type StandingChallenge = {
id: string;
metaGame: string;
numPlayers: number;
variants?: string[];
clockStart: number;
clockInc: number;
clockMax: number;
clockHard: boolean;
rated: boolean;
noExplore?: boolean
limit: number;
sensitivity: "meta" | "variants";
suspended: boolean;
};
type StandingChallengeRec = {
pk: "REALSTANDING";
sk: string; // user's ID
standing: StandingChallenge[];
};
const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
async function sendCommandWithRetry<T = any>(command: any, maxRetries = 8, initialDelay = 100, maxDelay = 5000): Promise<T> {
let retries = 0;
while (retries < maxRetries) {
try {
// @ts-ignore
return await ddbDocClient.send(command) as T;
} catch (err: any) {
if (['ThrottlingException', 'ProvisionedThroughputExceededException', 'InternalServerError', 'ServiceUnavailable'].includes(err.name)) {
retries++;
if (retries >= maxRetries) {
console.error(`Command failed after ${maxRetries} retries.`);
throw err;
}
const delay = Math.min(initialDelay * Math.pow(2, retries - 1), maxDelay);
const jitter = delay * 0.1 * Math.random();
console.log(`Retryable error (${err.name}) caught. Retrying in ${Math.round(delay + jitter)}ms...`);
await sleep(delay + jitter);
} else {
throw err;
}
}
}
// This should never be reached due to the throw in the catch block
throw new Error(`Command failed after ${maxRetries} retries without a retryable error`);
}
const DEFAULT_META_GAME_COUNTS = {
currentgames: 0,
completedgames: 0,
standingchallenges: 0,
stars: 0,
};
function isMetaGameCountsKey(key: string): boolean {
return key === "pk" || key === "sk" || key.endsWith("_ratings");
}
async function ensureMetaGameCountEntry(metaGame: string): Promise<void> {
await ddbDocClient.send(new UpdateCommand({
TableName: process.env.ABSTRACT_PLAY_TABLE,
Key: { pk: "METAGAMES", sk: "COUNTS" },
ExpressionAttributeNames: { "#g": metaGame },
ExpressionAttributeValues: { ":defaults": DEFAULT_META_GAME_COUNTS },
UpdateExpression: "SET #g = if_not_exists(#g, :defaults)",
}));
}
async function ensureMissingMetaGameCounts(): Promise<void> {
const data = await ddbDocClient.send(new GetCommand({
TableName: process.env.ABSTRACT_PLAY_TABLE,
Key: { pk: "METAGAMES", sk: "COUNTS" },
}));
const item = data.Item ?? {};
const existing = new Set(Object.keys(item).filter(k => !isMetaGameCountsKey(k)));
const missing: string[] = [];
gameinfo.forEach(g => {
if (!existing.has(g.uid)) {
missing.push(g.uid);
}
});
if (missing.length === 0) {
return;
}
console.log(`Initializing METAGAMES/COUNTS for new games: ${missing.join(", ")}`);
await Promise.all(missing.map(uid => ensureMetaGameCountEntry(uid)));
}
module.exports.query = async (event: { queryStringParameters: any; body?: string; httpMethod: string; }) => {
console.log(event);
let pars;
let query;
// Handle both GET (query parameters) and POST (JSON body) requests
if (event.httpMethod === 'POST' && event.body) {
try {
const bodyData = JSON.parse(event.body);
query = bodyData.query;
pars = bodyData.pars || {};
} catch (error) {
return {
statusCode: 400,
body: JSON.stringify({
message: "Invalid JSON in request body"
}),
headers
};
}
} else {
// Existing GET request handling
pars = event.queryStringParameters;
query = pars.query;
}
console.log(pars);
switch (query) {
case "user_names":
return await userNames();
case "challenge_details":
return await challengeDetails(pars);
case "standing_challenges":
return await standingChallenges(pars);
case "games":
return await games(pars);
case "ratings":
return await ratings(pars);
case "meta_games":
return await metaGamesDetails();
case "get_game":
return await game("", pars);
case "get_public_exploration":
return await getPublicExploration(pars);
case "bot_move":
return await botMove(pars);
case "get_tournaments":
return await getTournaments();
case "get_old_tournaments":
return await getOldTournaments(pars);
case "get_tournament":
return await getTournament(pars);
case "start_tournaments":
return await startTournaments();
case "archive_tournaments":
return await archiveTournaments();
case "get_event":
return await eventGetEvent(pars);
case "get_events":
return await eventGetEvents();
case "report_problem":
return await reportProblem(pars);
default:
return {
statusCode: 500,
body: JSON.stringify({
message: `Unable to execute unknown open query '${pars.query}'`
}),
headers
};
}
}
function parseLambdaIntegrationBody(body: string | Record<string, unknown> | undefined): Record<string, unknown> {
if (body === undefined || body === null) {
throw new Error("Missing request body");
}
if (typeof body === "string") {
return JSON.parse(body) as Record<string, unknown>;
}
return body;
}
module.exports.botQuery = async (event: { body: string | Record<string, unknown>; cognitoPoolClaims: PartialClaims; }) => {
console.log("botQuery: ", event.body);
console.log("botQuery claims:", {
sub: event.cognitoPoolClaims?.sub,
email: event.cognitoPoolClaims?.email,
email_verified: event.cognitoPoolClaims?.email_verified,
});
let body: Record<string, unknown>;
try {
body = parseLambdaIntegrationBody(event.body);
} catch (error) {
return {
statusCode: 400,
body: JSON.stringify({
message: "Invalid JSON in request body"
}),
headers
};
}
const verb = body.verb;
switch (verb) {
case "move":
return await handleMove(event.cognitoPoolClaims, body as { gameid: string; move: string; metaGame: string; });
default:
return {
statusCode: 400,
body: JSON.stringify({
message: `Unknown bot verb '${verb}'`
}),
headers
};
}
}
type PartialClaims = { sub: string; email: string; email_verified: boolean };
// It looks like there is no way to "run and forget", you need to finish all work before returning a response to the front end. :(
// Make sure the @typescript-eslint/no-floating-promises linter rule passes, otherwise promise might (at best?) only be fullfilled on the next call to the API...
module.exports.authQuery = async (event: { body: { query: any; pars: any; }; cognitoPoolClaims: PartialClaims; }) => {
console.log("authQuery: ", event.body.query);
const query = event.body.query;
const pars = event.body.pars;
switch (query) {
case "me":
return await me(event.cognitoPoolClaims, pars);
case "create_bot":
case "createBot":
return await createBot(event.cognitoPoolClaims, pars);
case "update_bot":
case "updateBot":
return await updateBot(event.cognitoPoolClaims, pars);
case "delete_bot":
case "deleteBot":
return await deleteBot(event.cognitoPoolClaims, pars);
case "begin_bot_secret_rotation":
case "beginBotSecretRotation":
return await beginBotSecretRotation(event.cognitoPoolClaims, pars);
case "finalize_bot_secret_rotation":
case "finalizeBotSecretRotation":
return await finalizeBotSecretRotation(event.cognitoPoolClaims, pars);
case "test_bot_status":
return await testBotStatus(event.cognitoPoolClaims);
case "update_test_bot":
return await updateTestBot(event.cognitoPoolClaims, pars);
case "next_game":
return await nextGame(event.cognitoPoolClaims.sub);
case "my_settings":
return await mySettings(event.cognitoPoolClaims);
case "new_setting":
return await newSetting(event.cognitoPoolClaims.sub, pars);
case "new_profile":
return await newProfile(event.cognitoPoolClaims, pars);
case "set_push":
return await setPush(event.cognitoPoolClaims.sub, pars);
case "save_push":
return await savePush(event.cognitoPoolClaims.sub, pars);
case "delete_push":
return await deletePush(event.cognitoPoolClaims.sub, pars);
case "save_tags":
return await saveTags(event.cognitoPoolClaims.sub, pars);
case "save_palettes":
return await savePalettes(event.cognitoPoolClaims.sub, pars);
case "save_customization":
return await saveCustomization(event.cognitoPoolClaims.sub, pars);
case "delete_customization":
return await deleteCustomization(event.cognitoPoolClaims.sub, pars);
case "update_standing":
return await updateStanding(event.cognitoPoolClaims.sub, pars);
case "block_player":
return await block_player(event.cognitoPoolClaims.sub, pars);
case "unblock_player":
return await unblock_player(event.cognitoPoolClaims.sub, pars);
case "standing_challenges":
return await standingChallenges({ ...pars, userId: event.cognitoPoolClaims.sub });
case "new_challenge":
return await newChallenge(event.cognitoPoolClaims.sub, pars);
case "challenge_revoke":
return await revokeChallenge(event.cognitoPoolClaims.sub, pars);
case "challenge_response":
return await respondedChallenge(event.cognitoPoolClaims.sub, pars);
case "submit_move":
return await submitMove(event.cognitoPoolClaims.sub, pars);
case "timeloss":
return await checkForTimeloss(event.cognitoPoolClaims.sub, pars);
case "abandoned":
return await checkForAbandonedGame(event.cognitoPoolClaims.sub, pars);
case "invoke_pie":
return await invokePie(event.cognitoPoolClaims.sub, pars);
case "update_note":
return await updateNote(event.cognitoPoolClaims.sub, pars);
case "update_commented":
return await updateCommented(event.cognitoPoolClaims.sub, pars);
case "set_lastSeen":
return await setLastSeen(event.cognitoPoolClaims.sub, pars);
case "submit_comment":
return await submitComment(event.cognitoPoolClaims.sub, pars);
case "save_exploration":
return await saveExploration(event.cognitoPoolClaims.sub, pars);
case "get_exploration":
return await getExploration(event.cognitoPoolClaims.sub, pars);
case "get_private_exploration":
return await getPrivateExploration(event.cognitoPoolClaims.sub, pars);
case "get_game":
return await game(event.cognitoPoolClaims.sub, pars);
case "get_playground":
return await getPlayground(event.cognitoPoolClaims.sub, pars);
case "new_playground":
return await newPlayground(event.cognitoPoolClaims.sub, pars);
case "reset_playground":
return await resetPlayground(event.cognitoPoolClaims.sub);
case "toggle_star":
return await toggleStar(event.cognitoPoolClaims.sub, pars);
case "set_game_state":
return await injectState(event.cognitoPoolClaims.sub, pars);
case "update_game_settings":
return await updateGameSettings(event.cognitoPoolClaims.sub, pars);
case "update_user_settings":
return await updateUserSettings(event.cognitoPoolClaims.sub, pars);
case "update_meta_game_counts":
return await updateMetaGameCounts(event.cognitoPoolClaims.sub);
case "purge_retired_completed_games":
return await purgeRetiredCompletedGames(event.cognitoPoolClaims.sub);
case "mark_published":
return await markAsPublished(event.cognitoPoolClaims.sub, pars);
case "new_tournament":
return await newTournament(event.cognitoPoolClaims.sub, pars);
case "join_tournament":
return await joinTournament(event.cognitoPoolClaims.sub, pars);
case "withdraw_tournament":
return await withdrawTournament(event.cognitoPoolClaims.sub, pars);
case "event_create":
return await eventCreate(event.cognitoPoolClaims.sub, pars);
case "event_delete":
return await eventDelete(event.cognitoPoolClaims.sub, pars);
case "event_publish":
return await eventPublish(event.cognitoPoolClaims.sub, pars);
case "event_register":
return await eventRegister(event.cognitoPoolClaims.sub, pars);
case "event_withdraw":
return await eventWithdraw(event.cognitoPoolClaims.sub, pars);
case "event_update_start":
return await eventUpdateStart(event.cognitoPoolClaims.sub, pars);
case "event_update_name":
return await eventUpdateName(event.cognitoPoolClaims.sub, pars);
case "event_update_desc":
return await eventUpdateDesc(event.cognitoPoolClaims.sub, pars);
case "event_update_invites":
return await eventUpdateInvites(event.cognitoPoolClaims.sub, pars);
case "event_update_result":
return await eventUpdateResult(event.cognitoPoolClaims.sub, pars);
case "event_update_divisions":
return await eventUpdateDivisions(event.cognitoPoolClaims.sub, pars);
case "event_create_games":
return await eventCreateGames(event.cognitoPoolClaims.sub, pars);
case "event_close":
return await eventClose(event.cognitoPoolClaims.sub, pars);
case "ping_bot":
return await pingBot(event.cognitoPoolClaims.sub, pars);
case "onetime_fix":
return await onetimeFix(event.cognitoPoolClaims.sub);
case "fix_games":
return await fixGames(event.cognitoPoolClaims.sub, pars);
case "test_push":
return await testPush(event.cognitoPoolClaims.sub);
case "test_async":
return await testAsync(event.cognitoPoolClaims.sub, pars);
case "delete_games":
return await deleteGames(event.cognitoPoolClaims.sub, pars);
case "end_tournament":
return await endATournament(event.cognitoPoolClaims.sub, pars);
case "start_tournament":
return await startATournament(event.cognitoPoolClaims.sub, pars);
default:
return {
statusCode: 500,
body: JSON.stringify({
message: `Unable to execute unknown query '${query}'`
}),
headers
};
}
}
async function userNames() {
// Bots are listed from the stage's DynamoDB table (abstract-play-dev vs abstract-play-prod).
// Bot Cognito credentials are also per-stage; dev tokens cannot call prod botQuery.
console.log("userNames: Scanning users.");
try {
const [data, botData] = await Promise.all([
ddbDocClient.send(
new QueryCommand({
TableName: process.env.ABSTRACT_PLAY_TABLE,
KeyConditionExpression: "#pk = :pk",
ExpressionAttributeValues: { ":pk": "USERS" },
ExpressionAttributeNames: { "#pk": "pk", "#name": "name" },
ProjectionExpression: "sk, #name, lastSeen, country, stars, bggid, about",
ReturnConsumedCapacity: "INDEXES"
})),
ddbDocClient.send(
new QueryCommand({
TableName: process.env.ABSTRACT_PLAY_TABLE,
KeyConditionExpression: "#pk = :pk",
ExpressionAttributeValues: { ":pk": "BOT" },
ExpressionAttributeNames: { "#pk": "pk", "#name": "name" },
ProjectionExpression: "sk, #name, lastseen, description, supported",
})),
]);
const users = data.Items;
if (users == undefined) {
throw new Error("Found no users?");
}
// tweak bot info
const idx = users.findIndex(u => u.sk === process.env.AIAI_USERID);
if (idx !== -1) {
users[idx].lastSeen = Date.now();
}
const userResults = users.map(u => ({ id: u.sk, name: u.name, country: u.country, stars: u.stars, lastSeen: u.lastSeen, bggid: u.bggid, about: u.about, bot: false } as UsersData));
const botResults = (botData.Items ?? []).map(b => ({
id: b.sk,
name: b.name,
country: "",
stars: [...new Set(((b.supported ?? []) as { meta: string }[]).map(s => s.meta))],
lastSeen: b.lastseen ?? 0,
about: b.description,
bot: true,
} as UsersData));
return {
statusCode: 200,
body: JSON.stringify([...userResults, ...botResults]),
headers
};
}
catch (error) {
logGetItemError(error);
return formatReturnError(`Unable to query table ${process.env.ABSTRACT_PLAY_TABLE}`);
}
}
async function challengeDetails(pars: { id: string; }) {
try {
const data = await ddbDocClient.send(
new GetCommand({
TableName: process.env.ABSTRACT_PLAY_TABLE,
Key: {
"pk": "CHALLENGE", "sk": pars.id
},
}));
console.log("Got:");
console.log(data);
return {
statusCode: 200,
body: JSON.stringify(data.Item),
headers
};
}
catch (error) {
logGetItemError(error);
return formatReturnError(`Unable to get challenge ${pars.id} from table ${process.env.ABSTRACT_PLAY_TABLE}`);
}
}
async function games(pars: { metaGame: string, type: string; }) {
const game = pars.metaGame;
console.log(game);
if (pars.type === "current") {
try {
const gamesData = await ddbDocClient.send(
new QueryCommand({
TableName: process.env.ABSTRACT_PLAY_TABLE,
KeyConditionExpression: "#pk = :pk and begins_with(#sk, :sk)",
ExpressionAttributeValues: { ":pk": "GAME", ":sk": game + '#0#' },
ExpressionAttributeNames: { "#pk": "pk", "#sk": "sk" },
}));
const gamelist = (gamesData.Items as FullGame[]).map(hydrateGameState);
const returnlist = gamelist.map(g => {
const state = GameFactory(g.metaGame, g.state); // JSON.parse(g.state);
if (state === undefined) {
throw new Error(`Could not parse game state for ${g.metaGame}:\n${g.state}`);
}
return {
"id": g.id, "metaGame": g.metaGame, "players": g.players, "toMove": g.toMove, "gameStarted": g.gameStarted,
"numMoves": state.stack.length - 1, "variants": state.variants, "commented": g.commented || 0
}
});
return {
statusCode: 200,
body: JSON.stringify(returnlist),
headers
};
}
catch (error) {
logGetItemError(error);
return formatReturnError(`Unable to get games for ${pars.metaGame}`);
}
} else if (pars.type === "completed") {
try {
const gamesData = await ddbDocClient.send(
new QueryCommand({
TableName: process.env.ABSTRACT_PLAY_TABLE,
KeyConditionExpression: "#pk = :pk",
ExpressionAttributeValues: { ":pk": "COMPLETEDGAMES#" + game },
ExpressionAttributeNames: { "#pk": "pk" }
}));
return {
statusCode: 200,
body: JSON.stringify(gamesData.Items),
headers
};
}
catch (error) {
logGetItemError(error);
return formatReturnError(`Unable to get games for ${pars.metaGame}`);
}
} else {
return formatReturnError(`Unknown type ${pars.type}`);
}
}
async function ratings(pars: { metaGame: string }) {
const game = pars.metaGame;
try {
const ratingsData = await ddbDocClient.send(
new QueryCommand({
TableName: process.env.ABSTRACT_PLAY_TABLE,
KeyConditionExpression: "#pk = :pk",
ExpressionAttributeValues: { ":pk": "RATINGS#" + game },
ExpressionAttributeNames: { "#pk": "pk" }
}));
return {
statusCode: 200,
body: JSON.stringify(ratingsData.Items),
headers
};
}
catch (error) {
logGetItemError(error);
return formatReturnError(`Unable to get ratings for ${pars.metaGame}`);
}
}
async function getPlayerRelationIds(userId: string, skPrefix: string): Promise<string[]> {
const ids: string[] = [];
let result = await ddbDocClient.send(
new QueryCommand({
TableName: process.env.ABSTRACT_PLAY_TABLE,
KeyConditionExpression: "#pk = :pk AND begins_with(#sk, :skPrefix)",
ExpressionAttributeValues: {
":pk": "PLAYER#" + userId,
":skPrefix": skPrefix,
},
ExpressionAttributeNames: { "#pk": "pk", "#sk": "sk" },
ProjectionExpression: "#sk",
})
);