Skip to content

Commit

Permalink
QoL (#353)
Browse files Browse the repository at this point in the history
* fix(ci): deploying without passing tests first

* chore(gacha): remove fools fake pull code

* fix(shop):  buying guarantees not failing when a user doesn't have enough tokens

* feat(gacha): speedup gacha by pre-removing existing characters from smaller pool
  • Loading branch information
ker0olos authored Apr 4, 2024
1 parent 509314d commit fdbd524
Show file tree
Hide file tree
Showing 10 changed files with 90 additions and 55 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,8 @@ jobs:
deploy:
if: github.event_name == 'push'
runs-on: ubuntu-latest
# needs:
# - test
needs:
- test
permissions:
id-token: write
contents: read
Expand Down
38 changes: 23 additions & 15 deletions db/addTokens.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,11 +59,13 @@ describe('db.addGuarantee()', () => {
guarantees: [1],
} as any);

const user = await db.addGuarantee('user-id', 5);
await db.addGuarantee('user-id', 5);

assertEquals(user!._id, insertedId);
assertEquals(user!.availableTokens, 0);
assertEquals(user!.guarantees, [1, 5]);
const _user = await client.users().findOne({ discordId: 'user-id' });

assertEquals(_user!._id, insertedId);
assertEquals(_user!.availableTokens, 0);
assertEquals(_user!.guarantees, [1, 5]);
});

it('add 4*', async () => {
Expand All @@ -73,11 +75,13 @@ describe('db.addGuarantee()', () => {
guarantees: [1],
} as any);

const user = await db.addGuarantee('user-id', 4);
await db.addGuarantee('user-id', 4);

assertEquals(user!._id, insertedId);
assertEquals(user!.availableTokens, 0);
assertEquals(user!.guarantees, [1, 4]);
const _user = await client.users().findOne({ discordId: 'user-id' });

assertEquals(_user!._id, insertedId);
assertEquals(_user!.availableTokens, 0);
assertEquals(_user!.guarantees, [1, 4]);
});

it('add 3*', async () => {
Expand All @@ -87,11 +91,13 @@ describe('db.addGuarantee()', () => {
guarantees: [1],
} as any);

const user = await db.addGuarantee('user-id', 3);
await db.addGuarantee('user-id', 3);

assertEquals(user!._id, insertedId);
assertEquals(user!.availableTokens, 0);
assertEquals(user!.guarantees, [1, 3]);
const _user = await client.users().findOne({ discordId: 'user-id' });

assertEquals(_user!._id, insertedId);
assertEquals(_user!.availableTokens, 0);
assertEquals(_user!.guarantees, [1, 3]);
});

it('not enough tokens', async () => {
Expand All @@ -101,9 +107,11 @@ describe('db.addGuarantee()', () => {
guarantees: [1],
} as any);

const user = await db.addGuarantee('user-id', 5);

assertEquals(user, null);
await assertRejects(
() => db.addGuarantee('user-id', 5),
Error,
'INSUFFICIENT_TOKENS',
);

const _user = await client.users().findOne({ discordId: 'user-id' });

Expand Down
18 changes: 7 additions & 11 deletions db/addTokens.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,5 @@
import { Mongo } from '~/db/mod.ts';

import type { WithId } from 'mongodb';

import type * as Schema from '~/db/schema.ts';

export const COSTS = {
THREE: 4,
FOUR: 12,
Expand Down Expand Up @@ -72,7 +68,7 @@ export async function addPulls(
export async function addGuarantee(
userId: string,
guarantee: number,
): Promise<WithId<Schema.User> | null> {
): Promise<void> {
const cost = guarantee === 5
? COSTS.FIVE
: guarantee === 4
Expand All @@ -81,23 +77,23 @@ export async function addGuarantee(

const db = new Mongo();

let result: WithId<Schema.User> | null;

try {
await db.connect();

result = await db.users().findOneAndUpdate({
const { modifiedCount } = await db.users().updateOne({
discordId: userId,
availableTokens: { $gte: cost },
}, {
$push: { guarantees: guarantee },
$inc: { availableTokens: -cost },
}, { returnDocument: 'after' });
});

if (!modifiedCount) {
throw new Error('INSUFFICIENT_TOKENS');
}
} finally {
await db.close();
}

return result;
}

export async function addKeys(
Expand Down
6 changes: 6 additions & 0 deletions db/ensureIndexes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,12 @@ async function createCharactersIndexes(db: Mongo) {
{ key: { userId: Direction.ascending, guildId: Direction.ascending } },
{ key: { mediaId: Direction.ascending, guildId: Direction.ascending } },
]);

// @findCharacters.findGuildCharacters
await db.characters() // Normal Index (speeds up queries)
.createIndexes([
{ key: { guildId: Direction.ascending } },
]);
}

async function createPacksIndexes(db: Mongo) {
Expand Down
18 changes: 18 additions & 0 deletions db/getInventory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -470,3 +470,21 @@ export async function getUserCharacters(

return result;
}

export async function getGuildCharacters(
guildId: string,
): Promise<string[]> {
const db = new Mongo();

let result: WithId<Schema.Character>[];

try {
await db.connect();

result = await db.characters().find({ guildId }).toArray();
} finally {
await db.close();
}

return result.map(({ characterId }) => characterId);
}
2 changes: 2 additions & 0 deletions db/mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import config from '~/src/config.ts';
import {
getActiveUsersIfLiked,
getGuild,
getGuildCharacters,
getInventory,
getUser,
getUserCharacters,
Expand Down Expand Up @@ -139,6 +140,7 @@ const db = {
getUser,
getGuild,
getUserCharacters,
getGuildCharacters,
rechargeConsumables,
getActiveUsersIfLiked,
//
Expand Down
21 changes: 18 additions & 3 deletions search-index/mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import {
search_media,
} from 'search-index';

import db from '~/db/mod.ts';

import packs from '~/src/packs.ts';

import utils from '~/src/utils.ts';
Expand Down Expand Up @@ -114,7 +116,7 @@ const searchCharacters = async (
});
};

const filterCharacters = async (
const pool = async (
filter: {
rating?: number;
popularity?: { between: [number, number] };
Expand Down Expand Up @@ -166,20 +168,33 @@ const filterCharacters = async (
}),
)).flat();

return filter_characters(
let pool = filter_characters(
builtin ? await Deno.readFile(charactersIndexPath) : undefined,
extra,
filter.role,
filter?.popularity?.between?.[0],
filter.popularity?.between?.[1],
filter.rating,
);

// attempt to speed pulls by pre-removing existing characters on smaller pools
// avoids checking if db.addCharacter() will fail with no-unique error
if (
(filter.popularity && filter.popularity.between[0] > 200_000) ||
filter.rating && filter.rating > 3
) {
const existing = await db.getGuildCharacters(guildId);

pool = pool.filter(({ id }) => !existing.includes(id));
}

return pool;
};

const searchIndex = {
searchMedia,
searchCharacters,
filterCharacters,
pool,
};

export default searchIndex;
Expand Down
26 changes: 8 additions & 18 deletions src/gacha.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ async function rangePool({ guildId }: { guildId: string }): Promise<{
// one specific role for the whole pool
: utils.rng(variables.roles);

const pool = await searchIndex.filterCharacters(
const pool = await searchIndex.pool(
{ role, popularity: { between: range } },
guildId,
);
Expand Down Expand Up @@ -157,7 +157,7 @@ export async function guaranteedPool(
role?: CharacterRole;
range?: [number, number];
}> {
const pool = await searchIndex.filterCharacters(
const pool = await searchIndex.pool(
{ rating: guarantee },
guildId,
);
Expand Down Expand Up @@ -299,10 +299,9 @@ async function rngPull(
}

async function pullAnimation(
{ token, userId, guildId, quiet, mention, components, pull, fakePull }: {
{ token, userId, guildId, quiet, mention, components, pull }: {
token: string;
pull: Pull;
fakePull?: Pull;
userId?: string;
guildId?: string;
quiet?: boolean;
Expand All @@ -312,8 +311,6 @@ async function pullAnimation(
): Promise<void> {
components ??= true;

const _pull = fakePull ?? pull;

const characterId = `${pull.character.packId}:${pull.character.id}`;

const mediaIds = [
Expand All @@ -324,9 +321,9 @@ async function pullAnimation(
).map(({ node }) => node) ?? [],
].map(({ packId, id }) => `${packId}:${id}`);

const mediaTitles = packs.aliasToArray(_pull.media.title);
const mediaTitles = packs.aliasToArray(pull.media.title);

const mediaImage = _pull.media.images?.[0];
const mediaImage = pull.media.images?.[0];

let message = new discord.Message()
.addEmbed(
Expand Down Expand Up @@ -355,7 +352,7 @@ async function pullAnimation(
.addEmbed(
new discord.Embed()
.setImage({
url: `${config.origin}/assets/stars/${_pull.rating.stars}.gif`,
url: `${config.origin}/assets/stars/${pull.rating.stars}.gif`,
}),
);

Expand All @@ -367,7 +364,7 @@ async function pullAnimation(

await message.patch(token);

await utils.sleep(_pull.rating.stars + 3);
await utils.sleep(pull.rating.stars + 3);
}
//

Expand Down Expand Up @@ -474,21 +471,14 @@ function start(
}

gacha.rngPull({ userId, guildId, guarantee })
.then(async (pull) => {
let fakePull: Pull | undefined = undefined;

if (config.fools) {
fakePull = await gacha.rngPull({ guildId, guarantee: 5 });
}

.then((pull) => {
return pullAnimation({
token,
userId,
guildId,
mention,
quiet,
pull,
fakePull,
});
})
.catch(async (err) => {
Expand Down
8 changes: 4 additions & 4 deletions tests/gacha.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ Deno.test('adding character to inventory', async (test) => {

const poolStub = stub(
searchIndex,
'filterCharacters',
'pool',
() =>
Promise.resolve([
new IndexedCharacter(
Expand Down Expand Up @@ -204,7 +204,7 @@ Deno.test('adding character to inventory', async (test) => {

const poolStub = stub(
searchIndex,
'filterCharacters',
'pool',
() =>
Promise.resolve([
new IndexedCharacter(
Expand Down Expand Up @@ -324,7 +324,7 @@ Deno.test('adding character to inventory', async (test) => {

const poolStub = stub(
searchIndex,
'filterCharacters',
'pool',
() =>
Promise.resolve([
new IndexedCharacter(
Expand Down Expand Up @@ -444,7 +444,7 @@ Deno.test('adding character to inventory', async (test) => {

const poolStub = stub(
searchIndex,
'filterCharacters',
'pool',
() =>
Promise.resolve([
new IndexedCharacter(
Expand Down
4 changes: 2 additions & 2 deletions tests/merge.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -621,7 +621,7 @@ Deno.test('synthesis confirmed', async (test) => {

const poolStub = stub(
searchIndex,
'filterCharacters',
'pool',
() =>
Promise.resolve([
new IndexedCharacter(
Expand Down Expand Up @@ -891,7 +891,7 @@ Deno.test('synthesis confirmed', async (test) => {

const poolStub = stub(
searchIndex,
'filterCharacters',
'pool',
() =>
Promise.resolve([
new IndexedCharacter(
Expand Down

0 comments on commit fdbd524

Please sign in to comment.