@@ -122,6 +122,19 @@ function shutdownSyncFetchWorker(): void {
122122
123123const CDN_CACHE_DIR = path . join ( os . homedir ( ) , ".zcode-captcha-cdn-cache" ) ;
124124const _memCdnCache = new Map ( ) ;
125+ // pe bundles rotate (pe.0xx…); every rotation would otherwise pin a fresh
126+ // multi-hundred-KB body for the process lifetime (issue #50). Insertion-ordered
127+ // FIFO — the oldest rotation ages out first; disk cache still serves re-reads.
128+ const MEM_CDN_CACHE_CAP = 16 ;
129+ function rememberCdnBody ( url , body ) {
130+ _memCdnCache . set ( url , body ) ;
131+ if ( _memCdnCache . size > MEM_CDN_CACHE_CAP ) {
132+ for ( const key of _memCdnCache . keys ( ) ) {
133+ _memCdnCache . delete ( key ) ;
134+ if ( _memCdnCache . size <= MEM_CDN_CACHE_CAP ) break ;
135+ }
136+ }
137+ }
125138let _cookieCache = { cookies : [ ] , ts : 0 } ;
126139const COOKIE_CACHE_TTL_MS = 5 * 60 * 1000 ;
127140const _DEBUG = / ^ ( 1 | t r u e | y e s ) $ / i. test (
@@ -136,8 +149,17 @@ if (proxyUrl) {
136149}
137150
138151// ── Globals shared across solves ────────────────────────────────────────────
152+ // Ring buffer: the stall detector reads only the newest entry and failure
153+ // diagnostics the last ~12 entries of the CURRENT solve — anything older is
154+ // dead weight. Unbounded it grew for the process lifetime (issue #50).
155+ const REQUEST_LOG_CAP = 256 ;
139156const _requestLog = [ ] ;
140- const solveTimes = [ ] ;
157+ function noteRequest ( entry ) {
158+ _requestLog . push ( entry ) ;
159+ if ( _requestLog . length > REQUEST_LOG_CAP ) {
160+ _requestLog . splice ( 0 , _requestLog . length - REQUEST_LOG_CAP ) ;
161+ }
162+ }
141163// Consecutive-stall tracker per pe bundle URL: the same cached pe version
142164// can stall every attempt (bad rotated VM variant / stale cache). After two
143165// stalls on one URL, evict its memory + disk cache entry so the next init
@@ -225,7 +247,7 @@ function getCachedBody(url) {
225247 const p = diskPathFor ( url ) ;
226248 if ( fs . existsSync ( p ) ) {
227249 const body = fs . readFileSync ( p ) ;
228- _memCdnCache . set ( url , body ) ;
250+ rememberCdnBody ( url , body ) ;
229251 return body ;
230252 }
231253 } catch ( _ ) { }
@@ -237,7 +259,7 @@ async function fetchAndStore(url) {
237259 const res = await fetch ( url , { headers : { "user-agent" : fp . userAgent } } ) ;
238260 const buf = Buffer . from ( await res . arrayBuffer ( ) ) ;
239261 if ( buf . length > 0 ) {
240- _memCdnCache . set ( url , buf ) ;
262+ rememberCdnBody ( url , buf ) ;
241263 try {
242264 const p = diskPathFor ( url ) ;
243265 fs . mkdirSync ( CDN_CACHE_DIR , { recursive : true } ) ;
@@ -339,7 +361,7 @@ function makeInterceptor(bypassPeCache = false) {
339361 return {
340362 async beforeAsyncRequest ( { request, window : w } ) {
341363 const url = request . url ;
342- _requestLog . push ( { at : Date . now ( ) , method : request . method , url } ) ;
364+ noteRequest ( { at : Date . now ( ) , method : request . method , url } ) ;
343365 injectRequestHeaders ( request ) ;
344366 if ( / \b a l i c d n \. c o m / i. test ( url ) ) {
345367 let body = skipPeCache ( url ) ? null : getCachedBody ( url ) ;
@@ -414,7 +436,7 @@ function makeInterceptor(bypassPeCache = false) {
414436 } ,
415437 beforeSyncRequest ( { request, window : w } ) {
416438 const url = request . url ;
417- _requestLog . push ( { at : Date . now ( ) , method : request . method , url, sync : true } ) ;
439+ noteRequest ( { at : Date . now ( ) , method : request . method , url, sync : true } ) ;
418440 injectRequestHeaders ( request ) ;
419441 let body = null ;
420442 if ( / \b a l i c d n \. c o m / i. test ( url ) ) {
@@ -2174,6 +2196,31 @@ export function removeGlobalWindowAlias(g, w) {
21742196 } catch ( _ ) { }
21752197}
21762198
2199+ // ── Heap reclaim at window-generation turnover ─────────────────────────────
2200+ // A destroyed window leaves a large dead object graph behind (SDK instances,
2201+ // pe VM, intervals, XHR buffers). JSC only hands pages back to the OS on a
2202+ // FULL synchronous collection, so without this the serve process ratchets:
2203+ // every window generation's allocation peak becomes the permanent RSS floor
2204+ // (issue #50: 2.9 days → 9.95GB resident). Throttled because pe-storm retry
2205+ // ladders destroy several windows back-to-back and Bun.gc(true) is a
2206+ // stop-the-world pass that gets heavier at large heaps.
2207+ const _gcStats = { calls : 0 , lastAt : 0 } ;
2208+ function reclaimCaptchaHeap ( ) {
2209+ try {
2210+ const gc =
2211+ ( typeof Bun !== "undefined" && typeof Bun . gc === "function" && Bun . gc ) ||
2212+ ( typeof globalThis . gc === "function" && globalThis . gc ) ; // Node --expose-gc (tests)
2213+ if ( ! gc ) return ; // plain Node runtime (Android bundle): no exposed gc, skip
2214+ const raw = Number ( process . env . CAPTCHA_GC_MIN_INTERVAL_MS ) ;
2215+ const minMs = Number . isFinite ( raw ) && raw >= 0 ? raw : 5_000 ;
2216+ const now = Date . now ( ) ;
2217+ if ( now - _gcStats . lastAt < minMs ) return ;
2218+ _gcStats . lastAt = now ;
2219+ _gcStats . calls += 1 ;
2220+ gc ( true ) ;
2221+ } catch ( _ ) { }
2222+ }
2223+
21772224function destroyDom ( win ) {
21782225 try {
21792226 const cap = win . document . getElementById ( "cap" ) ;
@@ -2192,6 +2239,7 @@ function destroyDom(win) {
21922239 // host constructor (harmless: the window registry is already cleared).
21932240 removeGuestScope ( win ) ;
21942241 try { shutdownSyncFetchWorker ( ) ; } catch ( _ ) { }
2242+ reclaimCaptchaHeap ( ) ;
21952243}
21962244
21972245function extractVerifyParam ( param ) {
@@ -2247,10 +2295,13 @@ function handleCaptchaResult(result) {
22472295// 815ms per solve) by amortizing the DOM boot + SDK script load. On by
22482296// default; opt out with CAPTCHA_WINDOW_REUSE=0 (or per-call
22492297// solveTraceless({reuseWindow:false})). The window
2250- // is discarded after `maxSolves` (memory growth), after any stall/failure
2251- // (fresh InitCaptchaV3 rolls a new pe version), or after `maxIdleMs` idle.
2298+ // is discarded after `maxSolves` (each solve leaves SDK instance graphs
2299+ // resident in the window — issue #50 measured tens of MB per solve), after
2300+ // any stall/failure (fresh InitCaptchaV3 rolls a new pe version), or after
2301+ // `maxIdleMs` idle. 8 keeps most of the amortization win while capping a
2302+ // generation's retention peak at ~1/3 of the old 25-solve default.
22522303const _reusePool = { window : null , browserFrame : null , solves : 0 , lastUsedAt : 0 } ;
2253- const REUSE_MAX_SOLVES = Number ( process . env . CAPTCHA_REUSE_MAX_SOLVES || 25 ) ;
2304+ const REUSE_MAX_SOLVES = Number ( process . env . CAPTCHA_REUSE_MAX_SOLVES || 8 ) ;
22542305const REUSE_MAX_IDLE_MS = Number ( process . env . CAPTCHA_REUSE_MAX_IDLE_MS || 120_000 ) ;
22552306
22562307function takeReusableWindow ( ) {
@@ -2448,4 +2499,17 @@ async function solveTraceless(opts) {
24482499 }
24492500}
24502501
2451- export { solveTraceless , createDom , destroyDom } ;
2502+ /** Test/debug observability into the memory guards (issue #50). */
2503+ export function __captchaMemStats ( ) {
2504+ return {
2505+ requestLogLength : _requestLog . length ,
2506+ requestLogCap : REQUEST_LOG_CAP ,
2507+ cdnCacheSize : _memCdnCache . size ,
2508+ cdnCacheCap : MEM_CDN_CACHE_CAP ,
2509+ reuseMaxSolves : REUSE_MAX_SOLVES ,
2510+ gcCalls : _gcStats . calls ,
2511+ gcLastAt : _gcStats . lastAt ,
2512+ } ;
2513+ }
2514+
2515+ export { solveTraceless , createDom , destroyDom , noteRequest , rememberCdnBody , reclaimCaptchaHeap } ;
0 commit comments