Use synchronized MastodonCache to prevent race condition crashes

This commit is contained in:
Shadowfacts 2019-12-14 11:31:14 -05:00
parent 0c78af7d4f
commit c26657bafa
Signed by untrusted user: shadowfacts
GPG Key ID: 94A5AB95422746E5
1 changed files with 30 additions and 4 deletions

View File

@ -12,10 +12,10 @@ import Pachyderm
class MastodonCache {
private static var statuses = [String: Status]()
private static var accounts = [String: Account]()
private static var relationships = [String: Relationship]()
private static var notifications = [String: Pachyderm.Notification]()
private static var statuses = CachedDictionary<Status>(name: "Statuses")
private static var accounts = CachedDictionary<Account>(name: "Accounts")
private static var relationships = CachedDictionary<Relationship>(name: "Relationships")
private static var notifications = CachedDictionary<Pachyderm.Notification>(name: "Notifications")
static let statusSubject = PassthroughSubject<Status, Never>()
static let accountSubject = PassthroughSubject<Account, Never>()
@ -134,3 +134,29 @@ class MastodonCache {
}
}
class CachedDictionary<Value> {
private let name: String
private var dict = [String: Value]()
private let queue: DispatchQueue
init(name: String) {
self.name = name
self.queue = DispatchQueue(label: "CachedDictionary (\(name)) Coordinator", attributes: .concurrent)
}
subscript(key: String) -> Value? {
get {
var result: Value? = nil
queue.sync {
result = dict[key]
}
return result
}
set(value) {
queue.async(flags: .barrier) {
self.dict[key] = value
}
}
}
}