-
Notifications
You must be signed in to change notification settings - Fork 1
Backport #106 to v1.x: bound dynamic-provider cache TTL + invalidation API (#105) #107
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
Open
heskew
wants to merge
1
commit into
v1.x
Choose a base branch
from
backport/dynamic-provider-cache-invalidation-v1x
base: v1.x
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+231
−8
Open
Changes from all commits
Commits
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
| Original file line number | Diff line number | Diff line change | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -10,7 +10,7 @@ import { OAuthResource } from './lib/resource.ts'; | |||||||||
| import { validateAndRefreshSession } from './lib/sessionValidator.ts'; | ||||||||||
| import { clearOAuthSession } from './lib/handlers.ts'; | ||||||||||
| import { HookManager } from './lib/hookManager.ts'; | ||||||||||
| import { DynamicProviderCache } from './lib/dynamicProviderCache.ts'; | ||||||||||
| import { DynamicProviderCache, DEFAULT_DYNAMIC_PROVIDER_CACHE_TTL_SECONDS } from './lib/dynamicProviderCache.ts'; | ||||||||||
| import type { Scope, OAuthPluginConfig, ProviderRegistry, OAuthHooks } from './types.ts'; | ||||||||||
|
|
||||||||||
| // Export HookManager class, OAuthResource class, and types | ||||||||||
|
|
@@ -39,6 +39,36 @@ export { getProvider } from './lib/providers/index.ts'; | |||||||||
| let pendingHooks: OAuthHooks | null = null; | ||||||||||
| let activeHookManager: HookManager | null = null; | ||||||||||
|
|
||||||||||
| // Active dynamic-provider cache for the loaded plugin instance, so consumers | ||||||||||
| // can invalidate entries when their backing config changes. Per-worker-thread: | ||||||||||
| // this references the cache in the thread that ran handleApplication. | ||||||||||
| let activeDynamicProviderCache: DynamicProviderCache | null = null; | ||||||||||
|
|
||||||||||
| /** | ||||||||||
| * Invalidate a single dynamically-resolved provider in the in-memory cache. | ||||||||||
| * Call this from application code after the backing config for `providerConfigId` | ||||||||||
| * changes (disabled, deleted, or credentials rotated) so the next request | ||||||||||
| * re-resolves it via the `onResolveProvider` hook instead of serving stale data. | ||||||||||
| * | ||||||||||
| * NOTE: the cache is per-worker-thread, so this evicts only in the thread that | ||||||||||
| * runs the call. Other threads converge within the configured TTL | ||||||||||
| * (`cacheDynamicProviders`, default {@link DEFAULT_DYNAMIC_PROVIDER_CACHE_TTL_SECONDS}s). | ||||||||||
| * For immediate cluster-wide effect, pair invalidation with a short TTL. | ||||||||||
| * | ||||||||||
| * @returns true if an entry was present and removed in this thread. | ||||||||||
| */ | ||||||||||
| export function invalidateDynamicProvider(providerConfigId: string): boolean { | ||||||||||
| return activeDynamicProviderCache?.delete(providerConfigId) ?? false; | ||||||||||
| } | ||||||||||
|
|
||||||||||
| /** | ||||||||||
| * Clear every dynamically-resolved provider from the in-memory cache (this | ||||||||||
| * worker thread only — see {@link invalidateDynamicProvider} for cross-thread notes). | ||||||||||
| */ | ||||||||||
| export function clearDynamicProviderCache(): void { | ||||||||||
| activeDynamicProviderCache?.clear(); | ||||||||||
| } | ||||||||||
|
|
||||||||||
| /** | ||||||||||
| * Register OAuth hooks programmatically | ||||||||||
| * Call this from your application code to register lifecycle hooks | ||||||||||
|
|
@@ -84,6 +114,9 @@ export async function handleApplication(scope: Scope): Promise<void> { | |||||||||
| let pluginDefaults: any = {}; // Store plugin defaults for dynamic provider resolution | ||||||||||
| const dynamicProviderCache = new DynamicProviderCache(); // TTL cache for dynamically-resolved providers | ||||||||||
|
|
||||||||||
| // Expose this thread's cache for consumer-driven invalidation | ||||||||||
| activeDynamicProviderCache = dynamicProviderCache; | ||||||||||
|
Comment on lines
+117
to
+118
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. Add the initialized cache to the set of active caches to support multiple active plugin instances in the same thread.
Suggested change
|
||||||||||
|
|
||||||||||
| // Create hookManager instance scoped to this application | ||||||||||
| const hookManager = new HookManager(logger); | ||||||||||
|
|
||||||||||
|
|
@@ -128,8 +161,10 @@ export async function handleApplication(scope: Scope): Promise<void> { | |||||||||
| // Extract plugin defaults for dynamic provider resolution | ||||||||||
| pluginDefaults = extractPluginDefaults(options); | ||||||||||
|
|
||||||||||
| // Update dynamic provider cache TTL (clears stale entries on config change) | ||||||||||
| dynamicProviderCache.updateTTL(options.cacheDynamicProviders ?? true); | ||||||||||
| // Update dynamic provider cache TTL (clears stale entries on config change). | ||||||||||
| // Defaults to a bounded TTL rather than forever so disabled/rotated | ||||||||||
| // dynamic providers stop being served without a restart (see #105). | ||||||||||
| dynamicProviderCache.updateTTL(options.cacheDynamicProviders ?? DEFAULT_DYNAMIC_PROVIDER_CACHE_TTL_SECONDS); | ||||||||||
|
|
||||||||||
| // Update the resource with new providers | ||||||||||
| if (Object.keys(providers).length === 0) { | ||||||||||
|
|
@@ -280,5 +315,8 @@ export async function handleApplication(scope: Scope): Promise<void> { | |||||||||
| // Clean up on scope close | ||||||||||
| scope.on('close', () => { | ||||||||||
| logger?.info?.('OAuth plugin shutting down'); | ||||||||||
| if (activeDynamicProviderCache === dynamicProviderCache) { | ||||||||||
| activeDynamicProviderCache = null; | ||||||||||
| } | ||||||||||
|
Comment on lines
+318
to
+320
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. |
||||||||||
| }); | ||||||||||
| } | ||||||||||
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
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 |
|---|---|---|
| @@ -0,0 +1,127 @@ | ||
| /** | ||
| * Tests for the module-level dynamic-provider cache invalidation wiring in | ||
| * src/index.ts: invalidateDynamicProvider(), clearDynamicProviderCache(), and | ||
| * the scope-close ownership guard. The DynamicProviderCache class itself is | ||
| * covered in test/lib/dynamicProviderCache.test.js — this exercises the | ||
| * handleApplication wiring around it. | ||
| * | ||
| * Everything runs in one test because the exported functions read module-level | ||
| * state (the active cache + active hookManager) that is shared across the file; | ||
| * node --test isolates each file in its own subprocess, so a single sequence | ||
| * keeps the state deterministic without cross-test contamination. | ||
| */ | ||
|
|
||
| import { describe, it } from 'node:test'; | ||
| import assert from 'node:assert/strict'; | ||
| import { | ||
| handleApplication, | ||
| registerHooks, | ||
| invalidateDynamicProvider, | ||
| clearDynamicProviderCache, | ||
| } from '../dist/index.js'; | ||
|
|
||
| function makeScope() { | ||
| const closeListeners = []; | ||
| let middleware = null; | ||
| const scope = { | ||
| logger: { info: () => {}, error: () => {}, warn: () => {}, debug: () => {} }, | ||
| options: { | ||
| _config: { | ||
| // A static provider so the plugin registers the real OAuthResource | ||
| // (not the no-providers error stub); the hook handles oac-* configs. | ||
| providers: { | ||
| github: { provider: 'github', clientId: 'gh-id', clientSecret: 'gh-secret' }, | ||
| }, | ||
| }, | ||
| getAll() { | ||
| return this._config; | ||
| }, | ||
| on() {}, | ||
| }, | ||
| server: { | ||
| // The session-validation middleware registers with no options; the MCP | ||
| // well-known handlers register with { urlPath }. Capture only the former. | ||
| http(fn, opts) { | ||
| if (!opts?.urlPath) middleware = fn; | ||
| return fn; | ||
| }, | ||
| }, | ||
| resources: { | ||
| set() {}, | ||
| }, | ||
| on(event, listener) { | ||
| if (event === 'close') closeListeners.push(listener); | ||
| }, | ||
| }; | ||
| return { scope, getMiddleware: () => middleware, closeListeners }; | ||
| } | ||
|
|
||
| /** A session whose token is far from expiry so the validator does no refresh/network. */ | ||
| function oacSession(providerConfigId) { | ||
| const future = Date.now() + 60 * 60 * 1000; | ||
| return { | ||
| oauth: { | ||
| providerConfigId, | ||
| accessToken: 'access-token', | ||
| expiresAt: future, | ||
| refreshThreshold: future, | ||
| }, | ||
| }; | ||
| } | ||
|
|
||
| describe('dynamic provider cache invalidation wiring', () => { | ||
| it('invalidate/clear evict resolved providers, and close releases the active cache', async () => { | ||
| // Before any plugin load there is no active cache → invalidate is a no-op. | ||
| assert.strictEqual(invalidateDynamicProvider('oac-1'), false); | ||
|
|
||
| let resolveCalls = 0; | ||
| registerHooks({ | ||
| async onResolveProvider(providerName) { | ||
| if (!providerName.startsWith('oac-')) return null; | ||
| resolveCalls++; | ||
| return { | ||
| provider: 'generic', | ||
| clientId: 'oac-client', | ||
| clientSecret: 'oac-secret', | ||
| authorizationUrl: 'https://idp.test/authorize', | ||
| tokenUrl: 'https://idp.test/token', | ||
| userInfoUrl: 'https://idp.test/userinfo', | ||
| scope: 'openid', | ||
| }; | ||
| }, | ||
| }); | ||
|
|
||
| const { scope, getMiddleware, closeListeners } = makeScope(); | ||
| await handleApplication(scope); | ||
| const middleware = getMiddleware(); | ||
| assert.ok(typeof middleware === 'function', 'middleware should be registered'); | ||
|
|
||
| const next = (req) => req; | ||
|
|
||
| // First request for oac-1 → cache miss → hook resolves and caches it. | ||
| await middleware({ session: oacSession('oac-1') }, next); | ||
| assert.strictEqual(resolveCalls, 1, 'hook resolves on first miss'); | ||
|
|
||
| // Second request → served from cache, hook not called again. | ||
| await middleware({ session: oacSession('oac-1') }, next); | ||
| assert.strictEqual(resolveCalls, 1, 'second request is a cache hit'); | ||
|
|
||
| // Invalidate the entry → evicts in this thread. | ||
| assert.strictEqual(invalidateDynamicProvider('oac-1'), true, 'invalidate evicts a present entry'); | ||
| assert.strictEqual(invalidateDynamicProvider('oac-1'), false, 'invalidate is false once evicted'); | ||
|
|
||
| // Next request re-resolves via the hook (cache miss after eviction). | ||
| await middleware({ session: oacSession('oac-1') }, next); | ||
| assert.strictEqual(resolveCalls, 2, 'request after invalidate re-resolves'); | ||
|
|
||
| // clearDynamicProviderCache() drops everything → next request re-resolves. | ||
| clearDynamicProviderCache(); | ||
| await middleware({ session: oacSession('oac-1') }, next); | ||
| assert.strictEqual(resolveCalls, 3, 'request after clear re-resolves'); | ||
|
|
||
| // Scope close releases the active-cache reference → invalidate becomes a no-op. | ||
| assert.strictEqual(closeListeners.length, 1, 'a close listener is registered'); | ||
| closeListeners[0](); | ||
| assert.strictEqual(invalidateDynamicProvider('oac-1'), false, 'invalidate is a no-op after close'); | ||
| }); | ||
| }); |
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
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Using a single global variable
activeDynamicProviderCachecan lead to issues if multiple instances of the plugin are loaded in the same thread (e.g., in multi-tenant environments, multiple applications, or during hot-reloads where a new scope is initialized before the old one is fully closed). In such cases, the global variable only tracks the most recently initialized instance, and closing any instance could prematurely clear the reference or leave other active caches unreachable for invalidation.Using a
Setof active caches resolves this cleanly, ensuring that invalidation and clearing are correctly propagated to all active caches in the thread.