Skip to content

[SANDBOX-1788] refactor the resource cache out of the OwnerFetcher#525

Merged
metlos merged 6 commits into
codeready-toolchain:masterfrom
metlos:resource-cache
Apr 22, 2026
Merged

[SANDBOX-1788] refactor the resource cache out of the OwnerFetcher#525
metlos merged 6 commits into
codeready-toolchain:masterfrom
metlos:resource-cache

Conversation

@metlos
Copy link
Copy Markdown
Contributor

@metlos metlos commented Apr 22, 2026

refactor the resource cache out of the OwnerFetcher so that it can be used for other purposes and shared.

I intend to use the new ResourceCache in the Guardian Cockpit for the reverse of what it was used for in the OwnerFetcher.

Summary by CodeRabbit

  • Improvements

    • Resource discovery is now cached to reduce redundant API calls and speed up lookups.
    • Owner resolution now uses the cache for more consistent and efficient behavior.
  • Bug Fixes

    • Owner lookup now returns an explicit error when a resource cannot be resolved, improving failure clarity.
  • Tests

    • Added unit tests covering discovery caching, lookups across core/custom groups, error propagation, and caching behavior.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 22, 2026

Warning

Rate limit exceeded

@metlos has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 3 minutes and 54 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 3 minutes and 54 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository YAML (base), Organization UI (inherited)

Review profile: CHILL

Plan: Pro Plus

Run ID: dedd0ca3-aae8-4b89-b4f3-9d77e526c436

📥 Commits

Reviewing files that changed from the base of the PR and between 313df53 and 42ec9f3.

📒 Files selected for processing (1)
  • pkg/client/resource_cache_test.go

Walkthrough

Introduces a new ResourceCache in pkg/client that lazily caches Kubernetes discovery results and provides lookups (kind<->GVR, GR->GVK). OwnerFetcher is refactored to use this cache and the discovery logic/tests are moved/updated accordingly.

Changes

Cohort / File(s) Summary
ResourceCache Implementation
pkg/client/resource_cache.go
Adds ResourceCache type with NewResourceCache, GVRForKind, and GVKForGR; lazy-initializes cached APIResourceLists via a discovery.ServerResourcesInterface and guards init with a mutex.
ResourceCache Tests
pkg/client/resource_cache_test.go
Adds unit tests and a fakeDiscoveryClient covering core/non-core lookups, "not found" cases, parse/error propagation, and caching behavior (ensures discovery called once).
OwnerFetcher Refactor
pkg/owners/fetcher.go
Replaces internal discovery/list caching with a *client.ResourceCache field; adds NewOwnerFetcherWithCache; GetOwners now resolves GVR via ResourceCache.GVRForKind and constructs dynamic client resources from the returned GVR.
OwnerFetcher Tests Updated
pkg/owners/fetcher_test.go
Removes TestGetAPIResourceList; minor local refactors (variable declaration and whitespace) and test adjustments to match refactored fetcher behavior.

Sequence Diagram(s)

sequenceDiagram
  participant Caller
  participant OwnerFetcher
  participant ResourceCache
  participant DiscoveryClient
  participant DynamicClient
  participant KubeAPI

  Caller->>OwnerFetcher: GetOwners(kind, apiVersion)
  OwnerFetcher->>ResourceCache: GVRForKind(kind, apiVersion)
  ResourceCache->>ResourceCache: ensureResourceList()
  alt cache empty
    ResourceCache->>DiscoveryClient: ServerPreferredResources()
    DiscoveryClient-->>ResourceCache: APIResourceList[]
    ResourceCache-->>ResourceCache: cache lists
  end
  ResourceCache-->>OwnerFetcher: GroupVersionResource (gvr), found
  OwnerFetcher->>DynamicClient: Resource(gvr).Get(...)
  DynamicClient->>KubeAPI: API request for gvr
  KubeAPI-->>DynamicClient: API response (owners)
  DynamicClient-->>OwnerFetcher: owners
  OwnerFetcher-->>Caller: owners
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 30.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main refactoring: extracting ResourceCache as a standalone component from OwnerFetcher to enable reuse across other parts of the codebase.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@pkg/client/resource_cache.go`:
- Around line 93-95: The code currently returns immediately when
rc.discoveryClient.ServerPreferredResources() returns an error, dropping partial
resourceList data; change the flow to always cache the returned resourceList
into the resource cache (the same structure used by your GVRForKind/GVKForGR
lookups) even when err != nil, and only treat the error as fatal if a subsequent
lookup (GVRForKind or GVKForGR) cannot be satisfied from that cached data;
detect partial failures using discovery.IsGroupDiscoveryFailedError(err) and
propagate the original err only when a lookup actually fails, otherwise ignore
the discovery partial-error after caching the results.
- Around line 11-14: The ResourceCache lazy init is racy: guard access to
resourceLists with a sync.RWMutex field on ResourceCache and use a
double-checked pattern inside ensureResourceList() — first RLock to test
resourceLists, if nil RUnlock then Lock, check again and if still nil call
discoveryClient.ServerPreferredResources() and assign the returned slice to
resourceLists while holding the Lock; release the Lock and use RLock for
readers. Also, when ServerPreferredResources() returns (lists, err) do not
discard lists on error — assign any partial lists to resourceLists and
surface/log the error instead of returning early so GVRForKind and GVKForGR can
use the partial discovery results.

In `@pkg/owners/fetcher.go`:
- Around line 76-78: The error construction in pkg/owners/fetcher.go incorrectly
takes the addresses of ownerReference.APIVersion and ownerReference.Kind; remove
the address-of operators so the fmt.Errorf call uses the string values directly
(i.e., use ownerReference.APIVersion and ownerReference.Kind in the "GVR not
found for owner reference: %s/%s" message) so the formatted error shows the
actual APIVersion and Kind rather than pointer diagnostics.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository YAML (base), Organization UI (inherited)

Review profile: CHILL

Plan: Pro Plus

Run ID: ef49d8f2-dc27-4487-988a-22ac96a64301

📥 Commits

Reviewing files that changed from the base of the PR and between 1fd670b and f48f6ed.

📒 Files selected for processing (3)
  • pkg/client/resource_cache.go
  • pkg/client/resource_cache_test.go
  • pkg/owners/fetcher.go

Comment thread pkg/client/resource_cache.go
Comment thread pkg/client/resource_cache.go
Comment thread pkg/owners/fetcher.go
Comment thread pkg/client/resource_cache.go
@sonarqubecloud
Copy link
Copy Markdown

@metlos metlos merged commit 61a6731 into codeready-toolchain:master Apr 22, 2026
7 of 8 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants