Skip to content

Commit

Permalink
chore(gacha): use one db connection for all retires
Browse files Browse the repository at this point in the history
  • Loading branch information
ker0olos committed Jun 5, 2024
1 parent 7d67010 commit 2f66463
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 8 deletions.
10 changes: 3 additions & 7 deletions db/addCharacter.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import db, { Mongo } from '~/db/mod.ts';
import db, { type Mongo } from '~/db/mod.ts';

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

Expand Down Expand Up @@ -108,6 +108,7 @@ export async function addCharacter(
userId,
guildId,
sacrifices,
mongo,
}: {
rating: number;
mediaId: string;
Expand All @@ -116,18 +117,15 @@ export async function addCharacter(
userId: string;
guildId: string;
sacrifices?: ObjectId[];
mongo: Mongo;
},
): Promise<void> {
const locale = user.cachedUsers[userId]?.locale ??
user.cachedUsers[guildId]?.locale;

const mongo = new Mongo();

const session = mongo.startSession();

try {
await mongo.connect();

session.startTransaction();

const { user, ...inventory } = await db.rechargeConsumables(
Expand Down Expand Up @@ -207,11 +205,9 @@ export async function addCharacter(
}

await session.endSession();
await mongo.close();

throw err;
} finally {
await session.endSession();
await mongo.close();
}
}
8 changes: 7 additions & 1 deletion src/gacha.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import i18n from '~/src/i18n.ts';
import user from '~/src/user.ts';
import search from '~/src/search.ts';

import db, { ObjectId } from '~/db/mod.ts';
import db, { Mongo, ObjectId } from '~/db/mod.ts';

import searchIndex from '~/search-index/mod.ts';

Expand Down Expand Up @@ -235,6 +235,8 @@ async function rngPull(
let character: Character | undefined = undefined;
let media: Media | undefined = undefined;

const mongo = new Mongo();

const controller = new AbortController();

const { signal } = controller;
Expand All @@ -251,6 +253,8 @@ async function rngPull(
throw new PoolError();
}

await mongo.connect();

try {
while (!signal.aborted) {
const mediaIndex = Math.floor(Math.random() * poolKeys.length);
Expand Down Expand Up @@ -301,6 +305,7 @@ async function rngPull(
guaranteed: typeof guarantee === 'number',
rating: rating.stars,
sacrifices,
mongo,
});
} catch (err) {
// E11000 duplicate key error collection
Expand All @@ -324,6 +329,7 @@ async function rngPull(
}
} finally {
clearTimeout(timeoutId);
await mongo.close();
}

if (!character || !media || !rating?.stars) {
Expand Down

0 comments on commit 2f66463

Please sign in to comment.