-
Notifications
You must be signed in to change notification settings - Fork 1.2k
fix: DiskCache served a cache miss for entries that were still fresh #26009
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
jkmassel
wants to merge
1
commit into
trunk
Choose a base branch
from
jkmassel/fix-diskcache-stale-read
base: trunk
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.
+112
−5
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 |
|---|---|---|
|
|
@@ -7,9 +7,11 @@ public actor DiskCache: DiskCacheProtocol { | |
|
|
||
| public static let shared = DiskCache() | ||
|
|
||
| private let cacheRoot = URL.cachesDirectory | ||
| private let cacheRoot: URL | ||
|
|
||
| public init() {} | ||
| public init(cacheRoot: URL = .cachesDirectory) { | ||
| self.cacheRoot = cacheRoot | ||
| } | ||
|
|
||
| public func read<T>( | ||
| _ type: T.Type, | ||
|
|
@@ -23,15 +25,19 @@ public actor DiskCache: DiskCacheProtocol { | |
| } | ||
|
|
||
| if let interval { | ||
| let attributes = try FileManager.default.attributesOfItem(atPath: path.path()) | ||
| // Read the date off the URL rather than a path string: `path()` percent-encodes, so a | ||
| // key needing encoding would name a file that doesn't exist. | ||
| let creationDate = try path.resourceValues(forKeys: [.creationDateKey]).creationDate | ||
|
|
||
| // If we can't find the creation date, assume the cache object is invalid because we can't guarantee | ||
| // the developer's intent will be respected. | ||
| guard let creationDate = attributes[.creationDate] as? Date else { | ||
| guard let creationDate else { | ||
| return nil | ||
| } | ||
|
|
||
| if creationDate.addingTimeInterval(interval) > Date.now { | ||
| // The entry expires once `interval` has elapsed since it was written, so treat it as a | ||
| // miss only once that moment has passed. | ||
| if creationDate.addingTimeInterval(interval) < Date.now { | ||
|
Contributor
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. Is the condition flipped because |
||
| return nil | ||
| } | ||
| } | ||
|
|
||
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,101 @@ | ||
| import Foundation | ||
| import Testing | ||
|
|
||
| @testable import WordPressCore | ||
|
|
||
| struct DiskCacheTests { | ||
|
|
||
| /// Each test gets its own root so a run never reads, writes, or deletes anything in the real | ||
| /// caches directory. | ||
| private func makeCache() throws -> (DiskCache, URL) { | ||
| let root = URL.temporaryDirectory.appending(path: "DiskCacheTests-\(UUID().uuidString)") | ||
| try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) | ||
| return (DiskCache(cacheRoot: root), root) | ||
| } | ||
|
|
||
| @Test func storesAndReadsBackAValue() async throws { | ||
| let (cache, root) = try makeCache() | ||
| defer { try? FileManager.default.removeItem(at: root) } | ||
|
|
||
| try await cache.store(["a", "b"], forKey: "key") | ||
|
|
||
| #expect(try await cache.read([String].self, forKey: "key") == ["a", "b"]) | ||
| } | ||
|
|
||
| /// A freshly-written entry is inside any sane window, so it has to come back. Before the fix | ||
| /// the comparison was inverted and this returned `nil`. | ||
| @Test func readsBackAnEntryThatIsStillFresh() async throws { | ||
| let (cache, root) = try makeCache() | ||
| defer { try? FileManager.default.removeItem(at: root) } | ||
|
|
||
| try await cache.store("value", forKey: "key") | ||
|
|
||
| #expect(try await cache.read(String.self, forKey: "key", notOlderThan: 3600) == "value") | ||
| } | ||
|
|
||
| /// The counterpart: a zero-length window expires the entry immediately. | ||
| @Test func treatsAnExpiredEntryAsAMiss() async throws { | ||
| let (cache, root) = try makeCache() | ||
| defer { try? FileManager.default.removeItem(at: root) } | ||
|
|
||
| try await cache.store("value", forKey: "key") | ||
| // The entry was written in the past, however narrowly, so any elapsed window excludes it. | ||
| try await Task.sleep(for: .milliseconds(50)) | ||
|
|
||
| #expect(try await cache.read(String.self, forKey: "key", notOlderThan: 0) == nil) | ||
| } | ||
|
|
||
| /// Passing no interval skips the age check entirely. | ||
| @Test func readsBackAnEntryWhenNoIntervalIsGiven() async throws { | ||
| let (cache, root) = try makeCache() | ||
| defer { try? FileManager.default.removeItem(at: root) } | ||
|
|
||
| try await cache.store("value", forKey: "key") | ||
|
|
||
| #expect(try await cache.read(String.self, forKey: "key") == "value") | ||
| } | ||
|
|
||
| @Test func returnsNilForAKeyThatWasNeverStored() async throws { | ||
| let (cache, root) = try makeCache() | ||
| defer { try? FileManager.default.removeItem(at: root) } | ||
|
|
||
| #expect(try await cache.read(String.self, forKey: "missing") == nil) | ||
| #expect(try await cache.read(String.self, forKey: "missing", notOlderThan: 3600) == nil) | ||
| } | ||
|
|
||
| /// The age check used to resolve the file through a percent-encoded path string, which named a | ||
| /// file that doesn't exist whenever the key needed encoding. | ||
| @Test func handlesAKeyThatNeedsPercentEncoding() async throws { | ||
| let (cache, root) = try makeCache() | ||
| defer { try? FileManager.default.removeItem(at: root) } | ||
|
|
||
| try await cache.store("value", forKey: "conversation 1 of 100%") | ||
|
|
||
| #expect(try await cache.read(String.self, forKey: "conversation 1 of 100%", notOlderThan: 3600) == "value") | ||
| } | ||
|
|
||
| @Test func removesAStoredEntry() async throws { | ||
| let (cache, root) = try makeCache() | ||
| defer { try? FileManager.default.removeItem(at: root) } | ||
|
|
||
| try await cache.store("value", forKey: "key") | ||
| try await cache.remove(key: "key") | ||
|
|
||
| #expect(try await cache.read(String.self, forKey: "key") == nil) | ||
| } | ||
|
|
||
| /// `removeAll` only touches the injected root, which is what keeps these tests from clearing a | ||
| /// developer's real cache. | ||
| @Test func removeAllClearsOnlyTheInjectedRoot() async throws { | ||
| let (cache, root) = try makeCache() | ||
| defer { try? FileManager.default.removeItem(at: root) } | ||
|
|
||
| try await cache.store("a", forKey: "one") | ||
| try await cache.store("b", forKey: "two") | ||
| #expect(try await cache.count() == 2) | ||
|
|
||
| try await cache.removeAll() | ||
|
|
||
| #expect(try await cache.count() == 0) | ||
| } | ||
| } |
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.
What do you think about using modification date instead, considering there is an API to update cache?