Spaces:
Runtime error
fix: reduce server memory footprint (#405)
Browse files* fix: reduce server memory footprint across session parsing, caching, and rate limiting
- Stream-parse Claude JSONL session files instead of loading entire files into memory
- Add 50MB file size cap to skip oversized session transcripts
- Add 30s TTL cache to getAllGatewaySessions() to avoid redundant disk reads per scheduler tick
- Cap rate limiter maps at 10,000 entries with oldest-first eviction
- Add request.signal abort listener to SSE route for defense-in-depth cleanup
- Add test for rate limiter maxEntries eviction behavior
* fix: address audit findings across all memory-fix files
claude-sessions.ts:
- Wrap readline loop in try/finally to ensure rl.close() on error paths
- Guard statSync in file loop to handle files deleted between readdir and stat
- Fix variable shadowing: rename inner `now` to `nowSec` to avoid confusion
- Update throttle timestamp on empty scan results (prevents repeated disk scans)
- Skip sidechain-only sessions (zero user+assistant messages)
sessions.ts:
- Decouple `active` flag from cache — compute at read time to prevent stale data
- Remove activeWithinMs from cache key to eliminate cache thrashing between
callers using different windows (Infinity vs default)
- Add invalidateSessionCache() and call it after pruneGatewaySessionsOlderThan
events/route.ts:
- Null out cleanup after first call to prevent double-invoke
- Remove unnecessary `if (request.signal)` guard (always defined on NextRequest)
rate-limit.test.ts:
- Rewrite eviction test with maxRequests=1 to actually prove eviction occurred
- Add assertion that non-evicted entries remain tracked
- src/app/api/events/route.ts +13 -2
- src/lib/__tests__/rate-limit.test.ts +25 -0
- src/lib/claude-sessions.ts +82 -69
- src/lib/rate-limit.ts +21 -0
- src/lib/sessions.ts +49 -29
|
@@ -57,11 +57,22 @@ export async function GET(request: NextRequest) {
|
|
| 57 |
},
|
| 58 |
|
| 59 |
cancel() {
|
| 60 |
-
|
| 61 |
-
|
|
|
|
|
|
|
| 62 |
},
|
| 63 |
})
|
| 64 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
return new Response(stream, {
|
| 66 |
headers: {
|
| 67 |
'Content-Type': 'text/event-stream',
|
|
|
|
| 57 |
},
|
| 58 |
|
| 59 |
cancel() {
|
| 60 |
+
if (cleanup) {
|
| 61 |
+
cleanup()
|
| 62 |
+
cleanup = null
|
| 63 |
+
}
|
| 64 |
},
|
| 65 |
})
|
| 66 |
|
| 67 |
+
// Defense-in-depth: if the request is aborted (proxy timeout, network drop)
|
| 68 |
+
// ensure we clean up the event listener even if cancel() doesn't fire.
|
| 69 |
+
request.signal.addEventListener('abort', () => {
|
| 70 |
+
if (cleanup) {
|
| 71 |
+
cleanup()
|
| 72 |
+
cleanup = null
|
| 73 |
+
}
|
| 74 |
+
}, { once: true })
|
| 75 |
+
|
| 76 |
return new Response(stream, {
|
| 77 |
headers: {
|
| 78 |
'Content-Type': 'text/event-stream',
|
|
@@ -72,4 +72,29 @@ describe('createRateLimiter', () => {
|
|
| 72 |
// Second IP now blocked
|
| 73 |
expect(limiter(makeRequest('10.0.0.2'))).not.toBeNull()
|
| 74 |
})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
})
|
|
|
|
| 72 |
// Second IP now blocked
|
| 73 |
expect(limiter(makeRequest('10.0.0.2'))).not.toBeNull()
|
| 74 |
})
|
| 75 |
+
|
| 76 |
+
it('evicts oldest entry when maxEntries is reached', () => {
|
| 77 |
+
const limiter = createRateLimiter({ windowMs: 60_000, maxRequests: 1, maxEntries: 3 })
|
| 78 |
+
|
| 79 |
+
// Fill to capacity and exhaust 10.0.0.1's quota
|
| 80 |
+
limiter(makeRequest('10.0.0.1'))
|
| 81 |
+
vi.advanceTimersByTime(1)
|
| 82 |
+
expect(limiter(makeRequest('10.0.0.1'))).not.toBeNull() // blocked: quota consumed
|
| 83 |
+
|
| 84 |
+
limiter(makeRequest('10.0.0.2'))
|
| 85 |
+
vi.advanceTimersByTime(1)
|
| 86 |
+
limiter(makeRequest('10.0.0.3'))
|
| 87 |
+
vi.advanceTimersByTime(1)
|
| 88 |
+
|
| 89 |
+
// Store has 3 entries (A blocked, B, C). Adding D evicts A (oldest resetAt)
|
| 90 |
+
limiter(makeRequest('10.0.0.4'))
|
| 91 |
+
|
| 92 |
+
// 10.0.0.1 was evicted — counter is gone, this is allowed (fresh entry)
|
| 93 |
+
expect(limiter(makeRequest('10.0.0.1'))).toBeNull()
|
| 94 |
+
// Now 10.0.0.1 is back at count=1 and blocked
|
| 95 |
+
expect(limiter(makeRequest('10.0.0.1'))).not.toBeNull()
|
| 96 |
+
|
| 97 |
+
// 10.0.0.3 should still be tracked (not evicted — it had the newest resetAt)
|
| 98 |
+
expect(limiter(makeRequest('10.0.0.3'))).not.toBeNull()
|
| 99 |
+
})
|
| 100 |
})
|
|
@@ -12,12 +12,16 @@
|
|
| 12 |
* - Activity status (active if last message < 5 minutes ago)
|
| 13 |
*/
|
| 14 |
|
| 15 |
-
import {
|
|
|
|
| 16 |
import { join } from 'path'
|
| 17 |
import { config } from './config'
|
| 18 |
import { getDatabase } from './db'
|
| 19 |
import { logger } from './logger'
|
| 20 |
|
|
|
|
|
|
|
|
|
|
| 21 |
// Rough per-token pricing (USD) for cost estimation
|
| 22 |
const MODEL_PRICING: Record<string, { input: number; output: number }> = {
|
| 23 |
'claude-opus-4-6': { input: 15 / 1_000_000, output: 75 / 1_000_000 },
|
|
@@ -78,12 +82,12 @@ function clampTimestamp(ms: number): number {
|
|
| 78 |
return ms
|
| 79 |
}
|
| 80 |
|
| 81 |
-
function parseSessionFile(filePath: string, projectSlug: string, fileMtimeMs: number): SessionStats | null {
|
| 82 |
try {
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
|
| 88 |
let sessionId: string | null = null
|
| 89 |
let model: string | null = null
|
|
@@ -99,77 +103,80 @@ function parseSessionFile(filePath: string, projectSlug: string, fileMtimeMs: nu
|
|
| 99 |
let firstMessageAt: string | null = null
|
| 100 |
let lastMessageAt: string | null = null
|
| 101 |
let lastUserPrompt: string | null = null
|
|
|
|
| 102 |
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
} catch {
|
| 108 |
-
continue
|
| 109 |
-
}
|
| 110 |
-
|
| 111 |
-
// Extract session ID from first entry that has one
|
| 112 |
-
if (!sessionId && entry.sessionId) {
|
| 113 |
-
sessionId = entry.sessionId
|
| 114 |
-
}
|
| 115 |
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
}
|
| 125 |
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
lastMessageAt = entry.timestamp
|
| 130 |
-
}
|
| 131 |
|
| 132 |
-
|
| 133 |
-
|
|
|
|
| 134 |
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
const msg = entry.message
|
| 139 |
-
if (typeof msg.content === 'string' && msg.content.length > 0) {
|
| 140 |
-
lastUserPrompt = msg.content.slice(0, 500)
|
| 141 |
}
|
| 142 |
-
}
|
| 143 |
|
| 144 |
-
|
| 145 |
-
assistantMessages++
|
| 146 |
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
|
|
|
|
|
|
|
|
|
| 150 |
}
|
| 151 |
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
outputTokens += (usage.output_tokens || 0)
|
| 159 |
-
}
|
| 160 |
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 165 |
}
|
| 166 |
}
|
| 167 |
}
|
|
|
|
|
|
|
| 168 |
}
|
| 169 |
|
| 170 |
-
if (!sessionId) return null
|
| 171 |
|
| 172 |
-
// Estimate cost (cache reads = 10% of input, cache creation = 125% of input)
|
| 173 |
const pricing = (model && MODEL_PRICING[model]) || DEFAULT_PRICING
|
| 174 |
const estimatedCost =
|
| 175 |
inputTokens * pricing.input +
|
|
@@ -184,7 +191,6 @@ function parseSessionFile(filePath: string, projectSlug: string, fileMtimeMs: nu
|
|
| 184 |
const effectiveFirstMs = parsedFirstMs || mtimeMs
|
| 185 |
const isActive = effectiveLastMs > 0 && (Date.now() - effectiveLastMs) < ACTIVE_THRESHOLD_MS
|
| 186 |
|
| 187 |
-
// Store total input tokens (including cache) for display
|
| 188 |
const totalInputTokens = inputTokens + cacheReadTokens + cacheCreationTokens
|
| 189 |
|
| 190 |
return {
|
|
@@ -211,7 +217,7 @@ function parseSessionFile(filePath: string, projectSlug: string, fileMtimeMs: nu
|
|
| 211 |
}
|
| 212 |
|
| 213 |
/** Scan all Claude Code projects and discover sessions */
|
| 214 |
-
export function scanClaudeSessions(): SessionStats[] {
|
| 215 |
const claudeHome = config.claudeHome
|
| 216 |
if (!claudeHome) return []
|
| 217 |
|
|
@@ -236,7 +242,6 @@ export function scanClaudeSessions(): SessionStats[] {
|
|
| 236 |
}
|
| 237 |
if (!stat.isDirectory()) continue
|
| 238 |
|
| 239 |
-
// Find JSONL files in this project
|
| 240 |
let files: string[]
|
| 241 |
try {
|
| 242 |
files = readdirSync(projectDir).filter(f => f.endsWith('.jsonl'))
|
|
@@ -246,7 +251,13 @@ export function scanClaudeSessions(): SessionStats[] {
|
|
| 246 |
|
| 247 |
for (const file of files) {
|
| 248 |
const filePath = join(projectDir, file)
|
| 249 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 250 |
if (parsed) sessions.push(parsed)
|
| 251 |
}
|
| 252 |
}
|
|
@@ -261,18 +272,20 @@ const SYNC_THROTTLE_MS = 30_000
|
|
| 261 |
|
| 262 |
/** Scan and upsert sessions into the database (throttled to avoid repeated disk scans) */
|
| 263 |
export async function syncClaudeSessions(force = false): Promise<{ ok: boolean; message: string }> {
|
| 264 |
-
const
|
| 265 |
-
if (!force && lastSyncAt > 0 && (
|
| 266 |
return lastSyncResult
|
| 267 |
}
|
| 268 |
try {
|
| 269 |
-
const sessions = scanClaudeSessions()
|
| 270 |
if (sessions.length === 0) {
|
| 271 |
-
|
|
|
|
|
|
|
| 272 |
}
|
| 273 |
|
| 274 |
const db = getDatabase()
|
| 275 |
-
const
|
| 276 |
|
| 277 |
const upsert = db.prepare(`
|
| 278 |
INSERT INTO claude_sessions (
|
|
@@ -309,7 +322,7 @@ export async function syncClaudeSessions(force = false): Promise<{ ok: boolean;
|
|
| 309 |
s.userMessages, s.assistantMessages, s.toolUses,
|
| 310 |
s.inputTokens, s.outputTokens, s.estimatedCost,
|
| 311 |
s.firstMessageAt, s.lastMessageAt, s.lastUserPrompt,
|
| 312 |
-
s.isActive ? 1 : 0,
|
| 313 |
)
|
| 314 |
upserted++
|
| 315 |
}
|
|
|
|
| 12 |
* - Activity status (active if last message < 5 minutes ago)
|
| 13 |
*/
|
| 14 |
|
| 15 |
+
import { createReadStream, readdirSync, statSync } from 'fs'
|
| 16 |
+
import { createInterface } from 'readline'
|
| 17 |
import { join } from 'path'
|
| 18 |
import { config } from './config'
|
| 19 |
import { getDatabase } from './db'
|
| 20 |
import { logger } from './logger'
|
| 21 |
|
| 22 |
+
// Skip JSONL files larger than this to avoid excessive I/O
|
| 23 |
+
const MAX_SESSION_FILE_BYTES = 50 * 1024 * 1024 // 50 MB
|
| 24 |
+
|
| 25 |
// Rough per-token pricing (USD) for cost estimation
|
| 26 |
const MODEL_PRICING: Record<string, { input: number; output: number }> = {
|
| 27 |
'claude-opus-4-6': { input: 15 / 1_000_000, output: 75 / 1_000_000 },
|
|
|
|
| 82 |
return ms
|
| 83 |
}
|
| 84 |
|
| 85 |
+
async function parseSessionFile(filePath: string, projectSlug: string, fileMtimeMs: number, fileSizeBytes: number): Promise<SessionStats | null> {
|
| 86 |
try {
|
| 87 |
+
if (fileSizeBytes > MAX_SESSION_FILE_BYTES) {
|
| 88 |
+
logger.warn({ filePath, fileSizeBytes }, 'Skipping oversized Claude session file')
|
| 89 |
+
return null
|
| 90 |
+
}
|
| 91 |
|
| 92 |
let sessionId: string | null = null
|
| 93 |
let model: string | null = null
|
|
|
|
| 103 |
let firstMessageAt: string | null = null
|
| 104 |
let lastMessageAt: string | null = null
|
| 105 |
let lastUserPrompt: string | null = null
|
| 106 |
+
let hasLines = false
|
| 107 |
|
| 108 |
+
const rl = createInterface({
|
| 109 |
+
input: createReadStream(filePath, { encoding: 'utf-8' }),
|
| 110 |
+
crlfDelay: Infinity,
|
| 111 |
+
})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
|
| 113 |
+
try {
|
| 114 |
+
for await (const line of rl) {
|
| 115 |
+
if (!line) continue
|
| 116 |
+
hasLines = true
|
| 117 |
+
|
| 118 |
+
let entry: JSONLEntry
|
| 119 |
+
try {
|
| 120 |
+
entry = JSON.parse(line)
|
| 121 |
+
} catch {
|
| 122 |
+
continue
|
| 123 |
+
}
|
| 124 |
|
| 125 |
+
if (!sessionId && entry.sessionId) {
|
| 126 |
+
sessionId = entry.sessionId
|
| 127 |
+
}
|
|
|
|
| 128 |
|
| 129 |
+
if (!gitBranch && entry.gitBranch) {
|
| 130 |
+
gitBranch = entry.gitBranch
|
| 131 |
+
}
|
|
|
|
|
|
|
| 132 |
|
| 133 |
+
if (!projectPath && entry.cwd) {
|
| 134 |
+
projectPath = entry.cwd
|
| 135 |
+
}
|
| 136 |
|
| 137 |
+
if (entry.timestamp) {
|
| 138 |
+
if (!firstMessageAt) firstMessageAt = entry.timestamp
|
| 139 |
+
lastMessageAt = entry.timestamp
|
|
|
|
|
|
|
|
|
|
| 140 |
}
|
|
|
|
| 141 |
|
| 142 |
+
if (entry.isSidechain) continue
|
|
|
|
| 143 |
|
| 144 |
+
if (entry.type === 'user' && entry.message) {
|
| 145 |
+
userMessages++
|
| 146 |
+
const msg = entry.message
|
| 147 |
+
if (typeof msg.content === 'string' && msg.content.length > 0) {
|
| 148 |
+
lastUserPrompt = msg.content.slice(0, 500)
|
| 149 |
+
}
|
| 150 |
}
|
| 151 |
|
| 152 |
+
if (entry.type === 'assistant' && entry.message) {
|
| 153 |
+
assistantMessages++
|
| 154 |
+
|
| 155 |
+
if (entry.message.model) {
|
| 156 |
+
model = entry.message.model
|
| 157 |
+
}
|
|
|
|
|
|
|
| 158 |
|
| 159 |
+
const usage = entry.message.usage
|
| 160 |
+
if (usage) {
|
| 161 |
+
inputTokens += (usage.input_tokens || 0)
|
| 162 |
+
cacheReadTokens += (usage.cache_read_input_tokens || 0)
|
| 163 |
+
cacheCreationTokens += (usage.cache_creation_input_tokens || 0)
|
| 164 |
+
outputTokens += (usage.output_tokens || 0)
|
| 165 |
+
}
|
| 166 |
+
|
| 167 |
+
if (Array.isArray(entry.message.content)) {
|
| 168 |
+
for (const block of entry.message.content) {
|
| 169 |
+
if (block.type === 'tool_use') toolUses++
|
| 170 |
+
}
|
| 171 |
}
|
| 172 |
}
|
| 173 |
}
|
| 174 |
+
} finally {
|
| 175 |
+
rl.close()
|
| 176 |
}
|
| 177 |
|
| 178 |
+
if (!hasLines || !sessionId || (userMessages === 0 && assistantMessages === 0)) return null
|
| 179 |
|
|
|
|
| 180 |
const pricing = (model && MODEL_PRICING[model]) || DEFAULT_PRICING
|
| 181 |
const estimatedCost =
|
| 182 |
inputTokens * pricing.input +
|
|
|
|
| 191 |
const effectiveFirstMs = parsedFirstMs || mtimeMs
|
| 192 |
const isActive = effectiveLastMs > 0 && (Date.now() - effectiveLastMs) < ACTIVE_THRESHOLD_MS
|
| 193 |
|
|
|
|
| 194 |
const totalInputTokens = inputTokens + cacheReadTokens + cacheCreationTokens
|
| 195 |
|
| 196 |
return {
|
|
|
|
| 217 |
}
|
| 218 |
|
| 219 |
/** Scan all Claude Code projects and discover sessions */
|
| 220 |
+
export async function scanClaudeSessions(): Promise<SessionStats[]> {
|
| 221 |
const claudeHome = config.claudeHome
|
| 222 |
if (!claudeHome) return []
|
| 223 |
|
|
|
|
| 242 |
}
|
| 243 |
if (!stat.isDirectory()) continue
|
| 244 |
|
|
|
|
| 245 |
let files: string[]
|
| 246 |
try {
|
| 247 |
files = readdirSync(projectDir).filter(f => f.endsWith('.jsonl'))
|
|
|
|
| 251 |
|
| 252 |
for (const file of files) {
|
| 253 |
const filePath = join(projectDir, file)
|
| 254 |
+
let fileStat
|
| 255 |
+
try {
|
| 256 |
+
fileStat = statSync(filePath)
|
| 257 |
+
} catch {
|
| 258 |
+
continue // file disappeared between readdir and stat
|
| 259 |
+
}
|
| 260 |
+
const parsed = await parseSessionFile(filePath, projectSlug, fileStat.mtimeMs, fileStat.size)
|
| 261 |
if (parsed) sessions.push(parsed)
|
| 262 |
}
|
| 263 |
}
|
|
|
|
| 272 |
|
| 273 |
/** Scan and upsert sessions into the database (throttled to avoid repeated disk scans) */
|
| 274 |
export async function syncClaudeSessions(force = false): Promise<{ ok: boolean; message: string }> {
|
| 275 |
+
const nowMs = Date.now()
|
| 276 |
+
if (!force && lastSyncAt > 0 && (nowMs - lastSyncAt) < SYNC_THROTTLE_MS) {
|
| 277 |
return lastSyncResult
|
| 278 |
}
|
| 279 |
try {
|
| 280 |
+
const sessions = await scanClaudeSessions()
|
| 281 |
if (sessions.length === 0) {
|
| 282 |
+
lastSyncAt = Date.now()
|
| 283 |
+
lastSyncResult = { ok: true, message: 'No Claude sessions found' }
|
| 284 |
+
return lastSyncResult
|
| 285 |
}
|
| 286 |
|
| 287 |
const db = getDatabase()
|
| 288 |
+
const nowSec = Math.floor(Date.now() / 1000)
|
| 289 |
|
| 290 |
const upsert = db.prepare(`
|
| 291 |
INSERT INTO claude_sessions (
|
|
|
|
| 322 |
s.userMessages, s.assistantMessages, s.toolUses,
|
| 323 |
s.inputTokens, s.outputTokens, s.estimatedCost,
|
| 324 |
s.firstMessageAt, s.lastMessageAt, s.lastUserPrompt,
|
| 325 |
+
s.isActive ? 1 : 0, nowSec, nowSec,
|
| 326 |
)
|
| 327 |
upserted++
|
| 328 |
}
|
|
@@ -12,6 +12,23 @@ interface RateLimiterOptions {
|
|
| 12 |
message?: string
|
| 13 |
/** If true, MC_DISABLE_RATE_LIMIT will not bypass this limiter */
|
| 14 |
critical?: boolean
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
}
|
| 16 |
|
| 17 |
// Trusted proxy IPs (comma-separated). Only parse XFF when behind known proxies.
|
|
@@ -41,6 +58,7 @@ export function extractClientIp(request: Request): string {
|
|
| 41 |
|
| 42 |
export function createRateLimiter(options: RateLimiterOptions) {
|
| 43 |
const store = new Map<string, RateLimitEntry>()
|
|
|
|
| 44 |
|
| 45 |
// Periodic cleanup every 60s
|
| 46 |
const cleanupInterval = setInterval(() => {
|
|
@@ -60,6 +78,7 @@ export function createRateLimiter(options: RateLimiterOptions) {
|
|
| 60 |
const entry = store.get(ip)
|
| 61 |
|
| 62 |
if (!entry || now > entry.resetAt) {
|
|
|
|
| 63 |
store.set(ip, { count: 1, resetAt: now + options.windowMs })
|
| 64 |
return null
|
| 65 |
}
|
|
@@ -113,6 +132,7 @@ export const heavyLimiter = createRateLimiter({
|
|
| 113 |
*/
|
| 114 |
export function createAgentRateLimiter(options: RateLimiterOptions) {
|
| 115 |
const store = new Map<string, RateLimitEntry>()
|
|
|
|
| 116 |
|
| 117 |
const cleanupInterval = setInterval(() => {
|
| 118 |
const now = Date.now()
|
|
@@ -131,6 +151,7 @@ export function createAgentRateLimiter(options: RateLimiterOptions) {
|
|
| 131 |
const entry = store.get(key)
|
| 132 |
|
| 133 |
if (!entry || now > entry.resetAt) {
|
|
|
|
| 134 |
store.set(key, { count: 1, resetAt: now + options.windowMs })
|
| 135 |
return null
|
| 136 |
}
|
|
|
|
| 12 |
message?: string
|
| 13 |
/** If true, MC_DISABLE_RATE_LIMIT will not bypass this limiter */
|
| 14 |
critical?: boolean
|
| 15 |
+
/** Max entries in the backing map before evicting oldest (default: 10_000) */
|
| 16 |
+
maxEntries?: number
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
const DEFAULT_MAX_ENTRIES = 10_000
|
| 20 |
+
|
| 21 |
+
/** Evict the entry with the earliest resetAt when at capacity */
|
| 22 |
+
function evictOldest(store: Map<string, RateLimitEntry>) {
|
| 23 |
+
let oldestKey: string | null = null
|
| 24 |
+
let oldestReset = Infinity
|
| 25 |
+
for (const [key, entry] of store) {
|
| 26 |
+
if (entry.resetAt < oldestReset) {
|
| 27 |
+
oldestReset = entry.resetAt
|
| 28 |
+
oldestKey = key
|
| 29 |
+
}
|
| 30 |
+
}
|
| 31 |
+
if (oldestKey) store.delete(oldestKey)
|
| 32 |
}
|
| 33 |
|
| 34 |
// Trusted proxy IPs (comma-separated). Only parse XFF when behind known proxies.
|
|
|
|
| 58 |
|
| 59 |
export function createRateLimiter(options: RateLimiterOptions) {
|
| 60 |
const store = new Map<string, RateLimitEntry>()
|
| 61 |
+
const maxEntries = options.maxEntries ?? DEFAULT_MAX_ENTRIES
|
| 62 |
|
| 63 |
// Periodic cleanup every 60s
|
| 64 |
const cleanupInterval = setInterval(() => {
|
|
|
|
| 78 |
const entry = store.get(ip)
|
| 79 |
|
| 80 |
if (!entry || now > entry.resetAt) {
|
| 81 |
+
if (!entry && store.size >= maxEntries) evictOldest(store)
|
| 82 |
store.set(ip, { count: 1, resetAt: now + options.windowMs })
|
| 83 |
return null
|
| 84 |
}
|
|
|
|
| 132 |
*/
|
| 133 |
export function createAgentRateLimiter(options: RateLimiterOptions) {
|
| 134 |
const store = new Map<string, RateLimitEntry>()
|
| 135 |
+
const maxEntries = options.maxEntries ?? DEFAULT_MAX_ENTRIES
|
| 136 |
|
| 137 |
const cleanupInterval = setInterval(() => {
|
| 138 |
const now = Date.now()
|
|
|
|
| 151 |
const entry = store.get(key)
|
| 152 |
|
| 153 |
if (!entry || now > entry.resetAt) {
|
| 154 |
+
if (!entry && store.size >= maxEntries) evictOldest(store)
|
| 155 |
store.set(key, { count: 1, resetAt: now + options.windowMs })
|
| 156 |
return null
|
| 157 |
}
|
|
@@ -45,6 +45,17 @@ function getGatewaySessionStoreFiles(): string[] {
|
|
| 45 |
return files
|
| 46 |
}
|
| 47 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
/**
|
| 49 |
* Read all sessions from OpenClaw agent session stores on disk.
|
| 50 |
*
|
|
@@ -54,41 +65,49 @@ function getGatewaySessionStoreFiles(): string[] {
|
|
| 54 |
* Each file is a JSON object keyed by session key (e.g. "agent:<agent>:main")
|
| 55 |
* with session metadata as values.
|
| 56 |
*/
|
| 57 |
-
export function getAllGatewaySessions(activeWithinMs = 60 * 60 * 1000): GatewaySession[] {
|
| 58 |
-
const sessions: GatewaySession[] = []
|
| 59 |
const now = Date.now()
|
| 60 |
-
for (const sessionsFile of getGatewaySessionStoreFiles()) {
|
| 61 |
-
const agentName = path.basename(path.dirname(path.dirname(sessionsFile)))
|
| 62 |
-
try {
|
| 63 |
-
const raw = fs.readFileSync(sessionsFile, 'utf-8')
|
| 64 |
-
const data = JSON.parse(raw)
|
| 65 |
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
}
|
| 84 |
-
} catch {
|
| 85 |
-
// Skip agents without valid session files
|
| 86 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
}
|
| 88 |
|
| 89 |
-
//
|
| 90 |
-
|
| 91 |
-
return sessions
|
| 92 |
}
|
| 93 |
|
| 94 |
export function countStaleGatewaySessions(retentionDays: number): number {
|
|
@@ -146,6 +165,7 @@ export function pruneGatewaySessionsOlderThan(retentionDays: number): { deleted:
|
|
| 146 |
}
|
| 147 |
}
|
| 148 |
|
|
|
|
| 149 |
return { deleted, filesTouched }
|
| 150 |
}
|
| 151 |
|
|
|
|
| 45 |
return files
|
| 46 |
}
|
| 47 |
|
| 48 |
+
// TTL cache to avoid re-reading session files multiple times per scheduler tick.
|
| 49 |
+
// Stores sessions without the `active` flag so the cache is independent of activeWithinMs.
|
| 50 |
+
type RawSession = Omit<GatewaySession, 'active'>
|
| 51 |
+
let _sessionCache: { data: RawSession[]; ts: number } | null = null
|
| 52 |
+
const SESSION_CACHE_TTL_MS = 30_000
|
| 53 |
+
|
| 54 |
+
/** Invalidate the session cache (e.g. after pruning). */
|
| 55 |
+
export function invalidateSessionCache(): void {
|
| 56 |
+
_sessionCache = null
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
/**
|
| 60 |
* Read all sessions from OpenClaw agent session stores on disk.
|
| 61 |
*
|
|
|
|
| 65 |
* Each file is a JSON object keyed by session key (e.g. "agent:<agent>:main")
|
| 66 |
* with session metadata as values.
|
| 67 |
*/
|
| 68 |
+
export function getAllGatewaySessions(activeWithinMs = 60 * 60 * 1000, force = false): GatewaySession[] {
|
|
|
|
| 69 |
const now = Date.now()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
|
| 71 |
+
let raw: RawSession[]
|
| 72 |
+
if (!force && _sessionCache && (now - _sessionCache.ts) < SESSION_CACHE_TTL_MS) {
|
| 73 |
+
raw = _sessionCache.data
|
| 74 |
+
} else {
|
| 75 |
+
const sessions: RawSession[] = []
|
| 76 |
+
for (const sessionsFile of getGatewaySessionStoreFiles()) {
|
| 77 |
+
const agentName = path.basename(path.dirname(path.dirname(sessionsFile)))
|
| 78 |
+
try {
|
| 79 |
+
const fileContent = fs.readFileSync(sessionsFile, 'utf-8')
|
| 80 |
+
const data = JSON.parse(fileContent)
|
| 81 |
+
|
| 82 |
+
for (const [key, entry] of Object.entries(data)) {
|
| 83 |
+
const s = entry as Record<string, any>
|
| 84 |
+
const updatedAt = s.updatedAt || 0
|
| 85 |
+
sessions.push({
|
| 86 |
+
key,
|
| 87 |
+
agent: agentName,
|
| 88 |
+
sessionId: s.sessionId || '',
|
| 89 |
+
updatedAt,
|
| 90 |
+
chatType: s.chatType || 'unknown',
|
| 91 |
+
channel: s.deliveryContext?.channel || s.lastChannel || s.channel || '',
|
| 92 |
+
model: typeof s.model === 'object' && s.model?.primary ? String(s.model.primary) : String(s.model || ''),
|
| 93 |
+
totalTokens: s.totalTokens || 0,
|
| 94 |
+
inputTokens: s.inputTokens || 0,
|
| 95 |
+
outputTokens: s.outputTokens || 0,
|
| 96 |
+
contextTokens: s.contextTokens || 0,
|
| 97 |
+
})
|
| 98 |
+
}
|
| 99 |
+
} catch {
|
| 100 |
+
// Skip agents without valid session files
|
| 101 |
}
|
|
|
|
|
|
|
| 102 |
}
|
| 103 |
+
|
| 104 |
+
sessions.sort((a, b) => b.updatedAt - a.updatedAt)
|
| 105 |
+
_sessionCache = { data: sessions, ts: Date.now() }
|
| 106 |
+
raw = sessions
|
| 107 |
}
|
| 108 |
|
| 109 |
+
// Compute `active` at read time so it's always fresh regardless of cache age
|
| 110 |
+
return raw.map(s => ({ ...s, active: (now - s.updatedAt) < activeWithinMs }))
|
|
|
|
| 111 |
}
|
| 112 |
|
| 113 |
export function countStaleGatewaySessions(retentionDays: number): number {
|
|
|
|
| 165 |
}
|
| 166 |
}
|
| 167 |
|
| 168 |
+
if (filesTouched > 0) invalidateSessionCache()
|
| 169 |
return { deleted, filesTouched }
|
| 170 |
}
|
| 171 |
|