diff --git a/src/Database/Database.php b/src/Database/Database.php index 5e72088cb..fe21d45c0 100644 --- a/src/Database/Database.php +++ b/src/Database/Database.php @@ -2785,12 +2785,27 @@ public function getCacheKeys(string $collectionId, ?string $documentId = null, a $sortedSelects = $selects; \sort($sortedSelects); - $payload = \json_encode([ - 'selects' => $sortedSelects, - 'relationships' => $collectionId !== self::METADATA && ($this->relationshipHook?->isEnabled() ?? false), - 'filters' => $this->getActiveFilterSignatures(), - ]) ?: ''; - $documentHashKey = $documentKey . ':' . \md5($payload); + $relationships = $collectionId !== self::METADATA && ($this->relationshipHook?->isEnabled() ?? false); + $filters = $this->getActiveFilterSignatures(); + $memoKey = ($filters === [] ? '-' : '+') + .($relationships ? '1' : '0') + .($sortedSelects === [] ? '' : (\json_encode($sortedSelects) ?: "\0")); + + $hash = self::$documentKeyHashes[$memoKey] ?? null; + if ($hash === null) { + $payload = \json_encode([ + 'selects' => $sortedSelects, + 'relationships' => $relationships, + 'filters' => $filters, + ]) ?: ''; + $hash = \md5($payload); + + if (\count(self::$documentKeyHashes) >= self::DOCUMENT_KEY_HASHES_LIMIT) { + self::$documentKeyHashes = []; + } + self::$documentKeyHashes[$memoKey] = $hash; + } + $documentHashKey = $documentKey . ':' . $hash; } return [ @@ -2938,6 +2953,24 @@ protected function getCollectionMetadataCacheKey(string $collection): string .'::'.$tenantKey.'::'.$collection; } + /** + * The filter signatures last built and the inputs they were built from, kept because cache keys need them on + * every read. An input that has not changed is the same array, which compares in constant time. + * + * @var array{filters: array, codecs: array, exclusions: array, signatures: array}|null + */ + private static ?array $filterSignatures = null; + + /** + * Document cache key hashes under the filter signatures last built, by whether filters apply, the relationships + * flag and the sorted selects. + * + * @var array + */ + private static array $documentKeyHashes = []; + + private const int DOCUMENT_KEY_HASHES_LIMIT = 1024; + /** * @return array */ @@ -2947,15 +2980,38 @@ private function getActiveFilterSignatures(): array return []; } + $codecs = $this->codecs?->signatures() ?? []; + $exclusions = $this->filterExclusions()->get() ?? []; + + $built = self::$filterSignatures; + if ( + $built !== null + && $built['filters'] === self::$filters + && $built['codecs'] === $codecs + && $built['exclusions'] === $exclusions + ) { + return $built['signatures']; + } + $signatures = []; foreach (self::$filters as $name => $callbacks) { $signatures[$name] = $callbacks['signature']; } - $signatures = \array_diff_key(($this->codecs?->signatures() ?? []) + $signatures, $this->filterExclusions()->get() ?? []); + $signatures = \array_diff_key($codecs + $signatures, $exclusions); \ksort($signatures); + if ($built === null || $built['signatures'] !== $signatures) { + self::$documentKeyHashes = []; + } + self::$filterSignatures = [ + 'filters' => self::$filters, + 'codecs' => $codecs, + 'exclusions' => $exclusions, + 'signatures' => $signatures, + ]; + return $signatures; } diff --git a/tests/unit/CacheKeyTest.php b/tests/unit/CacheKeyTest.php index ee604ade1..1cde0483c 100644 --- a/tests/unit/CacheKeyTest.php +++ b/tests/unit/CacheKeyTest.php @@ -163,6 +163,102 @@ public function testFiltersDisabledEntirelyProducesDifferentCacheKey(): void $this->assertNotEquals($hashEnabled, $hashDisabled); } + /** + * The digest other readers of the cache (such as the Rust port) rebuild: md5 of the JSON of the sorted + * selects, the relationships flag and the active filter signatures sorted by name. + * + * @param list $selects + * @param array $exclusions + */ + private function expectedHashKey(Database $db, array $selects, array $exclusions = []): string + { + $signatures = []; + foreach (FilterRegistry::filters() as $name => $callbacks) { + $signatures[$name] = $callbacks['signature']; + } + $signatures = \array_diff_key($db->getFilters()->signatures() + $signatures, $exclusions); + \ksort($signatures); + \sort($selects); + + [, $documentKey] = $db->getCacheBaseKeys('col', 'doc1'); + + return $documentKey.':'.\md5(\json_encode([ + 'selects' => $selects, + 'relationships' => false, + 'filters' => $signatures, + ]) ?: ''); + } + + public function testRepeatedHashKeysMatchTheirDigest(): void + { + $db = $this->createDatabase(); + + foreach ([[], ['name'], ['email', 'name'], []] as $selects) { + for ($i = 0; $i < 2; $i++) { + [, , $hashKey] = $db->getCacheKeys('col', 'doc1', $selects); + $this->assertSame($this->expectedHashKey($db, $selects), $hashKey); + } + } + } + + public function testFilterAddedAfterAKeyWasBuiltChangesTheKey(): void + { + $db = $this->createDatabase(); + $before = $this->getHashKey($db); + $filters = FilterRegistry::filters(); + $defaultsRegistered = FilterRegistry::defaultsRegistered(); + + try { + Database::addFilter('cacheKeyLateFilter', static fn (mixed $value): mixed => $value, static fn (mixed $value): mixed => $value); + + $after = $this->getHashKey($db); + $this->assertNotSame($before, $after); + $this->assertSame($this->expectedHashKey($db, []), $after); + } finally { + FilterRegistry::restore($filters, $defaultsRegistered); + } + + $this->assertSame($before, $this->getHashKey($db)); + } + + public function testCodecRegisteredOnASharedRegistryAfterAKeyWasBuiltChangesTheKey(): void + { + $db = $this->createDatabase(); + $other = $this->createDatabase()->setFilters($db->getFilters()); + $before = $this->getHashKey($db); + + $noop = static fn (mixed $value): mixed => $value; + $other->getFilters()->register(new Callback('sharedLateCodec', $noop, $noop)); + + $after = $this->getHashKey($db); + $this->assertNotSame($before, $after); + $this->assertSame($this->expectedHashKey($db, []), $after); + $this->assertSame($after, $this->getHashKey($other)); + } + + public function testAlternatingFilterExclusionsKeepTheirOwnKeys(): void + { + $db = $this->createDatabase(); + $skipJson = fn (): string => $db->skipFilters(fn (): string => $this->getHashKey($db), ['json']); + + $enabled = $this->getHashKey($db); + $skipped = $skipJson(); + + $this->assertSame($this->expectedHashKey($db, [], ['json' => true]), $skipped); + for ($i = 0; $i < 3; $i++) { + $this->assertSame($enabled, $this->getHashKey($db)); + $this->assertSame($skipped, $skipJson()); + } + + $db->setFiltering(false); + $off = $this->getHashKey($db); + $db->setFiltering(true); + $this->assertSame($enabled, $this->getHashKey($db)); + $db->setFiltering(false); + $this->assertSame($off, $this->getHashKey($db)); + $db->setFiltering(true); + } + public function testQueryCacheKeyUsesQueryCacheShape(): void { $adapter = self::createStub(FeatureAdapterStub::class);