Skip to content

Commit

Permalink
RecentMessageCache: add logging and increase TTL to 5 minutes
Browse files Browse the repository at this point in the history
  • Loading branch information
kevinlul committed Dec 16, 2023
1 parent 448e59f commit eb908a7
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,8 @@ if (process.argv.length > 2 && process.argv[2] === "--deploy-slash") {

container.registerInstance("got", createGotClient());

// TTL: 1 minute, sweep every 5 minutes
container.registerInstance<RecentMessageCache>(RecentMessageCache, new RecentMessageCache(60000, 300000));
// TTL: 5 minutes, sweep every 5 minutes
container.registerInstance<RecentMessageCache>(RecentMessageCache, new RecentMessageCache(300000, 300000));

container.register("limitRegulationRush", limitRegulationRushProvider);
container.register("limitRegulationMasterDuel", limitRegulationMasterDuelProvider);
Expand Down
6 changes: 6 additions & 0 deletions src/message-cache.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import { Message, Snowflake } from "discord.js";
import { getLogger } from "./logger";

/**
* In-memory key-value store used by SearchMessageListener to store recent <> card searches
* so that MessageDeleteListener can delete Bastion's replies
* if the searcher's message is deleted within a specified interval.
*/
export class RecentMessageCache {
#logger = getLogger("message-cache");

// This could also store the message objects
protected map: Map<Snowflake, { createdTimestamp: number; replies: Snowflake[] }> = new Map();
protected interval: NodeJS.Timeout;
Expand All @@ -30,6 +33,7 @@ export class RecentMessageCache {
return;
}
if (entry.createdTimestamp + this.ttlMilliseconds < Date.now()) {
this.#logger.info(`get expired after ${this.ttlMilliseconds} ms: ${entry}`);
this.map.delete(message);
return;
}
Expand All @@ -41,12 +45,14 @@ export class RecentMessageCache {
}

protected sweep(): void {
this.#logger.info(`sweep on ${this.map.size} entries`);
for (const [message, { createdTimestamp }] of this.map) {
if (createdTimestamp + this.ttlMilliseconds < Date.now()) {
// This is safe to do in the loop as maps have guaranteed order
this.map.delete(message);
}
}
this.#logger.info(`sweep finished leaving ${this.map.size} entries`);
}

/**
Expand Down

0 comments on commit eb908a7

Please sign in to comment.