Skip to content

Commit 56f2411

Browse files
NIOcursoragent
andcommitted
fix(mattermost): cap outbound target caches to prevent unbounded growth
Add outbound cache cap regressions. Co-authored-by: Cursor <[email protected]>
1 parent 94da0a9 commit 56f2411

2 files changed

Lines changed: 93 additions & 0 deletions

File tree

‎extensions/mattermost/src/mattermost/send.test.ts‎

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -744,3 +744,83 @@ describe("sendMessageMattermost user-first resolution", () => {
744744
expect(retryCall?.[2]?.initialDelayMs).toBe(1000);
745745
});
746746
});
747+
748+
describe("sendMessageMattermost outbound cache caps", () => {
749+
function makeAccount(token: string) {
750+
return {
751+
accountId: "default",
752+
botToken: token,
753+
baseUrl: "https://mattermost.example.com",
754+
config: {},
755+
};
756+
}
757+
758+
function restoreSendMocks() {
759+
mockState.createMattermostClient.mockReturnValue({});
760+
mockState.createMattermostPost.mockResolvedValue({ id: "post-id" });
761+
mockState.createMattermostDirectChannelWithRetry.mockResolvedValue({ id: "dm-channel-id" });
762+
mockState.fetchMattermostMe.mockResolvedValue({ id: "bot-id" });
763+
}
764+
765+
beforeEach(() => {
766+
vi.clearAllMocks();
767+
restoreSendMocks();
768+
});
769+
770+
it("evicts oldest DM channel cache entries after the configured cap", async () => {
771+
const token = "token-dm-cap-test";
772+
mockState.resolveMattermostAccount.mockReturnValue(makeAccount(token));
773+
774+
const firstUserId = `dm${"0".repeat(24)}`;
775+
for (let index = 0; index < 1025; index += 1) {
776+
const userId = `dm${String(index).padStart(24, "0")}`;
777+
mockState.createMattermostDirectChannelWithRetry.mockResolvedValueOnce({
778+
id: `dm-channel-${index}`,
779+
});
780+
await sendMessageMattermost(`user:${userId}`, "hello", { cfg: TEST_CFG });
781+
}
782+
783+
expect(mockState.createMattermostDirectChannelWithRetry).toHaveBeenCalledTimes(1025);
784+
785+
vi.clearAllMocks();
786+
restoreSendMocks();
787+
mockState.resolveMattermostAccount.mockReturnValue(makeAccount(token));
788+
mockState.createMattermostDirectChannelWithRetry.mockResolvedValueOnce({
789+
id: "dm-channel-0-again",
790+
});
791+
792+
await sendMessageMattermost(`user:${firstUserId}`, "hello again", { cfg: TEST_CFG });
793+
794+
expect(mockState.createMattermostDirectChannelWithRetry).toHaveBeenCalledTimes(1);
795+
});
796+
797+
it("evicts oldest user-by-name cache entries after the configured cap", async () => {
798+
const token = "token-user-cap-test";
799+
mockState.resolveMattermostAccount.mockReturnValue(makeAccount(token));
800+
801+
const firstUsername = "user0";
802+
for (let index = 0; index < 513; index += 1) {
803+
const username = `user${index}`;
804+
mockState.fetchMattermostUserByUsername.mockResolvedValueOnce({ id: `uid-${index}` });
805+
mockState.createMattermostDirectChannelWithRetry.mockResolvedValueOnce({
806+
id: `dm-channel-${index}`,
807+
});
808+
await sendMessageMattermost(`@${username}`, "hello", { cfg: TEST_CFG });
809+
}
810+
811+
expect(mockState.fetchMattermostUserByUsername).toHaveBeenCalledTimes(513);
812+
813+
vi.clearAllMocks();
814+
restoreSendMocks();
815+
mockState.resolveMattermostAccount.mockReturnValue(makeAccount(token));
816+
mockState.fetchMattermostUserByUsername.mockResolvedValueOnce({ id: "uid-0" });
817+
mockState.createMattermostDirectChannelWithRetry.mockResolvedValueOnce({
818+
id: "dm-channel-0-again",
819+
});
820+
821+
await sendMessageMattermost(`@${firstUsername}`, "hello again", { cfg: TEST_CFG });
822+
823+
expect(mockState.fetchMattermostUserByUsername).toHaveBeenCalledTimes(1);
824+
expect(mockState.createMattermostDirectChannelWithRetry).not.toHaveBeenCalled();
825+
});
826+
});

‎extensions/mattermost/src/mattermost/send.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import {
44
type MessageReceipt,
55
type MessageReceiptPartKind,
66
} from "openclaw/plugin-sdk/channel-outbound";
7+
import { pruneMapToMaxSize } from "openclaw/plugin-sdk/collection-runtime";
78
import { resolveMarkdownTableMode } from "openclaw/plugin-sdk/markdown-table-runtime";
89
import { requireRuntimeConfig } from "openclaw/plugin-sdk/plugin-config-runtime";
910
import { isPrivateNetworkOptInEnabled } from "openclaw/plugin-sdk/ssrf-runtime";
@@ -67,6 +68,14 @@ type MattermostTarget =
6768
| { kind: "channel-name"; name: string }
6869
| { kind: "user"; id?: string; username?: string };
6970

71+
// Caps match the Slack DM channel cache precedent; bounded by distinct (baseUrl, token, target)
72+
// triples seen during process lifetime. Without a cap, long-running servers accumulate one entry
73+
// per unique recipient/channel pair forever.
74+
const MATTERMOST_BOT_USER_CACHE_MAX = 64;
75+
const MATTERMOST_USER_BY_NAME_CACHE_MAX = 512;
76+
const MATTERMOST_CHANNEL_BY_NAME_CACHE_MAX = 512;
77+
const MATTERMOST_DM_CHANNEL_CACHE_MAX = 1024;
78+
7079
const botUserCache = new Map<string, MattermostUser>();
7180
const userByNameCache = new Map<string, MattermostUser>();
7281
const channelByNameCache = new Map<string, string>();
@@ -204,6 +213,7 @@ async function resolveBotUser(
204213
const client = createMattermostClient({ baseUrl, botToken: token, allowPrivateNetwork });
205214
const user = await fetchMattermostMe(client);
206215
botUserCache.set(key, user);
216+
pruneMapToMaxSize(botUserCache, MATTERMOST_BOT_USER_CACHE_MAX);
207217
return user;
208218
}
209219

@@ -226,6 +236,7 @@ async function resolveUserIdByUsername(params: {
226236
});
227237
const user = await fetchMattermostUserByUsername(client, username);
228238
userByNameCache.set(key, user);
239+
pruneMapToMaxSize(userByNameCache, MATTERMOST_USER_BY_NAME_CACHE_MAX);
229240
return user.id;
230241
}
231242

@@ -253,6 +264,7 @@ async function resolveChannelIdByName(params: {
253264
const channel = await fetchMattermostChannelByName(client, team.id, name);
254265
if (channel?.id) {
255266
channelByNameCache.set(key, channel.id);
267+
pruneMapToMaxSize(channelByNameCache, MATTERMOST_CHANNEL_BY_NAME_CACHE_MAX);
256268
return channel.id;
257269
}
258270
} catch {
@@ -345,6 +357,7 @@ async function resolveTargetChannelId(params: ResolveTargetChannelIdParams): Pro
345357
params.onDmChannelResolution?.(resolution);
346358
const channel = await resolution;
347359
dmChannelCache.set(dmKey, channel.id);
360+
pruneMapToMaxSize(dmChannelCache, MATTERMOST_DM_CHANNEL_CACHE_MAX);
348361
return channel.id;
349362
}
350363

0 commit comments

Comments
 (0)