Skip to content

Commit

Permalink
fix(functions-load-balancing): return present instance if available
Browse files Browse the repository at this point in the history
  • Loading branch information
rams23 committed Feb 4, 2021
1 parent eedc95d commit 77b21f7
Showing 1 changed file with 6 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {FirebaseCollection, RTDBPaths} from '@pipeline/common';
import {getDatabase, PROJECT_ID} from "../utils/rtdb";
import {Game} from "../models/Game";
import FieldValue = admin.firestore.FieldValue;

const db = admin.firestore();
const logger = functions.logger;

Expand Down Expand Up @@ -73,7 +74,7 @@ export const selectBestRTDBInstance = functions.region(
.orderBy('connectionsCount', "asc").limit(1).get();
const bestRTDBInstanceDoc = bestRTDBInstanceQuery.docs[0];
const bestRTDBInstance = bestRTDBInstanceDoc.data();
const bestRTDBInstanceName = `${PROJECT_ID}-${bestRTDBInstanceDoc.id}.${bestRTDBInstance.region}`;
let bestRTDBInstanceName = `${PROJECT_ID}-${bestRTDBInstanceDoc.id}.${bestRTDBInstance.region}`;

logger.log(`Selected instance ${bestRTDBInstanceName} with ${bestRTDBInstance.connectionsCount} game connections`);

Expand All @@ -93,15 +94,15 @@ export const selectBestRTDBInstance = functions.region(

await runTransactionWithRetry(db, async transaction => {
const gameDoc = await transaction.get(gameRef);
if(!gameDoc.exists) {
if (!gameDoc.exists) {
throw new functions.https.HttpsError('failed-precondition', `The game with ${gameId} does not exists`);
}
const game = gameDoc.data() as Game
if (!game.rtdbInstance) {
transaction.update(gameRef, {
rtdbInstance: bestRTDBInstanceName,
} as Partial<Game>);
const cards = game.cards !== null ? {...game.cards}: null;
const cards = game.cards !== null ? {...game.cards} : null;
game.cards = null;
game.rtdbInstance = null;
await rtdb.ref(`/${RTDBPaths.Games}/${gameId}`).set({
Expand All @@ -113,6 +114,8 @@ export const selectBestRTDBInstance = functions.region(
...cards,
});
}
} else {
bestRTDBInstanceName = game.rtdbInstance
}
});

Expand Down

0 comments on commit 77b21f7

Please sign in to comment.