Skip to content

Commit

Permalink
fix: limited last reader write to the db only once in 30 seconds to p…
Browse files Browse the repository at this point in the history
…revent I/O spamming with last read (#1817)
  • Loading branch information
exelban committed Feb 16, 2024
1 parent cc4b8c8 commit ec52dde
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 4 deletions.
2 changes: 2 additions & 0 deletions .swiftlint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ identifier_name:
- CombinedModulesSpacings
- BatteryInfo
- PublicIPAddressRefreshIntervals
- _values
- _writeTS

line_length: 200

Expand Down
15 changes: 11 additions & 4 deletions Kit/plugins/DB.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,11 @@ public class DB {
private let queue = DispatchQueue(label: "eu.exelban.db")
private let ttl: Int = 60*60

public var keys: [String] = []
public var _writeTS: [String: Date] = [:]
public var writeTS: [String: Date] {
get { self.queue.sync { self._writeTS } }
set { self.queue.sync { self._writeTS = newValue } }
}

private var _values: [String: Codable] = [:]
public var values: [String: Codable] {
Expand Down Expand Up @@ -47,9 +51,7 @@ public class DB {
}

public func setup<T: Codable>(_ type: T.Type, _ key: String) {
self.keys.append(key)
self.clean(key)

if let raw = self.lldb?.findOne(key), let value = try? JSONDecoder().decode(type, from: Data(raw.utf8)) {
self.values[key] = value
}
Expand All @@ -58,10 +60,15 @@ public class DB {
public func insert(key: String, value: Codable, ts: Bool = true) {
self.values[key] = value
guard let blobData = try? JSONEncoder().encode(value) else { return }
self.lldb?.insert(key, value: String(decoding: blobData, as: UTF8.self))

if ts {
self.lldb?.insert("\(key)@\(Date().currentTimeSeconds())", value: String(decoding: blobData, as: UTF8.self))
}

if let ts = self.writeTS[key], (Date().timeIntervalSince1970-ts.timeIntervalSince1970) < 30 { return }

self.lldb?.insert(key, value: String(decoding: blobData, as: UTF8.self))
self.writeTS[key] = Date()
}

public func findOne<T: Decodable>(_ dynamicType: T.Type, key: String) -> T? {
Expand Down

0 comments on commit ec52dde

Please sign in to comment.