72 lines
2.4 KiB
Swift
72 lines
2.4 KiB
Swift
import Foundation
|
|
|
|
@MainActor
|
|
final class SessionReadCache {
|
|
private struct Entry {
|
|
let bytes: Data
|
|
let storedAt: ContinuousClock.Instant
|
|
var fresh: Bool
|
|
}
|
|
|
|
private struct Request {
|
|
let task: Task<Data, Error>
|
|
let id = UUID()
|
|
}
|
|
|
|
private let clock = ContinuousClock()
|
|
private var entries: [String: Entry] = [:]
|
|
private var requests: [String: Request] = [:]
|
|
|
|
func cached(_ path: String) -> Data? {
|
|
guard let entry = entries[path], entry.storedAt.duration(to: clock.now) < .seconds(300) else { return nil }
|
|
return entry.bytes
|
|
}
|
|
|
|
func load(_ path: String, refresh: Bool, fetch: @escaping @MainActor () async throws -> Data) async throws -> Data {
|
|
try Task.checkCancellation()
|
|
if !refresh, let entry = entries[path], entry.fresh,
|
|
entry.storedAt.duration(to: clock.now) < .seconds(30) { return entry.bytes }
|
|
|
|
let request: Request
|
|
if let pending = requests[path] {
|
|
request = pending
|
|
} else {
|
|
request = Request(task: Task { try await fetch() })
|
|
requests[path] = request
|
|
}
|
|
let bytes: Data
|
|
do {
|
|
bytes = try await request.task.value
|
|
} catch {
|
|
if requests[path]?.id == request.id { requests[path] = nil }
|
|
throw error
|
|
}
|
|
// A write or sign-out can invalidate a request while its callers are suspended.
|
|
guard !request.task.isCancelled else { throw CancellationError() }
|
|
if requests[path]?.id == request.id {
|
|
requests[path] = nil
|
|
if bytes.count <= 128 * 1024 {
|
|
entries[path] = Entry(bytes: bytes, storedAt: clock.now, fresh: true)
|
|
if entries.count > 64, let oldest = entries.min(by: { $0.value.storedAt < $1.value.storedAt }) {
|
|
entries[oldest.key] = nil
|
|
}
|
|
} else {
|
|
entries[path] = nil
|
|
}
|
|
}
|
|
try Task.checkCancellation()
|
|
return bytes
|
|
}
|
|
|
|
func discard(_ path: String) { entries[path] = nil }
|
|
|
|
func invalidate(_ prefix: String, discard: Bool = false) {
|
|
for path in entries.keys.filter({ $0.hasPrefix(prefix) }) {
|
|
if discard { entries[path] = nil } else { entries[path]?.fresh = false }
|
|
}
|
|
for path in requests.keys.filter({ $0.hasPrefix(prefix) }) {
|
|
requests.removeValue(forKey: path)?.task.cancel()
|
|
}
|
|
}
|
|
}
|