Skip to content

Commit

Permalink
feat(worker): Add metrics for giveaways and reminders
Browse files Browse the repository at this point in the history
  • Loading branch information
tzushimelon committed Feb 7, 2024
1 parent fe875d5 commit 7794639
Show file tree
Hide file tree
Showing 4 changed files with 99 additions and 12 deletions.
10 changes: 10 additions & 0 deletions packages/sushii-worker/src/db/Giveaway/Giveaway.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,16 @@ export function getAllActiveGiveaways(
return query.execute();
}

export async function countAllActiveGiveaways(db: Kysely<DB>): Promise<number> {
const { count } = await db
.selectFrom("app_public.giveaways")
.select((eb) => eb.fn.countAll<number>().as("count"))
.where("is_ended", "=", false)
.executeTakeFirstOrThrow();

return count;
}

export function getAllCompletedGiveaways(
db: Kysely<DB>,
guildId: string,
Expand Down
51 changes: 50 additions & 1 deletion packages/sushii-worker/src/metrics.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import { InteractionType } from "discord-api-types/v10";
import { GatewayDispatchEvents, Interaction } from "discord.js";
import {
ApplicationCommandType,
GatewayDispatchEvents,
Interaction,
} from "discord.js";
import { collectDefaultMetrics, Counter, Gauge } from "prom-client";
import logger from "./logger";

Expand Down Expand Up @@ -63,6 +67,47 @@ const modalCounter = new Counter({
labelNames: ["status"],
});

// -----------------------------------------------------------------------------
// Reminders

export const pendingRemindersGauge = new Gauge({
name: prefixedName("reminders_pending"),
help: "Pending reminders",
});

export const sentRemindersCounter = new Counter({
name: prefixedName("reminders_sent"),
help: "Sent reminders",
labelNames: ["status"],
});

// -----------------------------------------------------------------------------
// Tempbans

export const pendingTempBansGauge = new Gauge({
name: prefixedName("tempban_pending"),
help: "Pending temporary bans",
});

export const unbannedTempBansCounter = new Counter({
name: prefixedName("tempban_unbanned"),
help: "Unbanned users from temporary bans",
labelNames: ["status"],
});

// -----------------------------------------------------------------------------
// Giveaways

export const activeGiveawaysGauge = new Gauge({
name: prefixedName("giveaways_active"),
help: "Active giveaways",
});

export const endedGiveawaysCounter = new Counter({
name: prefixedName("giveaways_ended"),
help: "Ended giveaways",
});

export function updateInteractionMetrics(
interaction: Interaction,
status: "success" | "error",
Expand All @@ -71,6 +116,10 @@ export function updateInteractionMetrics(

switch (type) {
case InteractionType.ApplicationCommand: {
switch (interaction.commandType) {
case ApplicationCommandType.ChatInput: {
}
}
slashCommandsCounter.inc({
command_name: interaction.commandName,
status,
Expand Down
13 changes: 12 additions & 1 deletion packages/sushii-worker/src/tasks/GiveawayTask.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,15 @@ import logger from "../logger";
import Context from "../model/context";
import BackgroundTask from "./BackgroundTask";
import db from "../model/db";
import { getAndEndPendingGiveaways } from "../db/Giveaway/Giveaway.repository";
import {
countAllActiveGiveaways,
getAndEndPendingGiveaways,
} from "../db/Giveaway/Giveaway.repository";
import {
endGiveaway,
updateGiveawayMessage,
} from "../interactions/giveaway/Giveaway.service";
import { activeGiveawaysGauge, endedGiveawaysCounter } from "../metrics";

const task: BackgroundTask = {
name: "Check for expired giveaways",
Expand Down Expand Up @@ -67,6 +71,13 @@ const task: BackgroundTask = {
await updateGiveawayMessage(giveawayChannel, giveaway, winnerIds);
}
/* eslint-enable no-await-in-loop */

// Increment ended metric
endedGiveawaysCounter.inc(expiredGiveaways.length);

// Update total active metric
const totalActive = await countAllActiveGiveaways(db);
activeGiveawaysGauge.set(totalActive);
},
};

Expand Down
37 changes: 27 additions & 10 deletions packages/sushii-worker/src/tasks/RemindersTask.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { getAndDeleteExpiredReminders } from "../db/Reminder/Reminder.repository
import db from "../model/db";
import Color from "../utils/colors";
import toTimestamp from "../utils/toTimestamp";
import { sentRemindersCounter } from "../metrics";

const task: BackgroundTask = {
name: "Check for expired reminders",
Expand All @@ -24,32 +25,48 @@ const task: BackgroundTask = {
"checking and deleting expired reminders",
);

let numSuccess = 0;
let numFailed = 0;

/* eslint-disable no-await-in-loop */
for (const reminder of expiredReminders) {
let user;
try {
user = await ctx.client.users.fetch(reminder.user_id);
} catch (err) {
continue;
}

const embed = new EmbedBuilder()
.setTitle(
`Reminder expired from ${toTimestamp(dayjs.utc(reminder.expire_at))}`,
)
.setDescription(reminder.description || "No description.")
.setColor(Color.Info);
const embed = new EmbedBuilder()
.setTitle(
`Reminder expired from ${toTimestamp(dayjs.utc(reminder.expire_at))}`,
)
.setDescription(reminder.description || "No description.")
.setColor(Color.Info);

try {
await user.send({
embeds: [embed],
});

numSuccess += 1;
} catch (err) {
// Might fail if the user has DMs disabled
numFailed += 1;
continue;
}
}
/* eslint-enable no-await-in-loop */

sentRemindersCounter.inc(
{
status: "success",
},
numSuccess,
);

sentRemindersCounter.inc(
{
status: "failed",
},
numFailed,
);
},
};

Expand Down

0 comments on commit 7794639

Please sign in to comment.