TeraSupportingStores.swift (11566B)
1 import Foundation 2 3 enum TeraSupportingLoadState: Sendable, Equatable { 4 case idle 5 case loading 6 case loaded 7 case empty 8 case failed(String) 9 } 10 11 @MainActor 12 final class TeraSearchStore: ObservableObject { 13 private static let rawQueryBytesMax = 256 14 private static let normalizedQueryBytesMax = 256 15 16 @Published private(set) var query = "" 17 @Published private(set) var results: [TeraSearchResult] = [] 18 @Published private(set) var state: TeraSupportingLoadState = .idle 19 @Published private(set) var observationState: TeraRuntimeObservationState = .inactive 20 var mediaWillChange: ([TeraMediaReference], [TeraMediaReference], TeraLocalNetwork?) -> Void = { _, _, _ in } 21 22 private let runtimeClient: TeraRuntimeClient 23 private let clock: TeraClock 24 private let observationDelay: @Sendable (UInt32) async throws -> Void 25 private var context: TeraLocalNetwork? 26 private var generation = TeraSessionGeneration.initial 27 private let observation = TeraStoreObservation() 28 29 init( 30 runtimeClient: TeraRuntimeClient, 31 clock: TeraClock = .system, 32 observationDelay: @escaping @Sendable (UInt32) async throws -> Void = TeraRuntimeObservationBackoff.sleep 33 ) { 34 self.runtimeClient = runtimeClient 35 self.clock = clock 36 self.observationDelay = observationDelay 37 } 38 39 func configure(context: TeraLocalNetwork?) { 40 guard self.context != context else { return } 41 generation = generation.invalidated() 42 replaceResults([]) 43 self.context = context 44 query = "" 45 state = .idle 46 if observation.isActive { 47 observation.stop() 48 start() 49 } 50 } 51 52 func updateQuery(_ value: String) { 53 generation = generation.invalidated() 54 query = value 55 replaceResults([]) 56 state = .idle 57 } 58 59 func start() { 60 observation.start( 61 client: runtimeClient, buffer: (capacity: 8, delay: observationDelay), 62 state: { [weak self] in self?.observationState = $0 }, 63 accepts: { [weak self] in $0.matches(context: self?.context) }, 64 invalidate: { [weak self] batch in 65 guard batch.contains(anyOf: [.today, .identity, .profile]) else { return } 66 self?.invalidatePresentation() 67 }, 68 refresh: { [weak self] batch in 69 guard batch.contains(anyOf: [.today, .identity, .profile]) else { return } 70 await self?.search() 71 } 72 ) 73 } 74 75 func invalidatePresentation() { 76 generation = generation.invalidated() 77 replaceResults([]) 78 state = .idle 79 } 80 81 func currentResult(id: String, type: TeraSearchResultType, context: TeraLocalNetwork?) -> TeraSearchResult? { 82 guard self.context == context else { return nil } 83 return results.first { $0.id == id && $0.type == type } 84 } 85 86 func currentMedia(context: TeraLocalNetwork?) -> [TeraMediaReference] { 87 guard self.context == context else { return [] } 88 return results.flatMap { supportingMedia(card: $0.card, profile: $0.profile) } 89 } 90 91 func search() async { 92 guard let context else { 93 state = .failed("Choose a local network before searching.") 94 return 95 } 96 guard query.utf8.count <= Self.rawQueryBytesMax, 97 !query.unicodeScalars.contains(where: CharacterSet.controlCharacters.contains) 98 else { 99 replaceResults([]) 100 state = .idle 101 return 102 } 103 let normalized = query.trimmingCharacters(in: .whitespacesAndNewlines) 104 guard !normalized.isEmpty, 105 normalized.lowercased().utf8.count <= Self.normalizedQueryBytesMax 106 else { 107 replaceResults([]) 108 state = .idle 109 return 110 } 111 112 generation = generation.invalidated() 113 let requestedGeneration = generation 114 state = .loading 115 do { 116 let loaded = try await runtimeClient.search( 117 context: context, 118 query: normalized, 119 limit: 50, 120 asOfUnixSeconds: clock.unixSeconds() 121 ) 122 guard requestedGeneration == generation, generation.isActive, !Task.isCancelled else { return } 123 replaceResults(Self.unique(loaded)) 124 state = results.isEmpty ? .empty : .loaded 125 } catch { 126 guard requestedGeneration == generation, generation.isActive, !Task.isCancelled else { return } 127 replaceResults([]) 128 state = .failed(Self.message(for: error)) 129 } 130 } 131 132 func stop() { 133 generation = generation.invalidated() 134 observation.stop() 135 observationState = .stopped 136 query = "" 137 replaceResults([]) 138 state = .idle 139 } 140 141 private func replaceResults(_ values: [TeraSearchResult]) { 142 mediaWillChange( 143 results.flatMap { supportingMedia(card: $0.card, profile: $0.profile) }, 144 values.flatMap { supportingMedia(card: $0.card, profile: $0.profile) }, context 145 ) 146 results = values 147 } 148 149 private static func unique(_ values: [TeraSearchResult]) -> [TeraSearchResult] { 150 var identifiers = Set<String>() 151 return values.filter { identifiers.insert("\($0.type):\($0.id)").inserted } 152 } 153 154 private static func message(for error: Error) -> String { 155 TeraUserMessages.text(for: error, fallback: .searchUnavailable) 156 } 157 } 158 159 @MainActor 160 final class TeraMeStore: ObservableObject { 161 @Published private(set) var snapshot: TeraMeSnapshot? 162 @Published private(set) var state: TeraSupportingLoadState = .idle 163 @Published private(set) var observationState: TeraRuntimeObservationState = .inactive 164 var mediaWillChange: ([TeraMediaReference], [TeraMediaReference], TeraLocalNetwork?) -> Void = { _, _, _ in } 165 166 private let runtimeClient: TeraRuntimeClient 167 private let clock: TeraClock 168 private let observationDelay: @Sendable (UInt32) async throws -> Void 169 private var context: TeraLocalNetwork? 170 private var generation = TeraSessionGeneration.initial 171 private let observation = TeraStoreObservation() 172 private var reloadTask: Task<Void, Never>? 173 174 deinit { reloadTask?.cancel() } 175 176 init( 177 runtimeClient: TeraRuntimeClient, 178 clock: TeraClock = .system, 179 observationDelay: @escaping @Sendable (UInt32) async throws -> Void = 180 TeraRuntimeObservationBackoff.sleep 181 ) { 182 self.runtimeClient = runtimeClient 183 self.clock = clock 184 self.observationDelay = observationDelay 185 } 186 187 func configure(context: TeraLocalNetwork?) { 188 guard self.context != context else { return } 189 generation = generation.invalidated() 190 reloadTask?.cancel() 191 reloadTask = nil 192 replaceSnapshot(nil) 193 self.context = context 194 state = .idle 195 if observation.isActive { 196 observation.stop() 197 startObservation() 198 } 199 } 200 201 func start() async { 202 startObservation() 203 reloadTask?.cancel() 204 reloadTask = Task { [weak self] in await self?.reload() } 205 let task = reloadTask 206 await withTaskCancellationHandler { await task?.value } onCancel: { task?.cancel() } 207 guard !Task.isCancelled else { return } 208 await observation.waitForRefresh() 209 } 210 211 func reload() async { 212 guard let context else { 213 replaceSnapshot(nil) 214 state = .failed("Choose a local network before loading your profile.") 215 return 216 } 217 generation = generation.invalidated() 218 let requestedGeneration = generation 219 if snapshot == nil { 220 state = .loading 221 } 222 do { 223 let loaded = try await runtimeClient.me( 224 context: context, 225 asOfUnixSeconds: clock.unixSeconds() 226 ) 227 guard requestedGeneration == generation, generation.isActive, !Task.isCancelled else { return } 228 replaceSnapshot(loaded) 229 state = loaded.cards.isEmpty && loaded.profile == nil ? .empty : .loaded 230 } catch { 231 guard requestedGeneration == generation, generation.isActive, !Task.isCancelled else { return } 232 if Self.refusesCurrentScope(error) { 233 replaceSnapshot(nil) 234 } 235 state = .failed(Self.message(for: error)) 236 } 237 } 238 239 func stop() { 240 generation = generation.invalidated() 241 observation.stop() 242 reloadTask?.cancel() 243 reloadTask = nil 244 observationState = .stopped 245 replaceSnapshot(nil) 246 state = .idle 247 } 248 249 func invalidatePresentation() { 250 generation = generation.invalidated() 251 reloadTask?.cancel() 252 replaceSnapshot(nil) 253 state = .idle 254 } 255 256 func currentCard(id: String, context: TeraLocalNetwork?) -> TeraTodayCard? { 257 guard self.context == context else { return nil } 258 return snapshot?.cards.first { $0.id == id } 259 } 260 261 func currentProfile(context: TeraLocalNetwork?) -> TeraProfileSummary? { 262 self.context == context ? snapshot?.profile : nil 263 } 264 265 func currentMedia(context: TeraLocalNetwork?) -> [TeraMediaReference] { 266 self.context == context ? Self.references(snapshot) : [] 267 } 268 269 private func replaceSnapshot(_ value: TeraMeSnapshot?) { 270 mediaWillChange(Self.references(snapshot), Self.references(value), context) 271 snapshot = value 272 } 273 274 private static func references(_ snapshot: TeraMeSnapshot?) -> [TeraMediaReference] { 275 (snapshot?.cards ?? []).flatMap { supportingMedia(card: $0, profile: nil) } 276 + supportingMedia(card: nil, profile: snapshot?.profile) 277 } 278 279 private func startObservation() { 280 observation.start( 281 client: runtimeClient, buffer: (capacity: 8, delay: observationDelay), 282 state: { [weak self] in self?.observationState = $0 }, 283 accepts: { [weak self] in $0.matches(context: self?.context) }, 284 invalidate: { [weak self] batch in 285 guard batch.contains(anyOf: [.today, .identity, .profile, .drafts]) else { return } 286 self?.invalidatePresentation() 287 }, 288 refresh: { [weak self] batch in 289 guard batch.contains(anyOf: [.today, .identity, .profile, .drafts]) else { return } 290 await self?.reloadTask?.value 291 guard !Task.isCancelled else { return } 292 await self?.reload() 293 } 294 ) 295 } 296 297 private static func refusesCurrentScope(_ error: Error) -> Bool { 298 switch TeraRuntimeClient.failure(from: error, operation: "me").code { 299 case "today_invalid_request", "today_refresh_required", "today_projection_rebuilding", 300 "today_cursor_invalid", "today_reader_unsupported", "today_runtime_unavailable", "today_state_failed", 301 "storage_space_insufficient": 302 true 303 default: 304 false 305 } 306 } 307 308 private static func message(for error: Error) -> String { 309 TeraUserMessages.text(for: error, fallback: .profileUnavailable) 310 } 311 } 312 313 private func supportingMedia(card: TeraTodayCard?, profile: TeraProfileSummary?) -> [TeraMediaReference] { 314 func references(_ value: TeraProfileSummary?) -> [TeraMediaReference] { 315 [value?.picture, value?.banner].compactMap(\.self) 316 } 317 return (card?.media ?? []) + references(card?.authorProfile) + references(profile) 318 + (card?.thread ?? []).flatMap { references($0.authorProfile) } 319 }