aboutsummaryrefslogtreecommitdiff
path: root/Hutch/Networking/SystemStatusRepository.swift
blob: 028c64ec568a9b545664cc56a6e8e44a2403a8d7 (plain) (blame)
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
import Foundation

protocol SystemStatusServing: Sendable {
    func fetchSnapshotHTML() async throws -> String
    func fetchIncidentFeedData() async throws -> Data
}

struct CachedSystemStatusValue<Value: Sendable>: Sendable {
    let value: Value
    let lastSuccessfulAt: Date
    let isStale: Bool
    let refreshErrorMessage: String?
}

actor SystemStatusRepository {
    private let service: any SystemStatusServing
    private let ttl: TimeInterval
    private let cacheStore: SystemStatusCacheStore
    private let now: @Sendable () -> Date

    private var snapshotCache: CacheEntry<SystemStatusSnapshot>?
    private var incidentsCache: CacheEntry<[StatusIncident]>?
    private var hasLoadedPersistentCache = false

    init(
        service: any SystemStatusServing = SystemStatusService(),
        ttl: TimeInterval = 10 * 60,
        cacheStore: SystemStatusCacheStore = SystemStatusCacheStore(),
        now: @escaping @Sendable () -> Date = Date.init
    ) {
        self.service = service
        self.ttl = ttl
        self.cacheStore = cacheStore
        self.now = now
    }

    func snapshot(forceRefresh: Bool = false) async throws -> SystemStatusSnapshot {
        try await snapshotResult(forceRefresh: forceRefresh).value
    }

    func recentIncidents(forceRefresh: Bool = false) async throws -> [StatusIncident] {
        try await recentIncidentsResult(forceRefresh: forceRefresh).value
    }

    func snapshotResult(forceRefresh: Bool = false) async throws -> CachedSystemStatusValue<SystemStatusSnapshot> {
        await loadPersistentCacheIfNeeded()

        if let cached = snapshotCache, !forceRefresh, !cached.isExpired(ttl: ttl, now: now) {
            return CachedSystemStatusValue(
                value: cached.value,
                lastSuccessfulAt: cached.timestamp,
                isStale: false,
                refreshErrorMessage: nil
            )
        }

        do {
            let html = try await service.fetchSnapshotHTML()
            let snapshot = try SystemStatusService.parseSnapshotHTML(html, fetchedAt: now())
            let entry = CacheEntry(value: snapshot, timestamp: now())
            snapshotCache = entry
            await cacheStore.saveSnapshotHTML(html, timestamp: entry.timestamp)
            return CachedSystemStatusValue(
                value: snapshot,
                lastSuccessfulAt: entry.timestamp,
                isStale: false,
                refreshErrorMessage: nil
            )
        } catch {
            if let cached = snapshotCache {
                return CachedSystemStatusValue(
                    value: cached.value,
                    lastSuccessfulAt: cached.timestamp,
                    isStale: true,
                    refreshErrorMessage: refreshErrorMessage(from: error)
                )
            }
            throw error
        }
    }

    func recentIncidentsResult(forceRefresh: Bool = false) async throws -> CachedSystemStatusValue<[StatusIncident]> {
        await loadPersistentCacheIfNeeded()

        if let cached = incidentsCache, !forceRefresh, !cached.isExpired(ttl: ttl, now: now) {
            return CachedSystemStatusValue(
                value: cached.value,
                lastSuccessfulAt: cached.timestamp,
                isStale: false,
                refreshErrorMessage: nil
            )
        }

        do {
            let feedData = try await service.fetchIncidentFeedData()
            let incidents = try await SystemStatusService.parseIncidentFeedXML(feedData)
            let entry = CacheEntry(value: incidents, timestamp: now())
            incidentsCache = entry
            await cacheStore.saveIncidentFeedData(feedData, timestamp: entry.timestamp)
            return CachedSystemStatusValue(
                value: incidents,
                lastSuccessfulAt: entry.timestamp,
                isStale: false,
                refreshErrorMessage: nil
            )
        } catch {
            if let cached = incidentsCache {
                return CachedSystemStatusValue(
                    value: cached.value,
                    lastSuccessfulAt: cached.timestamp,
                    isStale: true,
                    refreshErrorMessage: refreshErrorMessage(from: error)
                )
            }
            throw error
        }
    }

    private func loadPersistentCacheIfNeeded() async {
        guard !hasLoadedPersistentCache else { return }
        if let persistedSnapshot = await cacheStore.loadSnapshotHTML(),
           let snapshot = try? SystemStatusService.parseSnapshotHTML(persistedSnapshot.html, fetchedAt: persistedSnapshot.timestamp) {
            snapshotCache = CacheEntry(value: snapshot, timestamp: persistedSnapshot.timestamp)
        }
        if let persistedFeed = await cacheStore.loadIncidentFeedData(),
           let incidents = try? await SystemStatusService.parseIncidentFeedXML(persistedFeed.data) {
            incidentsCache = CacheEntry(value: incidents, timestamp: persistedFeed.timestamp)
        }
        hasLoadedPersistentCache = true
    }

    private func refreshErrorMessage(from error: any Error) -> String {
        error.userFacingMessage
    }
}

struct CacheEntry<Value: Sendable>: Sendable {
    let value: Value
    let timestamp: Date

    nonisolated func isExpired(ttl: TimeInterval, now: @escaping @Sendable () -> Date = Date.init) -> Bool {
        now().timeIntervalSince(timestamp) > ttl
    }
}