Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Not creating a new database session per transaction unit. #252

Merged
merged 1 commit into from
Nov 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"name": "logos",
"description": "A multi-purpose community bot built to cater to language-learning communities on Discord.",
"license": "ISC",
"version": "3.26.3",
"version": "3.26.4",
"type": "module",
"keywords": [
"discord",
Expand Down
63 changes: 35 additions & 28 deletions src/lib/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,10 +95,7 @@ type Client = {
warningsByTarget: Map<string, Map<string, Warning>>;
};
};
database: {
store: ravendb.IDocumentStore;
session: ravendb.IDocumentSession;
};
database: ravendb.IDocumentStore;
commands: {
commands: Record<keyof typeof commandTemplates, Command>;
showable: string[];
Expand Down Expand Up @@ -305,7 +302,7 @@ async function initialiseClient(
features: Client["features"],
localisations: Map<string, Map<LocalisationLanguage, string>>,
): Promise<void> {
const store = new ravendb.DocumentStore(
const database = new ravendb.DocumentStore(
environment.ravendbHost,
environment.ravendbDatabase,
environment.ravendbSecure
Expand All @@ -315,12 +312,10 @@ async function initialiseClient(
}
: {},
).initialize();
const session = store.openSession();
const database: Client["database"] = { store, session };

const client = createClient(environment, features, database, localisations);

addCacheInterceptors(client, database.session);
addCacheInterceptors(client, database);

await prefetchDataFromDatabase(client);

Expand Down Expand Up @@ -458,21 +453,21 @@ async function initialiseClient(
}

async function prefetchDataFromDatabase(client: Client): Promise<void> {
const entryRequestDocuments = await client.database.session
.query<EntryRequest>({ collection: "EntryRequests" })
.all();
const session = client.database.openSession();

const entryRequestDocuments = await session.query<EntryRequest>({ collection: "EntryRequests" }).all();

for (const document of entryRequestDocuments) {
client.cache.documents.entryRequests.set(document.id, document);
}

const reportDocuments = await client.database.session.query<Report>({ collection: "Reports" }).all();
const reportDocuments = await session.query<Report>({ collection: "Reports" }).all();

for (const document of reportDocuments) {
client.cache.documents.reports.set(`${document.guildId}/${document.authorId}/${document.createdAt}`, document);
}

const suggestionDocuments = await client.database.session.query<Suggestion>({ collection: "Suggestions" }).all();
const suggestionDocuments = await session.query<Suggestion>({ collection: "Suggestions" }).all();

for (const document of suggestionDocuments) {
client.cache.documents.suggestions.set(`${document.guildId}/${document.authorId}/${document.createdAt}`, document);
Expand All @@ -488,9 +483,11 @@ export async function handleGuildCreate(
client.log.info(`Logos added to "${guild.name}" (ID ${guild.id}).`);
}

const session = client.database.openSession();

const guildDocument =
client.cache.documents.guilds.get(guild.id.toString()) ??
(await client.database.session.load<Guild>(`guilds/${guild.id}`).then((value) => value ?? undefined));
(await session.load<Guild>(`guilds/${guild.id}`).then((value) => value ?? undefined));
if (guildDocument === undefined) {
return;
}
Expand Down Expand Up @@ -751,8 +748,8 @@ async function handleInteractionCreate(
}
}

function addCacheInterceptors(client: Client, session: ravendb.IDocumentSession): void {
const { load, store } = session;
function addCacheInterceptors(client: Client, database: ravendb.IDocumentStore): void {
const { openSession } = database;

// biome-ignore lint: Typing this out in TypeScript is a nonsense and I don't have time to do it right now.
function getCompositeId(collection: string, document: any): string {
Expand Down Expand Up @@ -845,24 +842,34 @@ function addCacheInterceptors(client: Client, session: ravendb.IDocumentSession)
}

// @ts-ignore
session.load = async (...args) => {
database.openSession = () => {
// @ts-ignore
const value = await load.call(session, ...args);
if (value === null) {
return value;
}
const session = openSession.call(database, { noTracking: true, noCaching: true });

saveValue(value);
const { load, store } = session;

return value;
};
// @ts-ignore
session.load = async (...args) => {
// @ts-ignore
const value = await load.call(session, ...args);
if (value === null) {
return value;
}

saveValue(value);

return value;
};

// @ts-ignore
session.store = async (value, ...args) => {
// @ts-ignore
await store.call(session, value, ...args);
session.store = async (value, ...args) => {
// @ts-ignore
await store.call(session, value, ...args);

saveValue(value);
};

saveValue(value);
return session;
};
}

Expand Down
4 changes: 3 additions & 1 deletion src/lib/commands/information/commands/information/guild.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,11 @@ async function handleDisplayGuildInformation(
return;
}

const session = client.database.openSession();

const guildDocument =
client.cache.documents.guilds.get(guildId.toString()) ??
(await client.database.session.load<Guild>(`guilds/${guildId}`).then((value) => value ?? undefined));
(await session.load<Guild>(`guilds/${guildId}`).then((value) => value ?? undefined));
if (guildDocument === undefined) {
return;
}
Expand Down
10 changes: 6 additions & 4 deletions src/lib/commands/information/commands/list/warnings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,9 +63,11 @@ async function handleDisplayWarnings(

const isSelf = member.id === interaction.user.id;

const session = client.database.openSession();

const userDocument =
client.cache.documents.users.get(member.id.toString()) ??
(await client.database.session.load<User>(`users/${member.id}`).then((value) => value ?? undefined)) ??
(await session.load<User>(`users/${member.id}`).then((value) => value ?? undefined)) ??
(await (async () => {
const userDocument = {
...({
Expand All @@ -75,8 +77,8 @@ async function handleDisplayWarnings(
} satisfies User),
"@metadata": { "@collection": "Users" },
};
await client.database.session.store(userDocument);
await client.database.session.saveChanges();
await session.store(userDocument);
await session.saveChanges();

return userDocument as User;
})());
Expand All @@ -89,7 +91,7 @@ async function handleDisplayWarnings(
const warningDocuments =
warningDocumentsCached !== undefined
? Array.from(warningDocumentsCached.values())
: await client.database.session
: await session
.query<Warning>({ collection: "Warnings" })
.whereStartsWith("id", `warnings/${member.id}`)
.all()
Expand Down
4 changes: 3 additions & 1 deletion src/lib/commands/language/commands/cefr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,11 @@ async function handleDisplayCefrGuide(
return;
}

const session = client.database.openSession();

const guildDocument =
client.cache.documents.guilds.get(guildId.toString()) ??
(await client.database.session.load<Guild>(`guilds/${guildId}`).then((value) => value ?? undefined));
(await session.load<Guild>(`guilds/${guildId}`).then((value) => value ?? undefined));
if (guildDocument === undefined) {
return;
}
Expand Down
4 changes: 3 additions & 1 deletion src/lib/commands/language/commands/resources.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,11 @@ async function handleDisplayResources(
return;
}

const session = client.database.openSession();

const guildDocument =
client.cache.documents.guilds.get(guildId.toString()) ??
(await client.database.session.load<Guild>(`guilds/${guildId}`).then((value) => value ?? undefined));
(await session.load<Guild>(`guilds/${guildId}`).then((value) => value ?? undefined));
if (guildDocument === undefined) {
return;
}
Expand Down
7 changes: 5 additions & 2 deletions src/lib/commands/meta/commands/settings/language/clear.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,12 @@ async function handleClearLanguage(
): Promise<void> {
const locale = interaction.locale;

const session = client.database.openSession();

await postponeReply([client, bot], interaction);
const userDocument =
client.cache.documents.users.get(interaction.user.id.toString()) ??
(await client.database.session.load<User>(`users/${interaction.user.id}`).then((value) => value ?? undefined));
(await session.load<User>(`users/${interaction.user.id}`).then((value) => value ?? undefined));
if (userDocument === undefined) {
return;
}
Expand All @@ -45,7 +47,8 @@ async function handleClearLanguage(
}

userDocument.account.language = undefined;
await client.database.session.saveChanges();
await session.store(userDocument);
await session.saveChanges();

{
const strings = {
Expand Down
7 changes: 5 additions & 2 deletions src/lib/commands/meta/commands/settings/language/set.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,16 +68,19 @@ async function handleSetLanguage([client, bot]: [Client, Discord.Bot], interacti

const language = languageOrUndefined;

const session = client.database.openSession();

await postponeReply([client, bot], interaction);
const userDocument =
client.cache.documents.users.get(interaction.user.id.toString()) ??
(await client.database.session.load<User>(`users/${interaction.user.id}`).then((value) => value ?? undefined));
(await session.load<User>(`users/${interaction.user.id}`).then((value) => value ?? undefined));
if (userDocument === undefined) {
return;
}

userDocument.account.language = language;
await client.database.session.saveChanges();
await session.store(userDocument);
await session.saveChanges();

const locale = getLocaleByLocalisationLanguage(language);

Expand Down
4 changes: 3 additions & 1 deletion src/lib/commands/meta/commands/settings/view.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,11 @@ async function handleDisplaySettings(
): Promise<void> {
const locale = interaction.locale;

const session = client.database.openSession();

const userDocument =
client.cache.documents.users.get(interaction.user.id.toString()) ??
(await client.database.session.load<User>(`users/${interaction.user.id}`).then((value) => value ?? undefined));
(await session.load<User>(`users/${interaction.user.id}`).then((value) => value ?? undefined));
if (userDocument === undefined) {
return;
}
Expand Down
18 changes: 12 additions & 6 deletions src/lib/commands/moderation/commands/pardon.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,11 @@ async function handlePardonUserAutocomplete(
return;
}

const session = client.database.openSession();

const guildDocument =
client.cache.documents.guilds.get(guildId.toString()) ??
(await client.database.session.load<Guild>(`guilds/${guildId}`).then((value) => value ?? undefined));
(await session.load<Guild>(`guilds/${guildId}`).then((value) => value ?? undefined));
if (guildDocument === undefined) {
return;
}
Expand Down Expand Up @@ -117,9 +119,11 @@ async function handlePardonUser([client, bot]: [Client, Discord.Bot], interactio
return;
}

const session = client.database.openSession();

const guildDocument =
client.cache.documents.guilds.get(guildId.toString()) ??
(await client.database.session.load<Guild>(`guilds/${guildId}`).then((value) => value ?? undefined));
(await session.load<Guild>(`guilds/${guildId}`).then((value) => value ?? undefined));
if (guildDocument === undefined) {
return;
}
Expand Down Expand Up @@ -162,8 +166,8 @@ async function handlePardonUser([client, bot]: [Client, Discord.Bot], interactio
return;
}

await client.database.session.delete(warning.id);
await client.database.session.saveChanges();
await session.delete(warning.id);
await session.saveChanges();

client.cache.documents.warningsByTarget
.get(member.id.toString())
Expand Down Expand Up @@ -207,9 +211,11 @@ async function getRelevantWarnings(
member: Logos.Member,
expirationMilliseconds: number,
): Promise<Warning[] | undefined> {
const session = client.database.openSession();

const userDocument =
client.cache.documents.users.get(member.id.toString()) ??
(await client.database.session.load<User>(`users/${member.id}`).then((value) => value ?? undefined));
(await session.load<User>(`users/${member.id}`).then((value) => value ?? undefined));
if (userDocument === undefined) {
return undefined;
}
Expand All @@ -218,7 +224,7 @@ async function getRelevantWarnings(
const warningDocuments =
warningDocumentsCached !== undefined
? Array.from(warningDocumentsCached.values())
: await client.database.session
: await session
.query<Warning>({ collection: "Warnings" })
.whereStartsWith("id", `warnings/${member.id}`)
.all()
Expand Down
4 changes: 3 additions & 1 deletion src/lib/commands/moderation/commands/policy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,11 @@ async function handleDisplayModerationPolicy(
return;
}

const session = client.database.openSession();

const guildDocument =
client.cache.documents.guilds.get(guildId.toString()) ??
(await client.database.session.load<Guild>(`guilds/${guildId}`).then((value) => value ?? undefined));
(await session.load<Guild>(`guilds/${guildId}`).then((value) => value ?? undefined));
if (guildDocument === undefined) {
return;
}
Expand Down
4 changes: 3 additions & 1 deletion src/lib/commands/moderation/commands/purge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,11 @@ async function handlePurgeMessages(
return;
}

const session = client.database.openSession();

const guildDocument =
client.cache.documents.guilds.get(guildId.toString()) ??
(await client.database.session.load<Guild>(`guilds/${guildId}`).then((value) => value ?? undefined));
(await session.load<Guild>(`guilds/${guildId}`).then((value) => value ?? undefined));
if (guildDocument === undefined) {
return;
}
Expand Down
Loading