-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDomainCacheEngine.swift
More file actions
71 lines (61 loc) Β· 2.01 KB
/
Copy pathDomainCacheEngine.swift
File metadata and controls
71 lines (61 loc) Β· 2.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
//
// DomainCacheEngine.swift
// Data
//
// Created by λ°λ―Όμ on 3/20/26.
// Copyright Β© 2025 yapp25thTeamTnT. All rights reserved.
//
import Foundation
enum DomainCacheReadResult<Snapshot: DomainCacheSnapshot>: Sendable {
case fresh(Snapshot)
case stale(Snapshot)
case miss
var freshSnapshot: Snapshot? {
guard case .fresh(let snapshot) = self else { return nil }
return snapshot
}
}
actor DomainCacheEngine {
private let policy: DomainCachePolicy
private let storage: any DomainSnapshotStoring
private let now: @Sendable () -> Date
init(
policy: DomainCachePolicy,
storage: any DomainSnapshotStoring,
now: @escaping @Sendable () -> Date = { Date() }
) {
self.policy = policy
self.storage = storage
self.now = now
}
func loadSnapshot<Snapshot: DomainCacheSnapshot>(
_ type: Snapshot.Type,
key: DomainCacheKey,
maxAge: TimeInterval?
) async throws -> DomainCacheReadResult<Snapshot> {
guard let envelope: DomainCacheEnvelope<Snapshot> = try await storage.loadSnapshot(
type,
key: key,
policy: policy
) else {
return .miss
}
guard let maxAge else { return .fresh(envelope.snapshot) }
return now().timeIntervalSince(envelope.savedAt) <= maxAge
? .fresh(envelope.snapshot)
: .stale(envelope.snapshot)
}
func saveSnapshot<Snapshot: DomainCacheSnapshot>(
_ snapshot: Snapshot,
key: DomainCacheKey
) async throws {
try await storage.saveSnapshot(snapshot, key: key, policy: policy)
try await storage.cleanupSnapshots(namespace: key.namespace, policy: policy, now: now())
}
func clear(namespace: String) async throws {
try await storage.removeSnapshots(namespace: namespace, policy: policy)
}
func cleanupSnapshotsAcrossNamespaces() async throws {
try await storage.cleanupSnapshots(policy: policy, now: now())
}
}