Skip to content

Commit

Permalink
AsyncLocalStorage experiment (nonfunctional)
Browse files Browse the repository at this point in the history
  • Loading branch information
kevinlul committed Dec 3, 2023
1 parent 040ab93 commit 550080c
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 26 deletions.
46 changes: 24 additions & 22 deletions src/Command.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { RESTPostAPIApplicationCommandsJSONBody } from "discord-api-types/v10";
import { AutocompleteInteraction, ChatInputCommandInteraction } from "discord.js";
import { Logger } from "./logger";
import { Logger, asyncLocalStorage } from "./logger";
import { Metrics } from "./metrics";
import { serialiseInteraction } from "./utils";

Expand Down Expand Up @@ -34,28 +34,30 @@ export abstract class Command {
* @param interaction
*/
async run(interaction: ChatInputCommandInteraction): Promise<void> {
try {
this.logger.verbose(
serialiseInteraction(interaction, { event: "attempt", ping: interaction.client.ws.ping })
);
const latency = await this.execute(interaction);
this.logger.verbose(serialiseInteraction(interaction, { event: "success", latency }));
this.metrics.writeCommand(interaction, latency);
} catch (error) {
this.metrics.writeCommand(interaction, -1);
this.logger.error(serialiseInteraction(interaction), error);
let method;
if (interaction.replied) {
method = "followUp" as const;
} else if (interaction.deferred) {
method = "editReply" as const;
} else {
method = "reply" as const;
await asyncLocalStorage.run(interaction, async () => {
try {
this.logger.verbose(
serialiseInteraction(interaction, { event: "attempt", ping: interaction.client.ws.ping })
);
const latency = await this.execute(interaction);
this.logger.verbose(serialiseInteraction(interaction, { event: "success", latency }));
this.metrics.writeCommand(interaction, latency);
} catch (error) {
this.metrics.writeCommand(interaction, -1);
this.logger.error(serialiseInteraction(interaction), error);
let method;
if (interaction.replied) {
method = "followUp" as const;
} else if (interaction.deferred) {
method = "editReply" as const;
} else {
method = "reply" as const;
}
await interaction[method]("Something went wrong. Please try again later.").catch(e =>
this.logger.error(serialiseInteraction(interaction), e)
);
}
await interaction[method]("Something went wrong. Please try again later.").catch(e =>
this.logger.error(serialiseInteraction(interaction), e)
);
}
});
}
}

Expand Down
34 changes: 30 additions & 4 deletions src/logger.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,53 @@
import { AsyncLocalStorage } from "async_hooks";
import debug, { Debug } from "debug";
import { escapeMarkdown, WebhookClient } from "discord.js";
import { AutocompleteInteraction, CommandInteraction, escapeMarkdown, Message, WebhookClient } from "discord.js";
import util from "util";
import { serialiseInteraction } from "./utils";

const global = debug("bot");

const webhook = process.env.BOT_LOGGER_WEBHOOK ? new WebhookClient({ url: process.env.BOT_LOGGER_WEBHOOK }) : null;

export const asyncLocalStorage = new AsyncLocalStorage<CommandInteraction | AutocompleteInteraction | Message>();

function contextLog(log: debug.Debugger): Debug["log"] {
return function (...args: Parameters<debug.Debugger>) {
const context = asyncLocalStorage.getStore();
if (context) {
if ("commandId" in context) {
log(serialiseInteraction(context), ...args);
} else {
log(
JSON.stringify({
channel: context.channelId,
message: context.id,
guild: context.guildId,
author: context.author.id
}),
...args
);
}
} else {
log(...args);
}
};
}
function withWebhook(log: debug.Debugger): Debug["log"] {
if (webhook) {
return function (...args: Parameters<debug.Debugger>) {
log(...args);
contextLog(log)(...args);
webhook
.send({
username: log.namespace,
content: escapeMarkdown(util.format(...args)),
allowedMentions: { parse: [] }
})
.catch(error => {
log("Failed to notify webhook.", error);
contextLog(log)("Failed to notify webhook.", error);
});
};
} else {
return log;
return contextLog(log);
}
}

Expand Down

0 comments on commit 550080c

Please sign in to comment.