Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : Lou-Ka iOS9// File : LouKa/Core/Account/SyncEngine.swift10// Description : synchronisation des favoris (avec leurs notes) et des11// recherches enregistrées avec le compte. À la connexion :12// toute la mémoire locale est envoyée, la liste fusionnée du13// serveur la remplace. Ensuite chaque ajout, note ou retrait14// part aussitôt ; les retraits qui n'ont pas pu partir sont15// gardés avec leur date et rejoués. Nouvelle synchronisation16// au retour au premier plan et au retour du réseau. Sans17// compte, rien n'est envoyé.18// Module : LouKa19// Repository : https://git.spboucher.ai/lou-ka-ios-v320// Project Website : https://www.lou-ka.com21// Created : 2026-11-3022// Last Modified : 2026-11-3023//24// =============================================================================25// AUTHOR & PROFESSIONAL AFFILIATION26// =============================================================================27//28// Author : Simon-Pierre Boucher29// Position : Professor of Finance30// Institution : Université du Québec en Outaouais (UQO)31// Department : Département des sciences administratives32// Organization : SP Boucher33//34// Website : https://spboucher.ai35// Git : https://git.spboucher.ai36//37// =============================================================================38// OFFICIAL CONTACT DIRECTORY39// =============================================================================40//41// General : info@spboucher.ai42// Professional : contact@spboucher.ai43// Direct : simon@spboucher.ai44// Research : research@spboucher.ai45// Development : dev@spboucher.ai46// Support : support@spboucher.ai47// Security/Admin : admin@spboucher.ai48// Notifications : notifications@spboucher.ai49//50// Preferred Contact: support@spboucher.ai51//52// =============================================================================53// COPYRIGHT & INTELLECTUAL PROPERTY54// =============================================================================55//56// Copyright (c) 202657// Simon-Pierre Boucher58//59// All rights reserved where applicable.60//61// This file is governed by the applicable project license,62// copyright notices, institutional agreements and relevant law.63//64// Unless expressly authorized by the applicable license or65// rights holder, copying, redistribution, sublicensing,66// publication and commercial exploitation are not permitted.67//68// Existing third-party rights and notices remain unaffected.69//70// =============================================================================71// CONFIDENTIALITY & SECURITY72// =============================================================================73//74// Classification : Public75// Distribution : Public repository; use is governed by the project license76// Security Contact : admin@spboucher.ai77//78// Access to this source does not independently grant permission79// to redistribute or disclose confidential materials.80//81// Do not embed credentials, private keys, access tokens,82// certificates or confidential personal information.83//84// =============================================================================85// LICENSE & MAINTENANCE86// =============================================================================87//88// License : None specified (no license file in this repository)89// Maintainer : Simon-Pierre Boucher90// Technical Contact: dev@spboucher.ai91//92// =============================================================================93// END OF SP BOUCHER SOURCE HEADER94// =============================================================================9596import Foundation97import Network98import Observation99100/// Chaîne de requête d'une recherche enregistrée : mêmes paramètres que `/api/v3/search` et que l'adresse101/// `/recherche?…` du site (plus `sort`, et `nl` pour une phrase libre).102enum SearchQuery {103 struct Read: Equatable, Sendable {104 var filters: SearchFilters105 var sort: SearchSort106 var phrase: String?107 }108109 static func string(_ filters: SearchFilters, sort: SearchSort, phrase: String? = nil) -> String {110 var comps = URLComponents()111 var items = filters.query.compactMap { k, v -> URLQueryItem? in112 guard let v, !v.isEmpty else { return nil }113 return URLQueryItem(name: k, value: v)114 }115 if let phrase, !phrase.isEmpty { items.append(URLQueryItem(name: "nl", value: phrase)) }116 if sort != .pertinence { items.append(URLQueryItem(name: "sort", value: sort.apiValue)) }117 comps.queryItems = items.sorted { $0.name < $1.name }118 return (comps.percentEncodedQuery ?? "").replacingOccurrences(of: "+", with: "%2B")119 }120121 /// Relit une requête ; nil si un paramètre n'est pas représentable par l'app (la recherche n'est alors122 /// pas affichée : mieux vaut l'omettre que l'ouvrir autrement que son auteur ne l'a enregistrée).123 static func read(_ query: String) -> Read? {124 let q = query.hasPrefix("?") ? String(query.dropFirst()) : query125 var comps = URLComponents()126 comps.percentEncodedQuery = q.replacingOccurrences(of: "+", with: "%20")127 var params: [String: String] = [:]128 for item in comps.queryItems ?? [] {129 guard let v = item.value, !v.isEmpty else { continue }130 if params[item.name] != nil { return nil } // paramètre répété : forme inconnue de l'app131 params[item.name] = v132 }133 var sort = SearchSort.pertinence134 if let s = params.removeValue(forKey: "sort") {135 guard let known = SearchSort.allCases.first(where: { $0.apiValue == s }) else { return nil }136 sort = known137 }138 let phrase = params.removeValue(forKey: "nl")139 var f = SearchFilters()140 guard f.apply(params: params).isEmpty else { return nil }141 if f.rooms?.isEmpty == true { f.rooms = nil }142 if f.kinds?.isEmpty == true { f.kinds = nil }143 if f.features?.isEmpty == true { f.features = nil }144 return Read(filters: f, sort: sort, phrase: phrase)145 }146}147148/// Retraits faits pendant qu'un compte est connecté et pas encore confirmés par le serveur.149struct PendingRemovals: Codable, Equatable, Sendable {150 /// uid du favori → moment du retrait (ms)151 var favorites: [String: Int64] = [:]152 /// identifiant de la recherche → moment du retrait (ms)153 var searches: [String: Int64] = [:]154 var isEmpty: Bool { favorites.isEmpty && searches.isEmpty }155156 static let storeKey = "compte.retraits"157 static func load(_ defaults: UserDefaults?) -> PendingRemovals {158 guard let d = defaults?.data(forKey: storeKey) else { return PendingRemovals() }159 return (try? JSONDecoder().decode(PendingRemovals.self, from: d)) ?? PendingRemovals()160 }161 func save(_ defaults: UserDefaults?) {162 guard let defaults else { return }163 if isEmpty { defaults.removeObject(forKey: PendingRemovals.storeKey) } else { defaults.set(try? JSONEncoder().encode(self), forKey: PendingRemovals.storeKey) }164 }165}166167/// Règles de fusion côté appareil (pures, testées). Le serveur arbitre (la version la plus récente168/// l'emporte) ; l'appareil ne protège que ce qui a changé pendant l'aller-retour.169enum SyncLogic {170 static func favoriteRequest(local: [RemoteFavorite], pending: PendingRemovals) -> FavoriteSyncRequest {171 let present = Set(local.map(\.uid))172 return FavoriteSyncRequest(items: local,173 removed: pending.favorites.filter { !present.contains($0.key) }174 .map { RemovedFavorite(uid: $0.key, at: $0.value) }.sorted { $0.uid < $1.uid })175 }176177 static func searchRequest(local: [RemoteSearch], pending: PendingRemovals) -> SearchSyncRequest {178 let present = Set(local.map(\.id))179 return SearchSyncRequest(items: local,180 removed: pending.searches.filter { !present.contains($0.key) }181 .map { RemovedSearch(id: $0.key, at: $0.value) }.sorted { $0.id < $1.id })182 }183184 /// Éléments envoyés que le serveur a refusé de prendre (`skipped` : limite du compte atteinte, identifiant185 /// refusé). Rien ne dit lesquels : tant que `skipped` n'est pas nul, aucun élément local absent de la186 /// réponse n'est supprimé de l'appareil. Ils restent locaux, comme sans compte.187 static func refused(sent: [String], server: [String], skipped: Int?) -> Set<String> {188 guard (skipped ?? 0) > 0 else { return [] }189 return Set(sent).subtracting(server)190 }191192 /// Ce que l'appareil garde de la réponse : la liste du serveur, moins ce qui a été retiré ici pendant193 /// l'aller-retour ; `keep` = éléments modifiés ici pendant l'aller-retour (ils ne sont pas écrasés, et194 /// ne sont pas supprimés si le serveur ne les connaît pas encore). `again` : une nouvelle195 /// synchronisation doit suivre.196 static func settle<T>(server: [T], id: (T) -> String, changed: Set<String>, removed: Set<String>) -> (apply: [T], keep: Set<String>, again: Bool) {197 (server.filter { !removed.contains(id($0)) }, changed.subtracting(removed), !changed.isEmpty || !removed.isEmpty)198 }199}200201@MainActor202@Observable203final class SyncEngine {204 private let library: Library205 private let api: AccountAPI206 @ObservationIgnored private let defaults: UserDefaults?207 @ObservationIgnored var isSignedIn: () -> Bool = { false }208 @ObservationIgnored var onUnauthenticated: () -> Void = {}209210 private(set) var syncing = false211 private(set) var lastSync: Date?212 /// Dernier échec, en clair (nil : la dernière synchronisation a réussi).213 private(set) var lastError: String?214 private(set) var pending: PendingRemovals215216 @ObservationIgnored private var needsSync = false217 @ObservationIgnored private var again = false218 @ObservationIgnored private var monitor: NWPathMonitor?219 /// Changements faits ici pendant une synchronisation en cours (identifiants de favoris et de recherches).220 @ObservationIgnored private var flightChanged: Set<String> = []221 @ObservationIgnored private var flightRemoved: Set<String> = []222 /// Envois immédiats en cours (attendus par les tests).223 @ObservationIgnored private var pushes: [Task<Void, Never>] = []224225 /// `defaults` nil : les retraits en attente ne survivent pas au lancement (tests, base jetable).226 init(library: Library, api: AccountAPI, defaults: UserDefaults?) {227 self.library = library228 self.api = api229 self.defaults = defaults230 pending = PendingRemovals.load(defaults)231 library.onChange = { [weak self] change in self?.handle(change) }232 }233234 /// Relance une synchronisation quand le réseau revient après un envoi manqué.235 func watchNetwork() {236 guard monitor == nil else { return }237 let m = NWPathMonitor()238 m.pathUpdateHandler = { [weak self] path in239 guard path.status == .satisfied else { return }240 Task { @MainActor in241 guard let self, self.needsSync || !self.pending.isEmpty else { return }242 await self.sync()243 }244 }245 m.start(queue: .global(qos: .utility))246 monitor = m247 }248249 /// Déconnexion : plus rien n'est envoyé ; la mémoire locale reste telle quelle.250 func reset() {251 pending = PendingRemovals()252 pending.save(defaults)253 needsSync = false254 lastSync = nil255 lastError = nil256 }257258 /// Attend la fin des envois immédiats en cours.259 func settle() async {260 while !pushes.isEmpty {261 let t = pushes.removeFirst()262 await t.value263 }264 }265266 // MARK: Envois immédiats267268 private func handle(_ change: Library.Change) {269 guard isSignedIn() else { return }270 if syncing {271 switch change {272 case .favoriteSaved(let k), .searchSaved(let k): flightChanged.insert(k); flightRemoved.remove(k)273 case .favoriteRemoved(let k, _), .searchRemoved(let k, _): flightRemoved.insert(k); flightChanged.remove(k)274 }275 }276 switch change {277 case .favoriteSaved(let uid):278 if pending.favorites.removeValue(forKey: uid) != nil { pending.save(defaults) }279 guard let f = library.favorite(uid)?.remote else { return }280 push { try await $0.putFavorite(f) }281 case .favoriteRemoved(let uid, let at):282 let ms = Ms.from(at)283 pending.favorites[uid] = ms284 pending.save(defaults)285 push({ try await $0.deleteFavorite(uid) }, done: { me in286 if me.pending.favorites[uid] == ms { me.pending.favorites[uid] = nil; me.pending.save(me.defaults) }287 })288 case .searchSaved(let id):289 if pending.searches.removeValue(forKey: id) != nil { pending.save(defaults) }290 guard let s = library.allSearches().first(where: { $0.syncID == id })?.remote else { return }291 push { try await $0.putSearch(s) }292 case .searchRemoved(let id, let at):293 let ms = Ms.from(at)294 pending.searches[id] = ms295 pending.save(defaults)296 push({ try await $0.deleteSearch(id) }, done: { me in297 if me.pending.searches[id] == ms { me.pending.searches[id] = nil; me.pending.save(me.defaults) }298 })299 }300 }301302 private func push(_ call: @escaping @Sendable (AccountAPI) async throws -> Void, done: (@MainActor (SyncEngine) -> Void)? = nil) {303 let api = self.api304 let t = Task { @MainActor [weak self] in305 do {306 try await call(api)307 if let self { done?(self) }308 } catch {309 self?.failed(error)310 }311 }312 pushes.append(t)313 if pushes.count > 24 { pushes.removeFirst(pushes.count - 24) }314 }315316 private func failed(_ error: Error) {317 guard let e = error as? AccountError else { return }318 if e.isUnauthenticated { onUnauthenticated(); return }319 // tout autre échec (hors ligne, serveur) : la prochaine synchronisation rattrapera320 needsSync = true321 }322323 // MARK: Synchronisation complète324325 /// Synchronise si la dernière réussite date de plus de `minInterval` secondes (retour au premier plan).326 func syncIfStale(minInterval: TimeInterval = 20) async {327 if syncing { return }328 if let last = lastSync, Date().timeIntervalSince(last) < minInterval, !needsSync, pending.isEmpty { return }329 await sync()330 }331332 /// Envoie toute la mémoire locale et les retraits en attente ; la liste fusionnée devient la mémoire locale.333 func sync() async {334 guard isSignedIn() else { return }335 if syncing { again = true; return }336 syncing = true337 defer { syncing = false }338 var rounds = 0339 repeat {340 again = false341 rounds += 1342 do {343 try await round()344 lastSync = Date()345 lastError = nil346 needsSync = false347 } catch let e as AccountError {348 if e.isUnauthenticated { onUnauthenticated(); return }349 needsSync = true350 lastError = e.errorDescription351 return352 } catch {353 needsSync = true354 return355 }356 } while again && rounds < 3 && isSignedIn()357 }358359 private func round() async throws {360 flightChanged = []; flightRemoved = []361 let sent = pending362363 // favoris364 let favItems = library.allFavorites().map(\.remote)365 let favs = try await api.syncFavorites(items: favItems, removed: SyncLogic.favoriteRequest(local: favItems, pending: sent).removed)366 guard isSignedIn() else { return }367 let f = SyncLogic.settle(server: favs.items, id: \.uid, changed: flightChanged, removed: flightRemoved)368 library.replaceFavorites(with: f.apply, keep: f.keep.union(SyncLogic.refused(sent: favItems.map(\.uid), server: favs.items.map(\.uid), skipped: favs.skipped)))369 for (uid, at) in sent.favorites where pending.favorites[uid] == at { pending.favorites[uid] = nil }370 pending.save(defaults)371372 // recherches enregistrées373 let searchItems = library.allSearches().map(\.remote)374 let searches = try await api.syncSearches(items: searchItems, removed: SyncLogic.searchRequest(local: searchItems, pending: sent).removed)375 guard isSignedIn() else { return }376 let s = SyncLogic.settle(server: searches.items, id: \.id, changed: flightChanged, removed: flightRemoved)377 library.replaceSearches(with: s.apply, keep: s.keep.union(SyncLogic.refused(sent: searchItems.map(\.id), server: searches.items.map(\.id), skipped: searches.skipped)))378 for (id, at) in sent.searches where pending.searches[id] == at { pending.searches[id] = nil }379 pending.save(defaults)380381 if f.again || s.again { again = true }382 }383}384