Skip to content

Commit

Permalink
fix(scripts): make it impossible for seeded maps to have identical names
Browse files Browse the repository at this point in the history
This causes a DB error, was happening when trying to add thousands of maps at once
  • Loading branch information
tsa96 committed Oct 23, 2024
1 parent 0059ce3 commit ca7bd1b
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 12 deletions.
7 changes: 7 additions & 0 deletions libs/random/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,13 @@ export function float(max: number, min = 0, decimalPlaces?: number): number {
);
}

export function char(
min = 'a'.codePointAt(0)!,
max = 'z'.codePointAt(0)!
): string {
return String.fromCodePoint(int(max, min));
}

export function element<T>(array: readonly T[]): T {
return array[Math.floor(Math.random() * array.length)];
}
Expand Down
34 changes: 22 additions & 12 deletions scripts/src/seed.script.ts
Original file line number Diff line number Diff line change
Expand Up @@ -367,23 +367,32 @@ prismaWrapper(async (prisma: PrismaClient) => {
);

const mapsToCreate = randRange(vars.maps);
const existingMaps = await prisma.mMap.findMany();
const usedNames = (existingMaps ?? []).map(({ name }) => name);
const usedNames = await prisma.mMap
.findMany()
.then((maps) => (maps ?? []).map(({ name }) => name));
const prefixes = [
...new Set([...GamemodeInfo.values()].map(({ prefix }) => prefix))
];
try {
for (let i = 0; i < mapsToCreate; i++) {
console.log(`Adding maps (${i + 1}/${mapsToCreate})`);
let name: string;
while (!name || usedNames.includes(name)) {
// Most maps have a gamemode prefix, some don't, want to be able to test
// with both.
const prefix = Random.element(prefixes);
name = faker.lorem.word();
if (Random.chance(0.75)) {
name = `${prefix}_${name}`;
}
console.log(`Adding map (${i + 1}/${mapsToCreate})`);
console.time('Added map');
// Make sure name always <= 32 chars (16 + 11 + 5 = 32)
let name =
faker.lorem.word({ length: { min: 3, max: 16 } }) +
faker.lorem.word({ length: { min: 3, max: 11 } });
// Most maps have a gamemode prefix, some don't, want to be able to test
// with both.
const prefix = Random.element(prefixes);
if (Random.chance(0.75)) {
name = `${prefix}_${name}`;
}

// This is so unlikely to happen, but if we ever get a duplicate name,
// just scramble some chars until we get a unique one.
while (usedNames.includes(name)) {
const idx = Random.int(0, 27);
name = name.slice(0, idx) + Random.char() + name.slice(idx + 1);
}

usedNames.push(name);
Expand Down Expand Up @@ -849,6 +858,7 @@ prismaWrapper(async (prisma: PrismaClient) => {
}
}

console.timeEnd('Added map');
//#endregion
}
} catch (error) {
Expand Down

0 comments on commit ca7bd1b

Please sign in to comment.