Skip to content

Commit

Permalink
feat: logs/metrics for presence_update execution time
Browse files Browse the repository at this point in the history
  • Loading branch information
tippfehlr committed Mar 10, 2024
1 parent 5e10a3b commit dad307c
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 9 deletions.
5 changes: 3 additions & 2 deletions locales/en-US.json
Original file line number Diff line number Diff line change
Expand Up @@ -102,5 +102,6 @@
"Yes": "Yes",
":x: That activity role already exists in this guild! :x:": ":x: That activity role already exists in this guild! :x:",
"I don’t use the bot myself. If you want to speed up development or help me pay for the server, please consider supporting me.": "I don’t use the bot myself. If you want to speed up development or help me pay for the server, please consider supporting me.",
"the role will not be removed again if set to true": "the role will not be removed again if set to true"
}
"the role will not be removed again if set to true": "the role will not be removed again if set to true",
"Live": "Live"
}
26 changes: 23 additions & 3 deletions src/modules/bot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import {
import config from './config';
import { i18n, log } from './messages';
import CommandHandler from './commandHandler';
import { configureInfluxDB } from './metrics';
import { configureInfluxDB, writeIntPoint } from './metrics';

export const client = new Discord.Client({
intents: [
Expand Down Expand Up @@ -145,8 +145,18 @@ client.on(Events.ClientReady, () => {
}
});

// PresenceUpdate fires once for every guild the bot shares with the user
client.on(Events.PresenceUpdate, async (oldMember, newMember) => {
const startTime = Date.now();
stats.presenceUpdates++;
let logTime = false;
// no activities changed
// if (oldMember?.activities.toString() === newMember?.activities.toString()) return;
if (newMember.user?.username === 'tippfehlr' && newMember.guild?.name === 'ASTRONEER') {
log.debug(`PRESENCE UPDATE: User ${newMember.user?.username}, ${newMember.activities.toString()}, ${oldMember?.activities.toString() === newMember?.activities.toString()}`)
logTime = true;
}
if (logTime) console.time('pre member-fetch');
if (!newMember.guild) return;
const guildID = newMember.guild.id;
if (!newMember.guild.members.me?.permissions.has(PermissionsBitField.Flags.ManageRoles)) {
Expand All @@ -164,7 +174,11 @@ client.on(Events.PresenceUpdate, async (oldMember, newMember) => {
const highestBotRolePosition = newMember.guild.members.me?.roles.highest.position;
const userIDHash = createHash('sha256').update(newMember.user.id).digest('base64');
const guildConfig = getGuildConfig(guildID);
await newMember.member?.fetch();
if (logTime) console.timeEnd('pre member-fetch');
// if (debug) console.time('fetch member ' + date);
// await newMember.member?.fetch(true);
// if (debug) console.timeEnd('fetch member ' + date);
if (logTime) console.time('roles');

if (
guildConfig.requiredRoleID !== null &&
Expand All @@ -187,10 +201,11 @@ client.on(Events.PresenceUpdate, async (oldMember, newMember) => {
prepare('SELECT * FROM activeTemporaryRoles WHERE userIDHash = ? AND guildID = ?')
.all(userIDHash, guildID) as DBActiveTemporaryRoles[];

if (logTime) console.timeEnd('roles');
if (statusRoles.length === 0 && activityRoles.length === 0 && activeTemporaryRoles.length === 0) {
return;
}

if (logTime) console.time('detect changes');
const permanentRoleIDsToBeAdded: Set<string> = new Set();
const tempRoleIDsToBeAdded: Set<string> = new Set();
const addRole = ({ roleID, permanent }: { roleID: string, permanent: boolean }) => {
Expand Down Expand Up @@ -227,6 +242,9 @@ client.on(Events.PresenceUpdate, async (oldMember, newMember) => {
}
});

if (logTime) console.timeEnd('detect changes');
if (logTime) console.time('apply changes');

// ------------ “apply changes” ------------
const addDiscordRoleToMember = ({ roleID, permanent }: { roleID: string, permanent: boolean }) => {
const role = newMember.guild?.roles.cache.get(roleID);
Expand Down Expand Up @@ -286,6 +304,8 @@ client.on(Events.PresenceUpdate, async (oldMember, newMember) => {
stats.rolesRemoved++;
});
});
if (logTime) console.timeEnd('apply changes');
writeIntPoint('presence_updates', 'took_time', Date.now() - startTime)
});

client.on(Events.GuildCreate, guild => {
Expand Down
9 changes: 5 additions & 4 deletions src/modules/metrics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,16 @@ import { getDBUserCount, getRolesCount, stats as dbStats, resetStats as resetDBS
export let client: InfluxDB;
export let writeApi: WriteApi;

export function writeIntPoint(name: string, fieldName: string, value: number) {
if (writeApi) writeApi.writePoint(new Point(name).intField(fieldName, value));
}


export async function configureInfluxDB() {
if (config.INFLUX_URL && config.INFLUX_TOKEN) {
client = new InfluxDB({ url: config.INFLUX_URL, token: config.INFLUX_TOKEN });
writeApi = client.getWriteApi('activity-roles', 'activity-roles');

const writeIntPoint = (name: string, fieldName: string, value: number) => {
writeApi.writePoint(new Point(name).intField(fieldName, value));
}

writeIntPoint('process', 'started', 1);
setInterval(() => {
const startTime = performance.now();
Expand Down

0 comments on commit dad307c

Please sign in to comment.