deadhead-space-freight-tycoon/apps/server/src/game/lock.ts

23 lines
612 B
TypeScript

import { eq } from "drizzle-orm";
import type { Db, Queryable } from "../db/client";
import { companies } from "../db/schema";
/**
* Runs `fn` in a transaction holding a row lock on the player's company, so
* changes to one player's money and fleet never interleave (Step 6.14).
*/
export function withPlayerLock<T>(
db: Db,
playerId: string,
fn: (tx: Queryable) => Promise<T>,
): Promise<T> {
return db.transaction(async (tx) => {
await tx
.select({ id: companies.id })
.from(companies)
.where(eq(companies.playerId, playerId))
.for("update");
return fn(tx);
});
}