Skip to content

Commit

Permalink
Merge pull request #42 from tresabhi/1.14.1
Browse files Browse the repository at this point in the history
  • Loading branch information
tresabhi authored Oct 18, 2023
2 parents 900c290 + a730f67 commit 495a830
Show file tree
Hide file tree
Showing 14 changed files with 76 additions and 58 deletions.
1 change: 1 addition & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"kranvagn",
"Leaderboard",
"leaderboards",
"Oopsy",
"outdir",
"outfile",
"ownedtanks",
Expand Down
17 changes: 17 additions & 0 deletions docs/changelogs/1.14.1.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Blitzkrieg 1.14.1

Oopsy daisy, a memory leak!

## Changes

- Simplified message for users to use `/link`

## Fixes

- Fixed a memory leak in the render thread manager

## Technical changes

- Added `UserError` extending `Error`
- This lets the bot avoid spamming the debug console for mistakes users make
- Reduced render threads to 2
17 changes: 10 additions & 7 deletions src/commands/ratings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import getMidnightLeaderboard, {
DATABASE_REPO,
} from '../core/blitzkrieg/getMidnightLeaderboard';
import { octokit } from '../core/blitzkrieg/octokit';
import throwError from '../core/blitzkrieg/throwError';
import { UserError } from '../core/blitzkrieg/userError';
import addRegionChoices from '../core/discord/addRegionChoices';
import addUsernameChoices from '../core/discord/addUsernameChoices';
import autocompleteUsername from '../core/discord/autocompleteUsername';
Expand Down Expand Up @@ -185,7 +185,7 @@ export const ratingsCommand = new Promise<CommandRegistryRaw>(
})
.then(({ data }) => {
if (!Array.isArray(data)) {
throw throwError('Archived ratings data is malformed');
throw new Error('Archived ratings data is malformed');
}
return data.map(
(folder) =>
Expand Down Expand Up @@ -292,7 +292,7 @@ export const ratingsCommand = new Promise<CommandRegistryRaw>(
})
.then(async ({ data }) => {
if (Array.isArray(data) || data.type !== 'file') {
throw throwError('Archived ratings data is malformed');
throw new Error('Archived ratings data is malformed');
}

const players = (await fetch(data.download_url!).then(
Expand Down Expand Up @@ -361,7 +361,7 @@ export const ratingsCommand = new Promise<CommandRegistryRaw>(
})
.then(async ({ data }) => {
if (Array.isArray(data) || data.type !== 'file') {
throw throwError('Archived ratings info is malformed');
throw new Error('Archived ratings info is malformed');
}

const response = fetch(data.download_url!);
Expand Down Expand Up @@ -404,7 +404,7 @@ export const ratingsCommand = new Promise<CommandRegistryRaw>(
})
.then(async ({ data }) => {
if (Array.isArray(data) || data.type !== 'file') {
throw throwError(
throw new Error(
'Archived ratings latest data is malformed',
);
}
Expand All @@ -418,9 +418,12 @@ export const ratingsCommand = new Promise<CommandRegistryRaw>(
);

if (playerIndex === -1) {
throw throwError(
throw new UserError(
`${accountInfo.nickname} didn't player ratings in season ${season}`,
'This player did not participate in this season or did not get past calibration.',
{
cause:
'This player did not participate in this season or did not get past calibration.',
},
);
}

Expand Down
9 changes: 3 additions & 6 deletions src/core/blitz/fetchWargaming.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import throwError from '../blitzkrieg/throwError';

export type BlitzResponse<Data extends object> =
| {
status: 'error';
Expand All @@ -18,9 +16,8 @@ export default async function fetchBlitz<Data extends object>(url: string) {
if (data.status === 'ok') {
return data.data;
} else {
throw throwError(
`Wargaming response error status:"${data.status}"`,
`Message: "${data.error.message}"\nURL: "${url}"`,
);
throw new Error(`Wargaming response error status:"${data.status}"`, {
cause: `Message: "${data.error.message}"\nURL: "${url}"`,
});
}
}
10 changes: 5 additions & 5 deletions src/core/blitz/getTankStats.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Region } from '../../constants/regions';
import { WARGAMING_APPLICATION_ID } from '../../constants/wargamingApplicationID';
import { TanksStats } from '../../types/tanksStats';
import throwError from '../blitzkrieg/throwError';
import { UserError } from '../blitzkrieg/userError';
import fetchBlitz from './fetchWargaming';

export default async function getTankStats(region: Region, id: number) {
Expand All @@ -10,10 +10,10 @@ export default async function getTankStats(region: Region, id: number) {
);

if (tankStats[id] === null) {
throw throwError(
'No tank stats available',
"This player doesn't have any stats for tanks available. This may not be the player you are looking for.",
);
throw new UserError('No tank stats available', {
cause:
"This player doesn't have any stats for tanks available. This may not be the player you are looking for.",
});
}

return tankStats[id];
Expand Down
16 changes: 7 additions & 9 deletions src/core/blitz/resolveTankId.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { go } from 'fuzzysort';
import throwError from '../blitzkrieg/throwError';
import { UserError } from '../blitzkrieg/userError';
import { TANKS, tankopedia } from '../blitzstars/tankopedia';

export default async function resolveTankId(tank: string | number) {
Expand All @@ -12,21 +12,19 @@ export default async function resolveTankId(tank: string | number) {
});

if (searchResult.length === 0) {
throw throwError(
'Tank not found',
`Could not find tank by the name "${tank}".`,
);
throw new UserError('Tank not found', {
cause: `Could not find tank by the name "${tank}".`,
});
} else {
return searchResult[0].obj.tank_id;
}
} else {
if ((await tankopedia)[number]) {
return number;
} else {
throw throwError(
'Tank not found',
`Could not find tank by the ID "${number}".`,
);
throw new UserError('Tank not found', {
cause: `Could not find tank by the ID "${number}".`,
});
}
}
}
3 changes: 1 addition & 2 deletions src/core/blitzkrieg/getArchivedRatingsInfo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { RatingsInfo } from '../../commands/ratings';
import { Region } from '../../constants/regions';
import { DATABASE_REPO } from './getMidnightLeaderboard';
import { octokit } from './octokit';
import throwError from './throwError';

const ARCHIVED_RATINGS_CACHE: Record<
Region,
Expand Down Expand Up @@ -32,7 +31,7 @@ export default async function getArchivedRatingsInfo(
});

if (Array.isArray(data) || data.type !== 'file')
throw throwError('Archived ratings info is malformed');
throw new Error('Archived ratings info is malformed');

const content = Buffer.from(data.content, 'base64').toString();
const jsonContent = JSON.parse(content) as RatingsInfo & {
Expand Down
18 changes: 11 additions & 7 deletions src/core/blitzkrieg/svgToPngThreaded.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Worker } from 'worker_threads';

const MAX_WORKERS = 3;
const MAX_WORKERS = 2;

const workers = [...Array(MAX_WORKERS)].map(() => {
const worker = new Worker(`${__dirname}/workers/render.cjs`);
Expand All @@ -19,18 +19,22 @@ function manageQueue() {

function cleanup() {
workers.push(worker);
worker.off('message', handleMessage);
worker.off('error', handleError);
manageQueue();
}

worker.postMessage(svg);
worker.on('message', (png: Uint8Array) => {
function handleMessage(png: Uint8Array) {
cleanup();
resolve(Buffer.from(png));
});
worker.on('error', (error) => {
}
function handleError(error: Error) {
cleanup();
throw error;
});
}

worker.postMessage(svg);
worker.on('message', handleMessage);
worker.on('error', handleError);
}
}

Expand Down
3 changes: 0 additions & 3 deletions src/core/blitzkrieg/throwError.ts

This file was deleted.

4 changes: 4 additions & 0 deletions src/core/blitzkrieg/userError.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/**
* Discriminator for user caused errors to not report in logs
*/
export class UserError extends Error {}
9 changes: 4 additions & 5 deletions src/core/discord/resolveClanFromCommand.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { ChatInputCommandInteraction } from 'discord.js';
import { Region } from '../../constants/regions';
import searchClansAcrossRegions from '../blitz/searchClansAcrossRegions';
import throwError from '../blitzkrieg/throwError';
import { UserError } from '../blitzkrieg/userError';
import { serverAndIdPattern } from './resolvePlayerFromCommand';

export default async function resolveClanFromCommand(
Expand All @@ -18,10 +18,9 @@ export default async function resolveClanFromCommand(
if (accounts[0]) {
return { region: accounts[0].region, id: accounts[0].clan_id };
} else {
throw throwError(
'Could not find clan',
`I couldn't find clan \`${clan}\`. Try selecting a username from the search result.`,
);
throw new UserError('Could not find clan', {
cause: `I couldn't find clan \`${clan}\`. Try selecting a username from the search result.`,
});
}
}
}
16 changes: 7 additions & 9 deletions src/core/discord/resolvePlayerFromCommand.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import markdownEscape from 'markdown-escape';
import { Region } from '../../constants/regions';
import searchPlayersAcrossRegions from '../blitz/searchPlayersAcrossRegions';
import { getBlitzFromDiscord } from '../blitzkrieg/discordBlitz';
import throwError from '../blitzkrieg/throwError';
import { UserError } from '../blitzkrieg/userError';

export const serverAndIdPattern = /(com|eu|asia)\/[0-9]+/;

Expand Down Expand Up @@ -34,12 +34,11 @@ export default async function resolvePlayerFromCommand(
id: accounts[0].account_id,
} satisfies ResolvedPlayer;
} else {
throw throwError(
'Could not find user',
`I couldn't find user "${markdownEscape(
throw new UserError('Could not find user', {
cause: `I couldn't find user "${markdownEscape(
commandUsername,
)}". Try picking an user from the search result, typing in a valid username, or using the \`/link\` command.`,
);
});
}
}
} else {
Expand All @@ -48,10 +47,9 @@ export default async function resolvePlayerFromCommand(
if (account) {
return { region: account.region, id: account.blitz };
} else {
throw throwError(
"You're not linked",
'Use the `/link` command to link your Discord and Blitz accounts.',
);
throw new UserError('Use the `/link` command', {
cause: 'Link your Blitz and Discord accounts to get started.',
});
}
}
}
4 changes: 1 addition & 3 deletions src/events/interactionCreate/handlers/button.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { ButtonInteraction, CacheType } from 'discord.js';
import { commands } from '..';
import throwError from '../../../core/blitzkrieg/throwError';
import normalizeInteractionReturnable from '../../../core/discord/normalizeInteractionReturnable';

export default async function handleButton(
Expand All @@ -13,8 +12,7 @@ export default async function handleButton(
const button = (await commands)[commandName]?.button;

if (!button) {
throwError(`Button handler not found for "${commandName}"`);
return;
throw new Error(`Button handler not found for "${commandName}"`);
}

if (interaction.message.interaction?.user.id !== interaction.user.id) {
Expand Down
7 changes: 5 additions & 2 deletions src/events/interactionCreate/handlers/chatInputCommand.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,11 @@ import {
} from 'discord.js';
import { commands } from '..';
import discord from '../../../../discord.json' assert { type: 'json' };
import { psa } from '../../../core/discord/psa';
import { UserError } from '../../../core/blitzkrieg/userError';
import embedNegative from '../../../core/discord/embedNegative';
import embedWarning from '../../../core/discord/embedWarning';
import normalizeInteractionReturnable from '../../../core/discord/normalizeInteractionReturnable';
import { psa } from '../../../core/discord/psa';

export default async function handleChatInputCommand(
interaction: ChatInputCommandInteraction<CacheType>,
Expand Down Expand Up @@ -53,7 +54,9 @@ export default async function handleChatInputCommand(
.setStyle(ButtonStyle.Link),
);

console.error(interaction.commandName, error);
if (!(error instanceof UserError)) {
console.error(interaction.commandName, error);
}

await interaction.editReply({
embeds: [
Expand Down

0 comments on commit 495a830

Please sign in to comment.