Skip to content

Commit

Permalink
Cache expiration for meta.last_update on an object's own channel.
Browse files Browse the repository at this point in the history
  • Loading branch information
elliottwilliams committed May 27, 2017
1 parent 97b3e59 commit 2b1b625
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
3 changes: 2 additions & 1 deletion Proper/Connection/CachedConnection.swift
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,8 @@ class CachedConnection<C: ConnectionType>: ConnectionType {
// terminates.
func subscribe(to topic: String) -> EventProducer {
return connection.subscribe(to: topic)
.on(value: { [weak self] in _ = self?.cache.store(event: $0, topic: topic) })
.on(terminated: { [weak self] in self?.cache.expire(lastEventFrom: topic, on: topic) },
value: { [weak self] in _ = self?.cache.store(event: $0, topic: topic) })
}
}

Expand Down
20 changes: 17 additions & 3 deletions Proper/Connection/LastEventCache.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ import Foundation

/// `NSCache`-backed storage for looking up responses to `meta.last_event`.
class LastEventCache: NSObject {
let cache = NSCache<NSString, Box<TopicEvent>>()
private let cache = NSCache<NSString, Box<TopicEvent>>()
private var voids = [String: DispatchWorkItem]()

/// Create a cache which retains around `numEvents` events (default 100).
init (numEvents: Int = 100) {
Expand Down Expand Up @@ -42,16 +43,29 @@ class LastEventCache: NSObject {
/// Store `event` in the cache. `event` must have an originator. Returns `true` if stored.
func store(event: TopicEvent, topic: String) {
if let originator = event.originator {
cache.setObject(Box(event), forKey: key(topic, originator) as NSString)
let key = self.key(topic, originator)
voids[key]?.cancel()
cache.setObject(Box(event), forKey: key as NSString)
}
}

/// Request `topic` to be removed from the cache at the end of the main loop.
@available(*, deprecated: 1.0, message: "Functionality removed, is now a no-op")
@available(*, unavailable, message: "Use expire(lastEventFrom:on)")
func void(topic: String) {
return
}

/// Informs the cache that a particular `lastEvent` will no longer be updated and will no longer be guaranteed valid.
func expire(lastEventFrom originator: String, on topic: String) {
let key = self.key(topic, originator)
let action = DispatchWorkItem { [weak self] in
self?.cache.removeObject(forKey: key as NSString)
self?.voids[key] = nil
}
voids[key] = action
DispatchQueue.main.async(execute: action)
}

private static func eventParams(_ proc: String, _ args: WampArgs) -> (metaTopic: String, originator: String)? {
guard let metaTopic = args[safe: 0] as? String, let originator = args[safe: 1] as? String,
proc == "meta.last_event" else {
Expand Down

0 comments on commit 2b1b625

Please sign in to comment.