Skip to content

Commit cd29bc3

Browse files
committed
feat: implement rate-limiting for 'started' event
1 parent 660ae1a commit cd29bc3

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

src/lib/device-cache.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { apiClient } from "./apiClient.js";
66
const CACHE_DIR = path.join(os.homedir(), ".browserstack", "combined_cache");
77
const CACHE_FILE = path.join(CACHE_DIR, "data.json");
88
const TTL_MS = 24 * 60 * 60 * 1000; // 1 day
9+
const TTL_STARTED_MS = 3 * 60 * 60 * 1000; // 3 Hours
910

1011
export enum BrowserStackProducts {
1112
LIVE = "live",
@@ -64,3 +65,26 @@ export async function getDevicesAndBrowsers(
6465

6566
return cache[type];
6667
}
68+
69+
// Rate limiter for started event (3H)
70+
export function shouldSendStartedEvent(): boolean {
71+
try {
72+
if (!fs.existsSync(CACHE_DIR)) {
73+
fs.mkdirSync(CACHE_DIR, { recursive: true });
74+
}
75+
let cache: Record<string, any> = {};
76+
if (fs.existsSync(CACHE_FILE)) {
77+
const raw = fs.readFileSync(CACHE_FILE, "utf8");
78+
cache = JSON.parse(raw || "{}");
79+
const last = parseInt(cache.lastStartedEvent, 10);
80+
if (!isNaN(last) && Date.now() - last < TTL_STARTED_MS) {
81+
return false;
82+
}
83+
}
84+
cache.lastStartedEvent = Date.now();
85+
fs.writeFileSync(CACHE_FILE, JSON.stringify(cache, null, 2), "utf8");
86+
return true;
87+
} catch (e) {
88+
return true;
89+
}
90+
}

src/oninitialized.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { trackMCP } from "./lib/instrumentation.js";
22
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3+
import { shouldSendStartedEvent } from "./lib/device-cache.js";
34

45
export function setupOnInitialized(server: McpServer, config?: any) {
56
const nodeVersion = process.versions.node;
@@ -12,6 +13,8 @@ export function setupOnInitialized(server: McpServer, config?: any) {
1213
}
1314

1415
server.server.oninitialized = () => {
15-
trackMCP("started", server.server.getClientVersion()!, undefined, config);
16+
if (shouldSendStartedEvent()) {
17+
trackMCP("started", server.server.getClientVersion()!, undefined, config);
18+
}
1619
};
1720
}

0 commit comments

Comments
 (0)