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

Fixed tracing prod #180

Merged
merged 7 commits into from
Oct 1, 2024
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
1 change: 1 addition & 0 deletions build.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ const out = esbuild.buildSync({
banner: { js: `/* 2022-${start.getFullYear()} © zhiyan114 GPLv3 UwU | Build: ${commitHash} */` },
outdir: "dist",
});

if(out.errors.length > 0)
console.error(`Build Failed: ${JSON.stringify(out.errors)}`);
const end = Date.now();
Expand Down
276 changes: 141 additions & 135 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"dependencies": {
"@discordjs/rest": "^2.0.0",
"@prisma/client": "^5.0.0",
"@sentry/node": "^8.0.0",
"@sentry/node": "^8.32.0",
"axios": "^1.1.2",
"bufferutil": "^4.0.6",
"canvas": "^2.11.2",
Expand Down
4 changes: 2 additions & 2 deletions src/commands/discord/getPoints.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ApplicationCommandType, ContextMenuCommandBuilder, EmbedBuilder, UserContextMenuCommandInteraction } from "discord.js";
import { ContextMenuCommandBuilder, EmbedBuilder, UserContextMenuCommandInteraction } from "discord.js";
import { DiscordClient } from "../../core/DiscordClient";
import { baseCommand } from "../../core/baseCommand";
import { DiscordUser } from "../../utils/DiscordUser";
Expand All @@ -16,7 +16,7 @@ export class getPointsCommand extends baseCommand {
this.client = client;
this.metadata = new ContextMenuCommandBuilder()
.setName("getpoints")
.setType(ApplicationCommandType.User);
.setType(2); // Workaround for ApplicationCommandType.User since it's throwing type error despite being correct??
}

public async execute(interaction: UserContextMenuCommandInteraction) {
Expand Down
3 changes: 2 additions & 1 deletion src/core/DiscordClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,8 @@ export class DiscordClient extends Client implements baseClient {
this.logger = new eventLogger(this);
this.redis = new Redis((process.env["ISDOCKER"] && !process.env["REDIS_CONN"]) ?
"redis://redis:6379" : process.env["REDIS_CONN"] ?? "", {
keyPrefix: `${this.config.redisPrefix}:`
keyPrefix: `${this.config.redisPrefix}:`,
enableReadyCheck: false,
});
this.prisma = new PrismaClient({
errorFormat: "minimal"
Expand Down
24 changes: 24 additions & 0 deletions src/events/discordEvents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { APIErrors } from "../utils/discordErrorCode";
import { captureException, withScope } from "@sentry/node";
import { BannerPic } from "../utils/bannerGen";
import { Prisma } from "@prisma/client";
import { randomBytes } from "crypto";

export class DiscordEvents extends baseEvent {
client: DiscordClient;
Expand Down Expand Up @@ -40,6 +41,12 @@ export class DiscordEvents extends baseEvent {

private async createCommand(interaction: Interaction) {
await withScope(async (scope) => {
scope.setTransactionName("Discord Interaction Handler");
scope.setPropagationContext({
traceId: randomBytes(16).toString("hex"),
spanId: randomBytes(16).toString("hex"),
});

const gMember = interaction.member as GuildMember | null;
scope.setUser({
id: interaction.user.id,
Expand All @@ -52,6 +59,7 @@ export class DiscordEvents extends baseEvent {

if(interaction.isCommand() || interaction.isContextMenuCommand())
return await this.commandHandler.commandEvent(interaction);


if(interaction.isButton())
if(interaction.customId === "RuleConfirm")
Expand All @@ -61,6 +69,10 @@ export class DiscordEvents extends baseEvent {

private async messageCreate(message: Message) {
await withScope(async (scope) => {
scope.setPropagationContext({
traceId: randomBytes(16).toString("hex"),
spanId: randomBytes(16).toString("hex"),
});
scope.setUser({
id: message.author.id,
username: message.author.username,
Expand All @@ -87,6 +99,10 @@ export class DiscordEvents extends baseEvent {

private async guildMemberAdd(member: GuildMember) {
await withScope(async (scope) => {
scope.setPropagationContext({
traceId: randomBytes(16).toString("hex"),
spanId: randomBytes(16).toString("hex"),
});
scope.setUser({
id: member.user.id,
username: member.user.username,
Expand Down Expand Up @@ -132,6 +148,10 @@ export class DiscordEvents extends baseEvent {

private async userUpdate(oldUser: User | PartialUser, newUser: User) {
await withScope(async (scope) => {
scope.setPropagationContext({
traceId: randomBytes(16).toString("hex"),
spanId: randomBytes(16).toString("hex"),
});
scope.setUser({
id: newUser.id,
username: newUser.username,
Expand Down Expand Up @@ -164,6 +184,10 @@ export class DiscordEvents extends baseEvent {

private async voiceStateUpdate(old: VoiceState, now: VoiceState) {
await withScope(async (scope) => {
scope.setPropagationContext({
traceId: randomBytes(16).toString("hex"),
spanId: randomBytes(16).toString("hex"),
});
scope.setUser({
id: now.member?.user.id,
username: now.member?.user.username,
Expand Down
15 changes: 9 additions & 6 deletions src/events/helper/DiscordCommandHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,23 +102,26 @@ export class DiscordCommandHandler {
}
}
}

startSpan({
await startSpan({
name: `Discord Command: ${command.metadata.name}`,
op: `discord.cmd.${command.metadata.name}`,
}, async () => {
try { await command.execute(interaction); }
try {
await command.execute(interaction);
}
catch(ex) {
const id = captureException(ex, {tags: {handled: "no"}});
await this.client.redis.set(`userSentryErrorID:${interaction.user.id}`, id, "EX", 1800);

// Let the user know that something went wrong
if(interaction.replied || interaction.deferred)
if(interaction.replied)
await interaction.followUp({content: "An error occur during command execution, please use the feedback command to submit a report.", ephemeral: true});
else if (interaction.deferred)
await interaction.editReply({content: "An error occur during command execution, please use the feedback command to submit a report."});
else
await interaction.reply({content: "An error occur during command execution, please use the feedback command to submit a report.", ephemeral: true});
}
});
});
}

public getCommandHash(): Buffer {
Expand Down
2 changes: 1 addition & 1 deletion src/events/helper/TwitchCommandHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export async function processCommand(eventData: eventType): Promise<boolean | un
return false;
}

startSpan({
await startSpan({
name: `Twitch Command: ${command.name}`,
op: `twitch.cmd.${command.name}`,
}, async () => {
Expand Down
6 changes: 5 additions & 1 deletion src/events/twitchEvents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { baseTEvent } from "../core/baseEvent";
import { TwitchUser } from "../utils/TwitchUser";
import { processCommand } from "./helper/TwitchCommandHandler";
import { withScope } from "@sentry/node";
import { randomBytes } from "crypto";


export class TwitchEvents extends baseTEvent {
Expand All @@ -21,9 +22,12 @@ export class TwitchEvents extends baseTEvent {
if(self) return;

await withScope(async (scope) => {

if(!userstate["user-id"] || !userstate['username']) return;

scope.setPropagationContext({
traceId: randomBytes(16).toString("hex"),
spanId: randomBytes(16).toString("hex"),
});
scope.setUser({
id: userstate["user-id"],
username: userstate.username,
Expand Down
14 changes: 3 additions & 11 deletions src/loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ sentryInit({
}
}),
prismaIntegration(),
redisIntegration({cachePrefixes: [redisPrefix]}),
redisIntegration({cachePrefixes: [`${redisPrefix}:`]}),
expressIntegration(),
],

Expand Down Expand Up @@ -109,15 +109,7 @@ sentryInit({


// Start the main software
//import './index';

// Clear import caches. Some libraries like Prisma will be used by sentry before OpenTeletry is registered...
const cacheClear = ["@prisma"];
for(const cache of cacheClear) {
const cacheKey = Object.keys(require.cache).find(key => key.includes(cache));
if(cacheKey)
delete require.cache[cacheKey];
}
import './index';

// eslint-disable-next-line @typescript-eslint/no-require-imports
require("./index"); // Workaround for esbuild's non-order transpilation
//require("./index"); // Workaround for esbuild's non-order transpilation