Skip to content
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

Add expiration time to Cache protocol and in-memory cache. #2601

Merged
merged 3 commits into from
Apr 12, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 11 additions & 0 deletions Sources/Vapor/Cache/Cache.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,22 @@ public protocol Cache {
func set<T>(_ key: String, to value: T?) -> EventLoopFuture<Void>
where T: Encodable

/// Sets an encodable value into the cache with an expiry time. Existing values are replaced. If `nil`, removes value.
func set<T>(_ key: String, to value: T?, expiresIn expirationTime: CacheExpirationTime?) -> EventLoopFuture<Void>
where T: Encodable

/// Creates a request-specific cache instance.
func `for`(_ request: Request) -> Self
}

extension Cache {
/// Sets an encodable value into the cache with an expiry time. Existing values are replaced. If `nil`, removes value.
public func set<T>(_ key: String, to value: T?, expiresIn expirationTime: CacheExpirationTime?) -> EventLoopFuture<Void>
where T: Encodable
{
return self.set(key, to: value)
}

/// Gets a decodable value from the cache. Returns `nil` if not found.
public func get<T>(_ key: String) -> EventLoopFuture<T?>
where T: Decodable
Expand Down
21 changes: 21 additions & 0 deletions Sources/Vapor/Cache/CacheExpirationTime.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/// Defines the lifetime of an entry in a cache.
public enum CacheExpirationTime {
case seconds(Int)
case minutes(Int)
case hours(Int)
case days(Int)

/// Returns the amount of time in seconds.
public var seconds: Int {
switch self {
case let .seconds(seconds):
return seconds
case let .minutes(minutes):
return minutes * 60
case let .hours(hours):
return hours * 60 * 60
case let .days(days):
return days * 24 * 60 * 60
}
}
}
34 changes: 30 additions & 4 deletions Sources/Vapor/Cache/MemoryCache.swift
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,16 @@ private struct MemoryCacheKey: LockKey, StorageKey {
}

private final class MemoryCacheStorage {
struct CacheEntryBox<T> {
var expiresAt: Date?
var value: T

init(_ value: T) {
self.expiresAt = nil
self.value = value
}
}

private var storage: [String: Any]
private var lock: Lock

Expand All @@ -47,16 +57,27 @@ private final class MemoryCacheStorage {
{
self.lock.lock()
defer { self.lock.unlock() }
return self.storage[key] as? T

guard let box = self.storage[key] as? CacheEntryBox<T> else { return nil }
if let expiresAt = box.expiresAt, expiresAt < Date() {
self.storage.removeValue(forKey: key)
return nil
}

return box.value
}

func set<T>(_ key: String, to value: T?)
func set<T>(_ key: String, to value: T?, expiresIn expirationTime: CacheExpirationTime?)
where T: Encodable
{
self.lock.lock()
defer { self.lock.unlock() }
if let value = value {
self.storage[key] = value
var box = CacheEntryBox(value)
if let expirationTime = expirationTime {
box.expiresAt = Date().addingTimeInterval(TimeInterval(expirationTime.seconds))
}
self.storage[key] = box
} else {
self.storage.removeValue(forKey: key)
}
Expand All @@ -80,9 +101,14 @@ private struct MemoryCache: Cache {

func set<T>(_ key: String, to value: T?) -> EventLoopFuture<Void>
where T: Encodable
{
self.set(key, to: value, expiresIn: nil)
}

func set<T>(_ key: String, to value: T?, expiresIn expirationTime: CacheExpirationTime?) -> EventLoopFuture<Void>
where T: Encodable
{
self.storage.set(key, to: value)
self.storage.set(key, to: value, expiresIn: expirationTime)
return self.eventLoop.makeSucceededFuture(())
}

Expand Down
9 changes: 8 additions & 1 deletion Tests/VaporTests/CacheTests.swift
Original file line number Diff line number Diff line change
@@ -1,19 +1,26 @@
import XCTVapor

final class CacheTests: XCTestCase {
func testDefaultCache() throws {
func testInMemoryCache() throws {
let app = Application(.testing)
defer { app.shutdown() }

try XCTAssertNil(app.cache.get("foo", as: String.self).wait())
try app.cache.set("foo", to: "bar").wait()
try XCTAssertEqual(app.cache.get("foo").wait(), "bar")

// Test expiration
try app.cache.set("foo2", to: "bar2", expiresIn: .seconds(1)).wait()
try XCTAssertEqual(app.cache.get("foo2").wait(), "bar2")
sleep(1)
try XCTAssertNil(app.cache.get("foo2", as: String.self).wait())
}

func testCustomCache() throws {
let app = Application(.testing)
defer { app.shutdown() }
app.caches.use(.foo)
try app.cache.set("1", to: "2").wait()
try XCTAssertEqual(app.cache.get("foo").wait(), "bar")
}
}
Expand Down