[4.x] Make globalCache always use the central connection with database cache stores#1462
Conversation
📝 WalkthroughWalkthroughAdds a central-connection override for database-backed global cache stores and updates related bootstrapper docs and test datasets to use ChangesDatabase Cache Connection Centralization
🎯 3 (Moderate) | ⏱️ ~20 minutes
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Comment |
globalCache always use the central connection
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## master #1462 +/- ##
============================================
+ Coverage 86.03% 86.05% +0.02%
Complexity 1178 1178
============================================
Files 185 185
Lines 3436 3441 +5
============================================
+ Hits 2956 2961 +5
Misses 480 480 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
|
@coderabbitai full review |
✅ Actions performedFull review triggered. |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@src/TenancyServiceProvider.php`:
- Around line 127-140: The loop eagerly instantiates every database cache store
by calling $manager->store($name)->getStore(), causing unnecessary connections;
instead, avoid materialization by registering a lazy decorator for each
configured database store using $manager->extend($name, ...), and inside that
extender wrap/return the real store and call setConnection(...) and
setLockConnection(...) on the DatabaseStore using $store['connection'] ??
$centralConnection and $store['lock_connection'] ?? $store['connection'] ??
$centralConnection so the central-connection fallback is applied only when a
store is actually resolved; reference $manager->extend, DatabaseStore,
setConnection, setLockConnection, $store and $centralConnection to locate and
implement the change.
🪄 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: Organization UI
Review profile: ASSERTIVE
Plan: Pro
Run ID: e78e02ab-9f44-436e-9714-85a7f2f2445b
📒 Files selected for processing (3)
src/TenancyServiceProvider.phptests/CachedTenantResolverTest.phptests/GlobalCacheTest.php
|
@coderabbitai full review |
✅ Actions performedFull review triggered. |
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@tests/CachedTenantResolverTest.php`:
- Line 168: The dataset leaves TenancyServiceProvider::$adjustCacheManagerUsing
mutated by the DatabaseTenancyBootstrapper case so the subsequent
CacheTenancyBootstrapper case inherits the callback; update the test fixture in
CachedTenantResolverTest (in the beforeEach/afterEach surrounding the dataset)
to explicitly reset TenancyServiceProvider::$adjustCacheManagerUsing to its
known default (e.g., null or the original default closure) in addition to the
existing Tenant::$extraCustomColumns reset so each case exercises
makeDatabaseCacheStoresCentral() independently.
In `@tests/GlobalCacheTest.php`:
- Line 168: Tests leave TenancyServiceProvider::$adjustCacheManagerUsing set by
DatabaseTenancyBootstrapper, causing stale static state that affects later
CacheTenancyBootstrapper assertions; reset the static between runs by explicitly
assigning the class default (e.g.
TenancyServiceProvider::$adjustCacheManagerUsing = null or the original default)
in the test suite setup/teardown (beforeEach()/afterEach()) in the
GlobalCacheTest so each test starts with a clean
TenancyServiceProvider::$adjustCacheManagerUsing state.
🪄 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: Organization UI
Review profile: ASSERTIVE
Plan: Pro
Run ID: 574ac1d9-33d8-4426-852f-0208fe2e5108
📒 Files selected for processing (3)
src/TenancyServiceProvider.phptests/CachedTenantResolverTest.phptests/GlobalCacheTest.php
There was a problem hiding this comment.
Pull request overview
This PR fixes globalCache behavior so that database-backed cache stores use the central (or explicitly configured) DB connection even when the app is currently in tenant context (notably when using DatabaseTenancyBootstrapper + CacheTenancyBootstrapper). This prevents global cache reads/writes and cache invalidation from accidentally targeting tenant databases.
Changes:
- Adjust
globalCache’s freshly-instantiatedCacheManagerto reset database cache stores onto the central/configured connection. - Add regression coverage for the database cache driver when used with
CacheTenancyBootstrapper. - Reset
TenancyServiceProvider::$adjustCacheManagerUsingin tests to avoid cross-test state leakage.
Reviewed changes
Copilot reviewed 3 out of 3 changed files in this pull request and generated no comments.
| File | Description |
|---|---|
src/TenancyServiceProvider.php |
Ensures database cache stores on the globalCache manager are pointed at the central/configured DB connection. |
tests/GlobalCacheTest.php |
Adds regression dataset for database cache + CacheTenancyBootstrapper and resets the static cache-manager adjuster between tests. |
tests/CachedTenantResolverTest.php |
Adds regression dataset for database cache + CacheTenancyBootstrapper and resets the static cache-manager adjuster between tests. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
globalCache always use the central connectionglobalCache always use the central connection with database cache store
Mention that it's not intended to be used with database cache stores (it *can* be used with db cache stores, there's just a little unexpected behavior).
Instead of looping through all database cache stores and setting their connection to central, use extend() to create the database stores lazily, using central connection
PHPStan complains that createDatabaseDriver is a protected method on CacheManager. Since PHPStan doesn't handle $this in the extend()'s closure well, I'm adding an ignore.
| * (typically the GlobalCache facade or global_cache() helper), even though this bootstrapper explicitly | ||
| * sets the connection to tenant for all scoped cache stores. Extending database store on the global cache manager | ||
| * cannot fix globalCache on its own because it reads 'tenant' from config (set by this bootstrapper), not null, | ||
| * so the callback is still needed to correct the connection to central for globalCache. |
There was a problem hiding this comment.
The added text is a bit difficult to understand. Is this basically trying to say that the extend() approach we've added in this PR isn't enough to make global cache DB stores work when DatabaseCacheBootstrapper — the old logic using static::$adjustCacheManagerUsing is still needed — because even though the newly added extend() logic does normally make DB stores use the central DB, in this case $config['connection'] ??= $centralConnection; resolves to tenant because this bootstrapper also overrides the connections' config which makes that ??= not do anything and the stores stay tenant?
There was a problem hiding this comment.
I'm going to rewrite the added text with this understanding in mind. If that's incorrect, let me know here.
There was a problem hiding this comment.
Updated all comments in 9f344bf, let me know if they're all correct.
There was a problem hiding this comment.
Confirming that the changes seem good and correct
There was a problem hiding this comment.
Actionable comments posted: 2
♻️ Duplicate comments (1)
src/Bootstrappers/DatabaseCacheBootstrapper.php (1)
24-32: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winSimplify and sharpen the docblock explanation.
The current text is technically correct but dense. Future maintainers may struggle to follow the two-layer correction (extend() + callback). Consider condensing to the essential causality:
* Notably, this bootstrapper sets TenancyServiceProvider::$adjustCacheManagerUsing to a callback * that ensures all affected stores still use the central connection when accessed via global cache - * (typically the GlobalCache facade or global_cache() helper). The code in TenancyServiceProvider - * that uses `extend()` callbacks to make database stores on the global cache manager use the central - * connection only corrects stores scoped by the Database*Tenancy*Bootstrapper. This bootstrapper - * also changes the stores' connection in the *config* to 'tenant' which doesn't let that callback - * change the connection back to central on the global cache manager. + * (typically the GlobalCache facade or global_cache() helper). This is needed because the + * `extend()` callback in TenancyServiceProvider only overrides `null` connections; this + * bootstrapper writes `'tenant'` into config, which bypasses that null-coalescing fallback.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/Bootstrappers/DatabaseCacheBootstrapper.php` around lines 24 - 32, The docblock in DatabaseCacheBootstrapper is too dense and should be simplified to focus on the core behavior. Reword the explanation around TenancyServiceProvider::$adjustCacheManagerUsing and the global cache/GlobalCache path so it clearly states that this bootstrapper changes the cache store config to tenant while also overriding the connection back to central for global cache access. Keep the distinction between the extend() behavior and this callback, but condense the wording so maintainers can understand the causality quickly.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@src/Bootstrappers/CacheTenancyBootstrapper.php`:
- Around line 21-25: The warning text in CacheTenancyBootstrapper should be made
more precise, since “harmless” understates the operational complexity of double
scoping. Update the docblock near the database cache store note to describe that
the cache will be scoped both by tenant database and by prefix, making
inspection and eviction harder, while avoiding language that implies it is
simply harmless.
In `@src/TenancyServiceProvider.php`:
- Around line 109-112: Update the explanatory comment near the cache store
extension logic in TenancyServiceProvider so it accurately describes what the
extend() callback does: it restores the central connection for any database
cache store whose connection config is null, not just stores affected by
DatabaseTenancyBootstrapper. Make the wording reflect that
DatabaseCacheBootstrapper is the one that writes 'tenant' into the store config
and bypasses the null fallback, and keep the explanation tied to the globalCache
handling in the extend() closure.
---
Duplicate comments:
In `@src/Bootstrappers/DatabaseCacheBootstrapper.php`:
- Around line 24-32: The docblock in DatabaseCacheBootstrapper is too dense and
should be simplified to focus on the core behavior. Reword the explanation
around TenancyServiceProvider::$adjustCacheManagerUsing and the global
cache/GlobalCache path so it clearly states that this bootstrapper changes the
cache store config to tenant while also overriding the connection back to
central for global cache access. Keep the distinction between the extend()
behavior and this callback, but condense the wording so maintainers can
understand the causality quickly.
🪄 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: Organization UI
Review profile: ASSERTIVE
Plan: Pro
Run ID: e8b27373-c1c3-4254-b6fe-1ffbbc2af1c1
📒 Files selected for processing (3)
src/Bootstrappers/CacheTenancyBootstrapper.phpsrc/Bootstrappers/DatabaseCacheBootstrapper.phpsrc/TenancyServiceProvider.php
globalCache always use the central connection with database cache storeglobalCache always use the central connection with database cache stores
globalCacheshould always use the central connection, but when using adatabase-driver cache store withDatabaseTenancyBootstrapper, it does not (with the exception ofDatabaseCacheBootstrapper, explained below).globalCachecreates a freshCacheManagereach time it's resolved (it's abind, not asingleton). A freshly-created manager builds its database stores using the current default DB connection. WhenDatabaseTenancyBootstrapperis active, that default istenant. SoglobalCachein tenant context points at the tenant DB. Specifically,CachedTenantResolverstores cached tenant lookups viaglobalCache. When a domain is deleted in tenant context, the invalidation logic callsglobalCache->forget(...), but that hits the tenant DB, while the resolver cache entry is in the central DB.globalCache->forget(...)doesn't actually do anything in that case.With
DatabaseCacheBootstrapper, this is already handled.globalCacheis always central because it setsTenancyServiceProvider::$adjustCacheManagerUsingto a callback that explicitly restores the central connection onglobalCache's stores.To fix this, after constructing the fresh CacheManager in the globalCache binding, explicitly set the connection of every database-driver store to its configured connection value, falling back to central_connection when the config value is null (null value = inherits whatever the current default DB connection is).
This is sufficient for
CacheTenancyBootstrapperand any other bootstrapper that doesn't explicitly set the store's DB connection. ForDatabaseCacheBootstrapperspecifically, this alone is not enough since it explicitly sets the store's config connection to 'tenant'. That's why DatabaseCacheBootstrapper's$adjustCacheManagerUsingcallback runs after and overrides those stores back to the original (central) connection.Added datasets that use the database cache store + CacheTenancyBootstrapper to the relevant tests (globalCache and invalidation) to test regression (0cf7043), and the changes mentioned above (5e65c67) make these tests pass.
Summary by CodeRabbit
Bug Fixes
Tests
Documentation