Skip to content

Commit 514829f

Browse files
hugenshenNIO
andauthored
fix(mattermost): cap outbound and monitor caches (#101740)
Co-authored-by: NIO <[email protected]>
1 parent 1d20542 commit 514829f

4 files changed

Lines changed: 173 additions & 4 deletions

File tree

‎extensions/mattermost/src/mattermost/monitor-resources.test.ts‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,63 @@ describe("mattermost monitor resources", () => {
149149
});
150150
});
151151

152+
it.each(["channel", "user"] as const)(
153+
"bounds the %s cache without refreshing insertion order on reads",
154+
async (kind) => {
155+
const fetchResource = kind === "channel" ? fetchMattermostChannel : fetchMattermostUser;
156+
fetchResource.mockImplementation(async (_client, id: string) => ({ id }));
157+
const resources = createMattermostMonitorResources({
158+
accountId: "default",
159+
callbackUrl: "https://openclaw.test/callback",
160+
client: {} as never,
161+
logger: {},
162+
mediaMaxBytes: 1024,
163+
saveRemoteMedia: vi.fn(),
164+
mediaKindFromMime: () => "document",
165+
});
166+
const resolve = kind === "channel" ? resources.resolveChannelInfo : resources.resolveUserInfo;
167+
168+
for (let index = 0; index < 1000; index += 1) {
169+
await resolve(`${kind}-${index}`);
170+
}
171+
await resolve(`${kind}-0`);
172+
await resolve(`${kind}-1000`);
173+
await resolve(`${kind}-0`);
174+
await resolve(`${kind}-1000`);
175+
176+
const requestedIds = fetchResource.mock.calls.map((call) => call[1]);
177+
expect(requestedIds.filter((id) => id === `${kind}-0`)).toHaveLength(2);
178+
expect(requestedIds.filter((id) => id === `${kind}-1000`)).toHaveLength(1);
179+
},
180+
);
181+
182+
it.each([
183+
{ kind: "channel" as const, ttlMs: 5 * 60_000 },
184+
{ kind: "user" as const, ttlMs: 10 * 60_000 },
185+
])("expires cached $kind lookups at their TTL", async ({ kind, ttlMs }) => {
186+
const now = vi.spyOn(Date, "now").mockReturnValue(1_000);
187+
const fetchResource = kind === "channel" ? fetchMattermostChannel : fetchMattermostUser;
188+
fetchResource.mockImplementation(async (_client, id: string) => ({ id }));
189+
const resources = createMattermostMonitorResources({
190+
accountId: "default",
191+
callbackUrl: "https://openclaw.test/callback",
192+
client: {} as never,
193+
logger: {},
194+
mediaMaxBytes: 1024,
195+
saveRemoteMedia: vi.fn(),
196+
mediaKindFromMime: () => "document",
197+
});
198+
const resolve = kind === "channel" ? resources.resolveChannelInfo : resources.resolveUserInfo;
199+
200+
await resolve(`${kind}-1`);
201+
now.mockReturnValue(1_000 + ttlMs - 1);
202+
await resolve(`${kind}-1`);
203+
now.mockReturnValue(1_000 + ttlMs);
204+
await resolve(`${kind}-1`);
205+
206+
expect(fetchResource).toHaveBeenCalledTimes(2);
207+
});
208+
152209
it("does not reuse cached lookups while the process clock is invalid", async () => {
153210
fetchMattermostChannel
154211
.mockResolvedValueOnce({ id: "chan-1", name: "old" })

‎extensions/mattermost/src/mattermost/monitor-resources.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
// Mattermost plugin module implements monitor resources behavior.
22
import { formatInboundMediaUnavailableText } from "openclaw/plugin-sdk/channel-inbound";
3+
import { pruneMapToMaxSize } from "openclaw/plugin-sdk/collection-runtime";
34
import {
45
asDateTimestampMs,
56
resolveExpiresAtMsFromDurationMs,
@@ -43,6 +44,7 @@ export function formatMattermostInboundMediaText(params: {
4344

4445
const CHANNEL_CACHE_TTL_MS = 5 * 60_000;
4546
const USER_CACHE_TTL_MS = 10 * 60_000;
47+
const MONITOR_RESOURCE_CACHE_MAX_ENTRIES = 1000;
4648

4749
type SaveRemoteMedia = (params: {
4850
url: string;
@@ -98,7 +100,11 @@ export function createMattermostMonitorResources(params: {
98100
): void => {
99101
const expiresAt = resolveExpiresAtMsFromDurationMs(ttlMs, { nowMs: rawNowMs });
100102
if (expiresAt !== undefined) {
103+
// Concurrent misses can resolve the same key out of order. Reinsert on
104+
// writes so the cap keeps the most recently resolved resources.
105+
cache.delete(key);
101106
cache.set(key, { value, expiresAt });
107+
pruneMapToMaxSize(cache, MONITOR_RESOURCE_CACHE_MAX_ENTRIES);
102108
}
103109
};
104110

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

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -744,3 +744,93 @@ describe("sendMessageMattermost user-first resolution", () => {
744744
expect(retryCall?.[2]?.initialDelayMs).toBe(1000);
745745
});
746746
});
747+
748+
describe("sendMessageMattermost outbound cache bounds", () => {
749+
const baseUrl = "https://mattermost.example.com";
750+
751+
beforeEach(async () => {
752+
vi.resetModules();
753+
vi.clearAllMocks();
754+
mockState.resolveMattermostAccount.mockReturnValue({
755+
accountId: "default",
756+
botToken: "default-token",
757+
baseUrl,
758+
config: {},
759+
});
760+
mockState.createMattermostClient.mockReturnValue({});
761+
mockState.createMattermostPost.mockResolvedValue({ id: "post-id" });
762+
mockState.createMattermostDirectChannelWithRetry.mockImplementation(
763+
async (_client, userIds: string[]) => ({ id: `dm-${userIds[1]}` }),
764+
);
765+
mockState.fetchMattermostMe.mockResolvedValue({ id: "bot-id" });
766+
mockState.fetchMattermostUserByUsername.mockImplementation(
767+
async (_client, username: string) => ({
768+
id: `user-${username}`,
769+
}),
770+
);
771+
mockState.fetchMattermostUserTeams.mockResolvedValue([{ id: "team-id" }]);
772+
mockState.fetchMattermostChannelByName.mockImplementation(
773+
async (_client, _teamId: string, name: string) => ({ id: `channel-${name}` }),
774+
);
775+
({ sendMessageMattermost } = await import("./send.js"));
776+
});
777+
778+
const send = async (to: string, token: string) =>
779+
await sendMessageMattermost(to, "hello", {
780+
cfg: TEST_CFG,
781+
botToken: token,
782+
baseUrl,
783+
});
784+
785+
it("bounds DM channel entries without refreshing insertion order on reads", async () => {
786+
const token = "dm-cache-token";
787+
for (let index = 0; index < 1024; index += 1) {
788+
await send(`user:user-${index}`, token);
789+
}
790+
await send("user:user-0", token);
791+
await send("user:user-1024", token);
792+
await send("user:user-0", token);
793+
await send("user:user-1024", token);
794+
795+
expect(mockState.createMattermostDirectChannelWithRetry).toHaveBeenCalledTimes(1026);
796+
});
797+
798+
it("bounds username entries and retains the newest resolved target", async () => {
799+
const token = "username-cache-token";
800+
for (let index = 0; index < 1024; index += 1) {
801+
await send(`@name-${index}`, token);
802+
}
803+
await send("@name-0", token);
804+
await send("@name-1024", token);
805+
await send("@name-0", token);
806+
await send("@name-1024", token);
807+
808+
expect(mockState.fetchMattermostUserByUsername).toHaveBeenCalledTimes(1026);
809+
expect(mockState.createMattermostDirectChannelWithRetry).toHaveBeenCalledTimes(1026);
810+
});
811+
812+
it("bounds channel-name entries and retains the newest resolved target", async () => {
813+
const token = "channel-cache-token";
814+
for (let index = 0; index < 1024; index += 1) {
815+
await send(`#channel-${index}`, token);
816+
}
817+
await send("#channel-0", token);
818+
await send("#channel-1024", token);
819+
await send("#channel-0", token);
820+
await send("#channel-1024", token);
821+
822+
expect(mockState.fetchMattermostChannelByName).toHaveBeenCalledTimes(1026);
823+
});
824+
825+
it("bounds bot-user entries independently from DM channel entries", async () => {
826+
for (let index = 0; index < 64; index += 1) {
827+
await send(`user:user-${index}`, `bot-cache-token-${index}`);
828+
}
829+
await send("user:probe-before-overflow", "bot-cache-token-0");
830+
await send("user:user-64", "bot-cache-token-64");
831+
await send("user:probe-after-overflow", "bot-cache-token-0");
832+
await send("user:newest-probe", "bot-cache-token-64");
833+
834+
expect(mockState.fetchMattermostMe).toHaveBeenCalledTimes(66);
835+
});
836+
});

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

Lines changed: 20 additions & 4 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,11 +68,21 @@ type MattermostTarget =
6768
| { kind: "channel-name"; name: string }
6869
| { kind: "user"; id?: string; username?: string };
6970

71+
const MATTERMOST_BOT_USER_CACHE_MAX_ENTRIES = 64;
72+
const MATTERMOST_TARGET_CACHE_MAX_ENTRIES = 1024;
7073
const botUserCache = new Map<string, MattermostUser>();
7174
const userByNameCache = new Map<string, MattermostUser>();
7275
const channelByNameCache = new Map<string, string>();
7376
const dmChannelCache = new Map<string, string>();
7477

78+
function cacheOutboundEntry<K, V>(cache: Map<K, V>, key: K, value: V, maxEntries: number): void {
79+
// Cache reads stay insertion ordered; only a newly resolved value refreshes
80+
// recency before the oldest retained entry is pruned.
81+
cache.delete(key);
82+
cache.set(key, value);
83+
pruneMapToMaxSize(cache, maxEntries);
84+
}
85+
7586
const getCore = () => getMattermostRuntime();
7687

7788
function createMattermostSendReceipt(params: {
@@ -203,7 +214,7 @@ async function resolveBotUser(
203214
}
204215
const client = createMattermostClient({ baseUrl, botToken: token, allowPrivateNetwork });
205216
const user = await fetchMattermostMe(client);
206-
botUserCache.set(key, user);
217+
cacheOutboundEntry(botUserCache, key, user, MATTERMOST_BOT_USER_CACHE_MAX_ENTRIES);
207218
return user;
208219
}
209220

@@ -225,7 +236,7 @@ async function resolveUserIdByUsername(params: {
225236
allowPrivateNetwork: params.allowPrivateNetwork,
226237
});
227238
const user = await fetchMattermostUserByUsername(client, username);
228-
userByNameCache.set(key, user);
239+
cacheOutboundEntry(userByNameCache, key, user, MATTERMOST_TARGET_CACHE_MAX_ENTRIES);
229240
return user.id;
230241
}
231242

@@ -252,7 +263,12 @@ async function resolveChannelIdByName(params: {
252263
try {
253264
const channel = await fetchMattermostChannelByName(client, team.id, name);
254265
if (channel?.id) {
255-
channelByNameCache.set(key, channel.id);
266+
cacheOutboundEntry(
267+
channelByNameCache,
268+
key,
269+
channel.id,
270+
MATTERMOST_TARGET_CACHE_MAX_ENTRIES,
271+
);
256272
return channel.id;
257273
}
258274
} catch {
@@ -344,7 +360,7 @@ async function resolveTargetChannelId(params: ResolveTargetChannelIdParams): Pro
344360
});
345361
params.onDmChannelResolution?.(resolution);
346362
const channel = await resolution;
347-
dmChannelCache.set(dmKey, channel.id);
363+
cacheOutboundEntry(dmChannelCache, dmKey, channel.id, MATTERMOST_TARGET_CACHE_MAX_ENTRIES);
348364
return channel.id;
349365
}
350366

0 commit comments

Comments
 (0)