Repository Public
1// SP Notes Core2// File: Tests/SPNotesSyncTests/RepositorySupportTests.swift3// Description: The shared behaviour of the repositories: the read-through cache and its policies, the typed errors4// (`.offline`, `.unsupported`, `.signedOut`…), and the merged search (local index + server).5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import SPNotesAPI10import SPNotesStore11import Testing12@testable import SPNotesSync13@testable import SPNotesTestSupport1415@Suite("Repositories: cache, errors, search (2.0)")16struct RepositorySupportTests {17 private struct Model: Codable, Sendable, Equatable { var n: Int; var at: Date }1819 @Test("read-through cache: network first, the cached copy with its fetch date when offline, and the four policies")20 func cachePolicies() async throws {21 let world = World(apiLevel: 3)22 let a = try world.device("A")23 let context = a.context24 let counter = Counter()25 let fetch: @Sendable () async throws -> Model = {26 let n = await counter.next()27 if await counter.offline { throw APIError.offline }28 return Model(n: n, at: Date(timeIntervalSince1970: 1_700_000_000))29 }30 await #expect(throws: RepositoryError.notCached) { try await context.read("test.model", policy: .cacheOnly, fetch: fetch) }31 let first = try await context.read("test.model", fetch: fetch)32 #expect(first.source == .network && first.value.n == 1)33 let again = try await context.read("test.model", policy: .cacheFirst(maxAge: 60), fetch: fetch)34 #expect(again.source == .cache && again.value == first.value, "fresh enough: no request, dates decoded back identically")35 #expect(await counter.count == 1)36 let stale = try await context.read("test.model", policy: .cacheFirst(maxAge: -1), fetch: fetch)37 #expect(stale.source == .network && stale.value.n == 2)3839 await counter.setOffline(true)40 let offline = try await context.read("test.model", fetch: fetch)41 #expect(offline.source == .cache && offline.value.n == 2)42 #expect(offline.fetchedAt == stale.fetchedAt || abs(offline.fetchedAt.timeIntervalSince(stale.fetchedAt)) < 0.01, "the fetch date is the one of the copy")43 #expect(!offline.isStale(maxAge: 3600) && offline.isStale(maxAge: 3600, now: Date().addingTimeInterval(7200)))44 await #expect(throws: RepositoryError.offline) { try await context.read("test.model", policy: .networkOnly, fetch: fetch) }45 await #expect(throws: RepositoryError.notCached) { try await context.read("test.other", fetch: fetch) }46 await world.closeAll()47 }4849 private actor Counter {50 var count = 051 var offline = false52 func next() -> Int { count += 1; return count }53 func setOffline(_ value: Bool) { offline = value }54 }5556 @Test("errors are typed: offline, signed out, unsupported, not found, and the server's code")57 func typedErrors() async throws {58 #expect(RepositoryError.from(APIError.offline) == .offline)59 #expect(RepositoryError.from(APIError.timeout) == .offline)60 #expect(RepositoryError.from(APIError.transport(.cannotConnectToHost)) == .offline)61 #expect(RepositoryError.from(APIError.http(status: 401, code: "unauthenticated", message: "Sign-in required", body: Data())) == .signedOut)62 #expect(RepositoryError.from(APIError.http(status: 501, code: "not_implemented", message: "no", body: Data())) == .unsupported(feature: "not_implemented"))63 #expect(RepositoryError.from(APIError.http(status: 404, code: "not_found", message: "Task not found", body: Data())) == .notFound("Task not found"))64 let refused = RepositoryError.from(APIError.http(status: 409, code: "relation_exists", message: "This relation already exists", body: Data(#"{"code":"relation_exists","id":"abc"}"#.utf8)))65 #expect(refused.code == "relation_exists")66 if case .server(let api) = refused { #expect(api.detailString("id") == "abc") } else { Issue.record("expected .server") }67 #expect(RepositoryError.from(StoreError.notFound("page x")) == .notFound("page x"))68 #expect(RepositoryError.offline.isOffline && RepositoryError.offline.errorDescription?.isEmpty == false)6970 // Features: unknown before the first cycle (nothing refused), known afterwards, and readable offline by a later session.71 let world = World(apiLevel: 2)72 let a = try world.device("A")73 #expect(await a.context.knownFeatures() == nil)74 try await a.context.require(ServerFeature.health)75 #expect(await a.sync() == .completed)76 #expect(await a.context.knownFeatures() == .legacy)77 await #expect(throws: RepositoryError.unsupported(feature: ServerFeature.health)) { try await a.context.require(ServerFeature.health) }78 try await a.restart()79 a.setOffline(true)80 #expect(await a.context.knownFeatures() == .legacy, "from the store cache, without the engine having run")81 await #expect(throws: RepositoryError.offline) { try await a.context.refreshFeatures() }82 await world.closeAll()83 }8485 @Test("search: local results at once; with the server, one merged list labelled local / server / both; a failing server never fails the search")86 func mergedSearch() async throws {87 let world = World(apiLevel: 3)88 let fake = world.fake89 let a = try world.device("A")90 let volatility = try await a.create("Volatilité conditionnelle", [("b1", "Le modèle GARCH de Bollerslev")])91 let other = try await a.create("Séries", [("b1", "Les données GARCH couvrent 2010 à 2025")])92 _ = try await a.create("Recette", [("b1", "Farine et beurre")])93 #expect(await a.sync() == .completed)94 let search = SearchRepository(context: a.context)9596 let local = try await search.local("garch")97 #expect(Set(local.map(\.pageId)) == [volatility, other])98 #expect(local.allSatisfy { $0.origin == .local && $0.localScore != nil && $0.page != nil })99100 // The server finds one of them (with the passage) and a page that is not on this device (semantic match).101 let remoteOnly = UUID().uuidString.lowercased()102 fake.stub("GET", path: "^/api/search$") { request in103 guard request.query["mode"] == "hybrid", request.query["q"] == "garch" else { return .error(400) }104 return .json("""105 [{"pageId":"\(volatility)","title":"Volatilité conditionnelle","heading":"Modèles","blockId":"b1","content":"Le modèle GARCH","snippet":"Le modèle \\u0001GARCH\\u0002","score":0.031,"kind":"page"},106 {"pageId":"\(remoteOnly)","title":"Hétéroscédasticité","blockId":"zz","snippet":"variance non constante","score":0.016,"kind":"page"}]107 """)108 }109 let outcome = try await search.search("garch", scope: .hybrid)110 #expect(outcome.usedServer && outcome.serverError == nil)111 #expect(outcome.results.first?.pageId == volatility, "found by both: first")112 let byPage = Dictionary(uniqueKeysWithValues: outcome.results.map { ($0.pageId, $0) })113 #expect(byPage[volatility]?.origin == .both && byPage[volatility]?.blockId == "b1" && byPage[volatility]?.heading == "Modèles")114 #expect(byPage[other]?.origin == .local)115 #expect(byPage[remoteOnly]?.origin == .server && byPage[remoteOnly]?.page == nil && byPage[remoteOnly]?.title == "Hétéroscédasticité")116 #expect(byPage[volatility]?.snippet.contains(SPNotesStore.SearchHit.highlightStart) == true)117 #expect(outcome.results.count == 3)118 #expect(fake.count("GET", "^/api/search\\?") == 1)119120 // Local only: no request. Offline or a failing server: the local list, and the reason.121 fake.clearLog()122 #expect(try await search.search("garch", scope: .localOnly).usedServer == false)123 #expect(fake.count("GET", "^/api/search") == 0)124 a.setOffline(true)125 let offline = try await search.search("garch")126 #expect(!offline.usedServer && offline.serverError == .offline && Set(offline.results.map(\.pageId)) == [volatility, other])127 a.setOffline(false)128 fake.inject(.status(503, code: "not_configured"), method: "GET", path: "^/api/search")129 let degraded = try await search.search("garch")130 #expect(!degraded.usedServer && degraded.serverError?.code == "not_configured" && degraded.results.count == 2)131 // The lexical-only server scope says so in the request.132 fake.clearLog()133 _ = try await search.search("garch")134 #expect(fake.count("GET", "semantic=0") == 1, "the default never asks for the paid embedding")135 await world.closeAll()136 }137}138