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

Update front storage with back storage when cache only found in back storage #84

Merged
merged 4 commits into from
May 15, 2017
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions Cache.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@
objects = {

/* Begin PBXBuildFile section */
57506FAE1EC29437009B71E9 /* ObjectMetadata.swift in Sources */ = {isa = PBXBuildFile; fileRef = 57506FAD1EC29437009B71E9 /* ObjectMetadata.swift */; };
57506FBF1EC2E1B7009B71E9 /* ObjectMetadata.swift in Sources */ = {isa = PBXBuildFile; fileRef = 57506FAD1EC29437009B71E9 /* ObjectMetadata.swift */; };
57506FC01EC2E1BA009B71E9 /* ObjectMetadata.swift in Sources */ = {isa = PBXBuildFile; fileRef = 57506FAD1EC29437009B71E9 /* ObjectMetadata.swift */; };
BDEDD3601DBCE5CE007416A6 /* BasicHybridCache.swift in Sources */ = {isa = PBXBuildFile; fileRef = D5291C6A1C2827FB00B702C9 /* BasicHybridCache.swift */; };
BDEDD3611DBCE5CE007416A6 /* Cache.swift in Sources */ = {isa = PBXBuildFile; fileRef = D5ACACDD1CD0272600567809 /* Cache.swift */; };
BDEDD3621DBCE5CE007416A6 /* Config.swift in Sources */ = {isa = PBXBuildFile; fileRef = D5291C151C28220B00B702C9 /* Config.swift */; };
Expand Down Expand Up @@ -143,6 +146,7 @@
/* End PBXContainerItemProxy section */

/* Begin PBXFileReference section */
57506FAD1EC29437009B71E9 /* ObjectMetadata.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ObjectMetadata.swift; sourceTree = "<group>"; };
BDEDD3561DBCE5B1007416A6 /* Cache.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Cache.framework; sourceTree = BUILT_PRODUCTS_DIR; };
BDEDD3781DBCEB8A007416A6 /* Cache-tvOS-Tests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "Cache-tvOS-Tests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; };
D5291C151C28220B00B702C9 /* Config.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Config.swift; sourceTree = "<group>"; };
Expand Down Expand Up @@ -322,6 +326,7 @@
D5291C251C28220B00B702C9 /* MemoryStorage.swift */,
D5291C261C28220B00B702C9 /* StorageAware.swift */,
D5291C271C28220B00B702C9 /* StorageFactory.swift */,
57506FAD1EC29437009B71E9 /* ObjectMetadata.swift */,
);
path = Storage;
sourceTree = "<group>";
Expand Down Expand Up @@ -840,6 +845,7 @@
BDEDD36D1DBCE5D8007416A6 /* SyncCache.swift in Sources */,
BDEDD36A1DBCE5D8007416A6 /* NSDate+Cache.swift in Sources */,
BDEDD36F1DBCE5D8007416A6 /* DiskStorage.swift in Sources */,
57506FC01EC2E1BA009B71E9 /* ObjectMetadata.swift in Sources */,
D5A138C21EB29BFA00881A20 /* UIImage+Cache.swift in Sources */,
BDEDD3601DBCE5CE007416A6 /* BasicHybridCache.swift in Sources */,
BDEDD3701DBCE5D8007416A6 /* MemoryStorage.swift in Sources */,
Expand Down Expand Up @@ -922,6 +928,7 @@
D5291D911C283CFB00B702C9 /* String+Cache.swift in Sources */,
D5291D901C283CFB00B702C9 /* NSDate+Cache.swift in Sources */,
D5A138C41EB29C2100881A20 /* NSImage+Cache.swift in Sources */,
57506FBF1EC2E1B7009B71E9 /* ObjectMetadata.swift in Sources */,
D5291D931C283CFB00B702C9 /* DiskStorage.swift in Sources */,
D5291D861C283CFB00B702C9 /* BasicHybridCache.swift in Sources */,
D5ACACCD1CD0207300567809 /* SyncHybridCache.swift in Sources */,
Expand Down Expand Up @@ -960,6 +967,7 @@
D5291C321C28220B00B702C9 /* StorageKind.swift in Sources */,
D5291C301C28220B00B702C9 /* Expiry.swift in Sources */,
D5291C331C28220B00B702C9 /* JSON+Cache.swift in Sources */,
57506FAE1EC29437009B71E9 /* ObjectMetadata.swift in Sources */,
D5A138C11EB29BFA00881A20 /* UIImage+Cache.swift in Sources */,
D5291C2F1C28220B00B702C9 /* Capsule.swift in Sources */,
D5291C2D1C28220B00B702C9 /* Config.swift in Sources */,
Expand Down
36 changes: 29 additions & 7 deletions Source/Shared/BasicHybridCache.swift
Original file line number Diff line number Diff line change
Expand Up @@ -32,16 +32,22 @@ public class BasicHybridCache: NSObject {
- Parameter name: A name of the cache
- Parameter config: Cache configuration
*/
public init(name: String, config: Config = Config.defaultConfig) {
public convenience init(name: String, config: Config = Config.defaultConfig) {
let frontStorage = StorageFactory.resolve(name, kind: config.frontKind, maxSize: UInt(config.maxObjects))
let backStorage = StorageFactory.resolve(name, kind: config.backKind, maxSize: config.maxSize)
self.init(name: name, frontStorage: frontStorage, backStorage: backStorage, config: config)

}
internal init(name: String, frontStorage: StorageAware, backStorage: StorageAware, config: Config) {
self.name = name
self.frontStorage = frontStorage
self.backStorage = backStorage
self.config = config

frontStorage = StorageFactory.resolve(name, kind: config.frontKind, maxSize: UInt(config.maxObjects))
backStorage = StorageFactory.resolve(name, kind: config.backKind, maxSize: config.maxSize)
super.init()

let notificationCenter = NotificationCenter.default

#if os(macOS)
notificationCenter.addObserver(self, selector: #selector(clearExpiredDataInBackStorage),
name: NSNotification.Name.NSApplicationWillTerminate, object: nil)
Expand All @@ -56,7 +62,7 @@ public class BasicHybridCache: NSObject {
name: .UIApplicationDidEnterBackground, object: nil)
#endif
}

/**
Removes notification center observer.
*/
Expand Down Expand Up @@ -109,10 +115,26 @@ public class BasicHybridCache: NSObject {
}

weakSelf.backStorage.object(key) { (object: T?) in
completion(object)
guard let object = object else {
completion(nil)
return
}
weakSelf.copyToFrontStorage(key, object: object, completion: completion)
}
}
}

private func copyToFrontStorage<T: Cachable>(_ key: String, object: T, completion: @escaping (_ object: T?) -> Void) {

guard let metadata = self.backStorage.objectMetadata(key) else {
completion(nil)
return
}

self.frontStorage.add(key, object: object, expiry: metadata.expiry, completion: { _ in
completion(object)
})
}

/**
Removes the object from to the front and back cache storages.
Expand Down
17 changes: 17 additions & 0 deletions Source/Shared/Storage/DiskStorage.swift
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,23 @@ public final class DiskStorage: StorageAware {
completion?()
}
}

/**
Gets information about the cached object.

- Parameter key: Unique key to identify the object in the cache
*/
public func objectMetadata(_ key: String) -> ObjectMetadata? {

do {
let attributes = try fileManager.attributesOfItem(atPath: filePath(key))
let fileModifiedDate = Expiry.date(attributes[FileAttributeKey.modificationDate] as! Date)
Copy link
Contributor

Choose a reason for hiding this comment

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

Can modificationDate be nil at this point?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@zenangst I assume modificationDate can't be nil. But in the off chance that it is, if the file is deleted fileManager.attributesOfItem is called, I concluded that we shouldn't return a cache object.

Copy link
Contributor

Choose a reason for hiding this comment

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

@kirmanie nice! was just curious :)

Copy link
Contributor

Choose a reason for hiding this comment

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

@kirmanie I think I would still add guard or if to avoid force unwrapping.

return ObjectMetadata(expiry: fileModifiedDate)

} catch {}

return nil
}

/**
Tries to retrieve the object from the disk storage.
Expand Down
14 changes: 14 additions & 0 deletions Source/Shared/Storage/MemoryStorage.swift
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,20 @@ public final class MemoryStorage: StorageAware {
}
}

/**
Gets information about the cached object.

- Parameter key: Unique key to identify the object in the cache
*/
public func objectMetadata(_ key: String) -> ObjectMetadata? {

guard let capsule = cache.object(forKey: key as AnyObject) as? Capsule else {
return nil
}

return ObjectMetadata(expiry: Expiry.date(capsule.expiryDate))
}

/**
Tries to retrieve the object from the memory storage.

Expand Down
9 changes: 9 additions & 0 deletions Source/Shared/Storage/ObjectMetadata.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
public struct ObjectMetadata {
let expiry: Expiry
}

extension ObjectMetadata: Equatable {}

public func ==(lhs: ObjectMetadata, rhs: ObjectMetadata) -> Bool {
return lhs.expiry.date == rhs.expiry.date
}
7 changes: 7 additions & 0 deletions Source/Shared/Storage/StorageAware.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,13 @@ public protocol CacheAware {
*/
func add<T: Cachable>(_ key: String, object: T, expiry: Expiry, completion: (() -> Void)?)

/**
Gets information about the cached object.

- Parameter key: Unique key to identify the object in the cache
*/
func objectMetadata(_ key: String) -> ObjectMetadata?

/**
Tries to retrieve the object from the cache.

Expand Down
28 changes: 28 additions & 0 deletions Tests/iOS/Specs/CacheSpec.swift
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,34 @@ class CacheSpec: QuickSpec {

self.waitForExpectations(timeout: 4.0, handler:nil)
}

it("should resolve from disk and set in-memory cache if object not in-memory") {
let frontStorage = MemoryStorage(name: "MemoryStorage")
let backStorage = DiskStorage(name: "DiskStorage")
let config = Config.defaultConfig
let key = "myusernamedjohn"
let object = SpecHelper.user

let cache = Cache<User>(name: "MyCache", frontStorage: frontStorage, backStorage: backStorage, config: config)

waitUntil(timeout: 4.0) { done in

backStorage.add(key, object: object) {

cache.object(key) { (receivedObject: User?) in

expect(receivedObject?.firstName).to(equal(object.firstName))
expect(receivedObject?.lastName).to(equal(object.lastName))

frontStorage.object(key) { (inmemoryCachedUser: User?) in
expect(inmemoryCachedUser?.firstName).to(equal(object.firstName))
expect(inmemoryCachedUser?.lastName).to(equal(object.lastName))
done()
}
}
}
}
}
}

describe("#remove") {
Expand Down
27 changes: 27 additions & 0 deletions Tests/iOS/Specs/Storage/DiskStorageSpec.swift
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,33 @@ class DiskStorageSpec: QuickSpec {
}
}

describe("#objectMetadata") {
it("returns nil if object doesn't exist") {
let storage = DiskStorage(name: name)

let metadata = storage.objectMetadata(key)

expect(metadata).to(beNil())
}

it("returns object metadata if object exists") {
let storage = DiskStorage(name: name)

waitUntil(timeout: 2.0) { done in

storage.add(key, object: object) {
let metadata = storage.objectMetadata(key)
let attributes = try! fileManager.attributesOfItem(atPath: storage.filePath(key))
let fileModifiedDate = Expiry.date(attributes[FileAttributeKey.modificationDate] as! Date)
let expectedMetadata = ObjectMetadata(expiry: fileModifiedDate)

expect(metadata).to(equal(expectedMetadata))
done()
}
}
}
}

describe("#object") {
it("resolves cached object") {
let expectation = self.expectation(description: "Object Expectation")
Expand Down
27 changes: 26 additions & 1 deletion Tests/iOS/Specs/Storage/MemoryStorageSpec.swift
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,32 @@ class MemoryStorageSpec: QuickSpec {
self.waitForExpectations(timeout: 2.0, handler:nil)
}
}


describe("#objectMetadata") {
it("returns nil if object doesn't exist") {
let storage = MemoryStorage(name: name)

let metadata = storage.objectMetadata(key)

expect(metadata).to(beNil())
}

it("returns object metadata if object exists") {
let storage = MemoryStorage(name: name)
let expiry = Expiry.date(Date())

waitUntil(timeout: 2.0) { done in

storage.add(key, object: object, expiry: expiry) {
let metadata = storage.objectMetadata(key)
let expectedMetadata = ObjectMetadata(expiry: expiry)
expect(metadata).to(equal(expectedMetadata))
done()
}
}
}
}

describe("#object") {
it("resolves cached object") {
let expectation = self.expectation(description: "Object Expectation")
Expand Down