setup some race condition protection on update, host client now starts game when everyone is ready

This commit is contained in:
2025-06-18 14:55:10 -07:00
parent 66ff3eaaea
commit f263e7f18f
10 changed files with 180 additions and 77 deletions

View File

@ -15,6 +15,7 @@ import {
notFoundResponse,
singleResponse,
} from "$lib/server/responseBodies";
import { retry } from "$lib/server/retry";
import type { RequestHandler } from "@sveltejs/kit";
export const PUT: RequestHandler = async ({ params, request }): Promise<Response> => {
@ -35,19 +36,35 @@ export const PUT: RequestHandler = async ({ params, request }): Promise<Response
return badRequestResponse("malformed request");
}
const listing = await readListingById(ServerCollections.Games, id, isListing<GameData>);
if (!listing) {
return notFoundResponse();
}
const putItem = async (): Promise<[boolean, Response]> => {
const listing = await readListingById(
ServerCollections.Games,
id,
isListing<GameData>,
);
if (listing.data.isStarted === true) {
return conflictResponse();
}
if (!listing) {
return [false, notFoundResponse()];
}
const game = Game.from(listing.data);
if (game.setPlayerReady(player) === null) return notFoundResponse();
if (listing.data.isStarted === true) {
return [false, conflictResponse()];
}
await writeUpdatedListing(ServerCollections.Games, updateListing(listing, game));
const game = Game.from(listing.data);
if (game.setPlayerReady(player) === null) return [false, notFoundResponse()];
return singleResponse(game);
const res = await writeUpdatedListing(
ServerCollections.Games,
updateListing(listing, game),
);
if (!res.acknowledged || res.modifiedCount === 0) {
return [true, conflictResponse()];
}
return [false, singleResponse(game)];
};
return await retry(putItem);
};