-
Notifications
You must be signed in to change notification settings - Fork 0
fix(hardening): TTL-based eviction for connection driver cache (#574) #582
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
b4c503c
fix(hardening): TTL-based eviction for connection driver cache
alfredorubin96 3ddc7d2
test(app): add coverage for close() and error paths in driver cache
alfredorubin96 1d89ffb
fix(test): use undefined close for no-close module test
alfredorubin96 af7e20f
fix(test): remove problematic no-close mock test
alfredorubin96 b6cc54e
test(app): direct coverage for _evictStaleEntries + simplify unref check
alfredorubin96 27743af
refactor(app): simplify closeModuleSilently — remove redundant try
alfredorubin96 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -45,8 +45,94 @@ function toConnectionTypeEnum(type: DbType): number { | |
| return type === "neo4j" ? ConnectionTypes.NEO4J : ConnectionTypes.POSTGRESQL; | ||
| } | ||
|
|
||
| /** Cache of connection modules keyed by type+uri+username+database. */ | ||
| const moduleCache = new Map<string, unknown>(); | ||
| /** | ||
| * TTL-based connection module cache. Each entry tracks last-access time | ||
| * and is evicted after `CACHE_TTL_MS` of inactivity. This prevents | ||
| * leaking driver instances on long-running servers when credentials | ||
| * rotate or connections are deleted. | ||
| */ | ||
| const CACHE_TTL_MS = 30 * 60 * 1000; // 30 minutes | ||
| const EVICTION_INTERVAL_MS = 5 * 60 * 1000; // sweep every 5 minutes | ||
|
Comment on lines
+54
to
+55
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Make the TTL configurable, not just defaulted. The issue objective calls for a configurable idle TTL, but these constants hard-code both TTL and sweep cadence. Consider reading validated server-side env/config values with these as fallbacks. Example direction+function readPositiveDurationMs(name: string, fallbackMs: number): number {
+ const value = Number(process.env[name]);
+ return Number.isFinite(value) && value > 0 ? value : fallbackMs;
+}
+
-const CACHE_TTL_MS = 30 * 60 * 1000; // 30 minutes
-const EVICTION_INTERVAL_MS = 5 * 60 * 1000; // sweep every 5 minutes
+const CACHE_TTL_MS = readPositiveDurationMs(
+ "QUERY_EXECUTOR_CACHE_TTL_MS",
+ 30 * 60 * 1000,
+);
+const EVICTION_INTERVAL_MS = readPositiveDurationMs(
+ "QUERY_EXECUTOR_EVICTION_INTERVAL_MS",
+ 5 * 60 * 1000,
+);🤖 Prompt for AI Agents |
||
|
|
||
| interface CacheEntry { | ||
| module: unknown; | ||
| lastAccessedAt: number; | ||
| } | ||
|
|
||
| const moduleCache = new Map<string, CacheEntry>(); | ||
|
|
||
| let evictionTimer: ReturnType<typeof setInterval> | null = null; | ||
|
|
||
| function startEvictionTimer() { | ||
| if (evictionTimer) return; | ||
| const timer = setInterval(() => _evictStaleEntries(), EVICTION_INTERVAL_MS); | ||
| // unref() exists on Node's Timeout but not in all runtimes. When | ||
| // available, prevents the timer from keeping the process alive. | ||
| (timer as { unref?: () => void }).unref?.(); | ||
| evictionTimer = timer; | ||
| } | ||
|
|
||
| /** Visible for testing. Sweeps the cache and evicts stale entries. */ | ||
| export function _evictStaleEntries() { | ||
| const now = Date.now(); | ||
| for (const [key, entry] of moduleCache) { | ||
| if (now - entry.lastAccessedAt > CACHE_TTL_MS) { | ||
| closeModuleSilently(entry.module); | ||
| moduleCache.delete(key); | ||
| } | ||
| } | ||
| if (moduleCache.size === 0 && evictionTimer) { | ||
| clearInterval(evictionTimer); | ||
| evictionTimer = null; | ||
| } | ||
| } | ||
|
|
||
| function closeModuleSilently(mod: unknown) { | ||
| const m = mod as { close?: () => Promise<void> }; | ||
| if (typeof m.close === "function") { | ||
| m.close().catch(() => {}); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Close and remove a cached connection module by its cache key. | ||
| * Called when a connection's credentials change or the connection is deleted. | ||
| */ | ||
| export function closeConnection( | ||
| type: DbType, | ||
| credentials: ConnectionCredentials, | ||
| ): void { | ||
| const key = getCacheKey(type, credentials); | ||
| const entry = moduleCache.get(key); | ||
| if (entry) { | ||
| closeModuleSilently(entry.module); | ||
| moduleCache.delete(key); | ||
| } | ||
|
alfredo1996 marked this conversation as resolved.
|
||
| } | ||
|
|
||
| /** | ||
| * Close all cached connection modules. Used in tests and graceful shutdown. | ||
| */ | ||
| export async function closeAllConnections(): Promise<void> { | ||
| const closePromises: Promise<void>[] = []; | ||
| for (const [, entry] of moduleCache) { | ||
| const m = entry.module as { close?: () => Promise<void> }; | ||
| if (typeof m.close === "function") { | ||
| closePromises.push(m.close().catch(() => {})); | ||
| } | ||
| } | ||
| moduleCache.clear(); | ||
| if (evictionTimer) { | ||
| clearInterval(evictionTimer); | ||
| evictionTimer = null; | ||
| } | ||
| await Promise.all(closePromises); | ||
| } | ||
|
|
||
| /** Visible for testing — returns current cache size. */ | ||
| export function _getCacheSize(): number { | ||
| return moduleCache.size; | ||
| } | ||
|
|
||
| function getCacheKey(type: DbType, credentials: ConnectionCredentials): string { | ||
| const advancedKey = [ | ||
|
|
@@ -82,22 +168,22 @@ function getOrCreateModule( | |
| credentials: ConnectionCredentials, | ||
| ): unknown { | ||
| const key = getCacheKey(type, credentials); | ||
| let connModule = moduleCache.get(key); | ||
| if (!connModule) { | ||
| const authConfig = { | ||
| uri: ensureDatabaseInUri(credentials.uri, credentials.database), | ||
| username: credentials.username, | ||
| password: credentials.password, | ||
| authType: 1, // NATIVE | ||
| }; | ||
| const advancedOptions = buildAdvancedOptions(credentials); | ||
| connModule = createConnectionModule( | ||
| type, // string type for registry lookup | ||
| authConfig, | ||
| advancedOptions, | ||
| ); | ||
| moduleCache.set(key, connModule); | ||
| const entry = moduleCache.get(key); | ||
| if (entry) { | ||
| entry.lastAccessedAt = Date.now(); | ||
| return entry.module; | ||
| } | ||
|
|
||
| const authConfig = { | ||
| uri: ensureDatabaseInUri(credentials.uri, credentials.database), | ||
| username: credentials.username, | ||
| password: credentials.password, | ||
| authType: 1, // NATIVE | ||
| }; | ||
| const advancedOptions = buildAdvancedOptions(credentials); | ||
| const connModule = createConnectionModule(type, authConfig, advancedOptions); | ||
| moduleCache.set(key, { module: connModule, lastAccessedAt: Date.now() }); | ||
|
alfredo1996 marked this conversation as resolved.
|
||
| startEvictionTimer(); | ||
| return connModule; | ||
| } | ||
|
|
||
|
|
||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.