Repository Public
1// SP Drive iOS2// File: KitTests/EngineNextTests.swift3// Description: Sync engine 2.0 — tests of each policy against the real backend: Wi-Fi only, Low Data Mode, Low Power Mode and battery,4// priorities, retries with backoff, adaptive concurrency, crash-safe recovery, selective offline, the change listener,5// offline-first work and the description of conflicts. The pure decision logic is tested without a server.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import Foundation10import Testing11@testable import SPDriveKit1213// MARK: Pure logic (no server)1415@Suite struct PolicyLogicTests {16 @Test func policyMatrix() {17 let p = TransferPolicy.default18 #expect(p.evaluate(.ideal) == .init(limit: 6, userHold: nil, backgroundHold: nil))19 #expect(p.evaluate(.init(online: false)) == .init(limit: 0, userHold: .offline, backgroundHold: .offline))20 // cellular allowed by default, fewer at once21 #expect(p.evaluate(.init(expensive: true)) == .init(limit: 2, userHold: nil, backgroundHold: nil))22 // Wi-Fi only: everything waits, unless the user exempts a transfer23 let wifiOnly = TransferPolicy(allowCellular: false)24 let held = wifiOnly.evaluate(.init(expensive: true))25 #expect(held.userHold == .waitingForWiFi && held.backgroundHold == .waitingForWiFi)26 #expect(held.hold(userInitiated: true, exemptFromWiFiOnly: true) == nil)27 #expect(wifiOnly.evaluate(.ideal).userHold == nil)28 // Low Data Mode: one at a time, background work waits, the user's own transfers go29 let low = p.evaluate(.init(constrained: true))30 #expect(low == .init(limit: 1, userHold: nil, backgroundHold: .lowDataMode))31 #expect(TransferPolicy(backgroundInLowDataMode: true).evaluate(.init(constrained: true)).backgroundHold == nil)32 // Low Power Mode and battery only ever hold background work33 #expect(p.evaluate(.init(lowPowerMode: true)) == .init(limit: 2, userHold: nil, backgroundHold: .lowPowerMode))34 #expect(p.evaluate(.init(batteryLevel: 0.1)).backgroundHold == .lowBattery)35 #expect(p.evaluate(.init(batteryLevel: 0.1, charging: true)).backgroundHold == nil)36 #expect(p.evaluate(.init(batteryLevel: 0.5)).backgroundHold == nil)37 #expect(p.evaluate(.init(batteryLevel: nil)).backgroundHold == nil) // unknown level (simulator) never blocks38 #expect(TransferPolicy(batteryFloor: 0).evaluate(.init(batteryLevel: 0.01)).backgroundHold == nil)39 // the most specific reason wins when several apply40 #expect(wifiOnly.evaluate(.init(expensive: true, constrained: true, lowPowerMode: true)).backgroundHold == .waitingForWiFi)41 }4243 @Test func backoffGrowsIsCappedAndJittered() {44 for n in 0..<12 {45 let step = min(60, 0.5 * pow(2, Double(n)))46 #expect(Backoff.delay(attempt: n, unit: 0) == step / 2)47 #expect(Backoff.delay(attempt: n, unit: 1) == step)48 let d = Backoff.delay(attempt: n)49 #expect(d >= step / 2 && d <= step)50 }51 #expect(Backoff.delay(attempt: 500, unit: 1) == 60)52 #expect(Backoff.delay(attempt: 0, base: 1, cap: 60, unit: 1) == 1) // reconnection of the event stream: 1 s → 60 s53 #expect(Set((0..<40).map { _ in Backoff.delay(attempt: 5) }).count > 1)54 }5556 @Test func adaptiveConcurrencyFollowsThroughputAndErrors() {57 // each added transfer adds throughput: the limit climbs to the top58 var a = AdaptiveConcurrency(initial: 3)59 for _ in 0..<40 { a.recordSuccess(bytes: 8 << 20, seconds: 1, active: a.limit) }60 #expect(a.limit == 6)6162 // the path is saturated: a fourth transfer buys nothing, the controller comes back to three and stays63 var b = AdaptiveConcurrency(initial: 3)64 for _ in 0..<4 { b.recordSuccess(bytes: 8 << 20, seconds: 1, active: 3) }65 #expect(b.limit == 4)66 for _ in 0..<4 { b.recordSuccess(bytes: 6 << 20, seconds: 1, active: 4) } // same total as before67 #expect(b.limit == 3)68 for _ in 0..<20 { b.recordSuccess(bytes: 8 << 20, seconds: 1, active: 3) }69 #expect(b.limit == 3)7071 // errors: halved, never below one72 var c = AdaptiveConcurrency(initial: 6)73 for _ in 0..<3 { c.recordFailure() }74 #expect(c.limit == 3)75 for _ in 0..<3 { c.recordFailure() }76 #expect(c.limit == 1)77 for _ in 0..<9 { c.recordFailure() }78 #expect(c.limit == 1)79 // small transfers say nothing about throughput80 var d = AdaptiveConcurrency(initial: 2)81 for _ in 0..<50 { d.recordSuccess(bytes: 2000, seconds: 0.01, active: 2) }82 #expect(d.limit == 2)83 // an isolated error among successes changes nothing84 var e = AdaptiveConcurrency(initial: 4)85 e.recordFailure()86 for _ in 0..<3 { e.recordSuccess(bytes: 100, seconds: 1, active: 1) }87 #expect(e.limit == 4)88 }89}9091// MARK: Against the backend9293@Suite(.enabled(if: TestEnv.available, "disposable backend not running: Scripts/test-server.sh up"), .serialized)94struct EngineNextTests {95 func upload(_ d: Device, _ name: String, _ data: Data, into parent: String) async throws -> DriveItem {96 _ = try await d.engine.importFile(at: d.tempFile(name, data), into: parent)97 await d.settle()98 return try #require(d.child(name, of: parent))99 }100101 @Test func wifiOnlyHoldsTransfersOnCellularAndReleasesThemOnWiFi() async throws {102 let a = try await Device(), b = try await Device(host: "127.0.0.1")103 let ws = try await a.workspace("wifi")104 await a.setPolicy { $0.allowCellular = false }105 await a.set { $0.expensive = true }106107 let first = try await a.engine.importFile(at: a.tempFile("un.bin", randomData(40_000)), into: ws.id)108 let second = try await a.engine.importFile(at: a.tempFile("deux.bin", randomData(40_000)), into: ws.id)109 // metadata is light and still travels: a folder created on cellular reaches the server110 _ = try await a.engine.createFolder(name: "Sur cellulaire", in: ws.id)111 await a.engine.sync()112 try await Task.sleep(for: .milliseconds(400))113 let t1 = try #require(a.store.activeTransfer(itemID: first.id, kind: .upload)), t2 = try #require(a.store.activeTransfer(itemID: second.id, kind: .upload))114 #expect(t1.state == .queued && t2.state == .queued)115 #expect(await a.engine.hold(of: t1.id) == .waitingForWiFi)116 #expect(a.engine.badge(for: first) == .waiting)117 await b.engine.sync()118 #expect(b.child("Sur cellulaire", of: ws.id) != nil)119 #expect(b.child("un.bin", of: ws.id) == nil && b.child("deux.bin", of: ws.id) == nil)120121 // the request itself carries the restriction, so the system enforces it even when the app is suspended122 let shaped = await a.engine.shape(URLRequest(url: URL(string: "http://localhost:8663/x")!), for: t1)123 #expect(shaped.allowsExpensiveNetworkAccess == false && shaped.allowsCellularAccess == false)124125 // « use cellular this once » for one transfer: it goes, the other still waits126 await a.engine.allowOnCellular([t2.id])127 #expect(await eventually { a.store.transfer(t2.id)?.state == .done })128 #expect(a.store.transfer(t1.id)?.state == .queued)129130 // Wi-Fi is back131 await a.set { $0.expensive = false }132 await a.settle()133 #expect(await a.engine.currentHolds().isEmpty)134 await b.engine.sync()135 #expect(b.child("un.bin", of: ws.id) != nil && b.child("deux.bin", of: ws.id) != nil)136 }137138 @Test func runningTransferGoesBackToTheQueueWhenThePathBecomesCellular() async throws {139 let a = try await Device()140 let ws = try await a.workspace("path")141 await a.setPolicy { $0.allowCellular = false }142 NetworkGate.stall("offset=0", true)143 defer { NetworkGate.stall("offset=0", false) }144 let item = try await a.engine.importFile(at: a.tempFile("en-route.bin", randomData(300_000)), into: ws.id)145 await a.engine.sync()146 #expect(await eventually { a.store.activeTransfer(itemID: item.id, kind: .upload)?.state == .running && NetworkGate.seen.withLock { $0["offset=0", default: 0] } > 0 })147 let t = try #require(a.store.activeTransfer(itemID: item.id, kind: .upload))148149 await a.set { $0.expensive = true } // left the Wi-Fi while a block was travelling150 #expect(a.store.transfer(t.id)?.state == .queued) // waiting, not « paused »: the user asked for nothing151 #expect(await a.engine.hold(of: t.id) == .waitingForWiFi)152 #expect(a.store.transfer(t.id)?.uploadID != nil) // the server-side session is kept for the resumption153154 NetworkGate.stall("offset=0", false)155 await a.set { $0.expensive = false }156 await a.settle()157 #expect(a.store.transfer(t.id)?.state == .done)158 #expect(a.child("en-route.bin", of: ws.id)?.pending == false)159 }160161 @Test func lowDataModeLowPowerModeAndBatteryHoldBackgroundWorkOnly() async throws {162 let a = try await Device(), b = try await Device(host: "127.0.0.1")163 let ws = try await a.workspace("power")164 let pinned = try await upload(a, "fond.bin", randomData(30_000), into: ws.id)165 let wanted = try await upload(a, "voulu.bin", randomData(30_000), into: ws.id)166 await b.engine.sync()167168 // Low Data Mode: the pin (background) waits, the file the user opens arrives169 await b.set { $0.constrained = true }170 try await b.engine.pin(pinned.id)171 try await Task.sleep(for: .milliseconds(300))172 let tp = try #require(b.store.activeTransfer(itemID: pinned.id, kind: .download))173 #expect(tp.state == .queued)174 #expect(await b.engine.hold(of: tp.id) == .lowDataMode)175 #expect(b.engine.badge(for: pinned) == .waitingDownload)176 _ = try await b.engine.localCopy(of: wanted.id)177 #expect(b.engine.badge(for: wanted) == .available)178 #expect(b.store.transfer(tp.id)?.state == .queued)179 #expect(await b.engine.concurrencyState().effective == 1)180181 // Low Power Mode, then a low battery: same file, other reasons182 await b.set { $0.constrained = false; $0.lowPowerMode = true }183 #expect(await b.engine.hold(of: tp.id) == .lowPowerMode)184 await b.set { $0.lowPowerMode = false; $0.batteryLevel = 0.08 }185 #expect(await b.engine.hold(of: tp.id) == .lowBattery)186 #expect(b.store.transfer(tp.id)?.state == .queued)187188 // the user opens the held file: it becomes user-initiated and is no longer background work189 _ = try await b.engine.localCopy(of: pinned.id)190 #expect(b.engine.badge(for: pinned) == .pinned)191192 // plugged in: background work resumes on its own193 let later = try await upload(a, "plus-tard.bin", randomData(20_000), into: ws.id)194 await b.engine.sync()195 try await b.engine.pin(later.id)196 try await Task.sleep(for: .milliseconds(200))197 #expect(await b.engine.currentHolds().values.contains(.lowBattery))198 await b.set { $0.charging = true }199 await b.settle()200 #expect(b.engine.badge(for: later) == .pinned)201 }202203 @Test func userInitiatedTransferTakesTheSlotOfABackgroundOne() async throws {204 let a = try await Device(), b = try await Device(host: "127.0.0.1", concurrency: 1)205 let ws = try await a.workspace("prio")206 let big = try await upload(a, "gros.bin", randomData(900_000), into: ws.id)207 let small = try await upload(a, "petit.txt", Data("vite".utf8), into: ws.id)208 await b.engine.sync()209 let key = "files/\(big.id)/content"210 NetworkGate.stall(key, true)211 defer { NetworkGate.stall(key, false) }212 try await b.engine.pin(big.id)213 #expect(await eventually { b.store.activeTransfer(itemID: big.id, kind: .download)?.state == .running && NetworkGate.seen.withLock { $0[key, default: 0] } > 0 })214215 // one slot, taken by a background download that hangs: the file the user asks for must not wait behind it216 let url = try await b.engine.localCopy(of: small.id)217 #expect(try Data(contentsOf: url) == Data("vite".utf8))218 #expect(b.store.localState(big.id)?.hasCopy != true)219220 NetworkGate.stall(key, false)221 await b.settle()222 #expect(b.engine.badge(for: big) == .pinned)223 }224225 @Test func retriesBackOffExponentiallyAndErrorsLowerTheConcurrency() async throws {226 let a = try await Device()227 let ws = try await a.workspace("retry")228 await a.engine.setJitter { 1 } // upper bound of each step: 0.5 s, 1 s, 2 s229 #expect(await a.engine.concurrencyState().adaptive == 3)230 NetworkGate.failNext(3, pathContaining: "offset=0", code: .timedOut)231 let started = Date.now232 let item = try await a.engine.importFile(at: a.tempFile("tenace.bin", randomData(60_000)), into: ws.id)233 await a.engine.sync()234 #expect(await eventually(5) { await a.engine.retryDelay(of: a.store.activeTransfer(itemID: item.id, kind: .upload)?.id ?? "") != nil })235 await a.settle()236 let elapsed = Date.now.timeIntervalSince(started)237 #expect(elapsed >= 3.4, "three retries wait 0.5 + 1 + 2 s, waited \(elapsed)")238 #expect(elapsed < 20)239 #expect(a.child("tenace.bin", of: ws.id)?.pending == false)240 // three timeouts in a row: the controller halves the number of simultaneous transfers241 #expect(await a.engine.concurrencyState().adaptive == 1)242 // being offline is not an error of the path243 let b = try await Device(host: "127.0.0.1")244 await b.engine.sync()245 b.setOffline(true)246 defer { NetworkGate.set("127.0.0.1", offline: false) }247 _ = try await b.engine.importFile(at: b.tempFile("x.bin", randomData(10)), into: ws.id)248 await b.engine.sync()249 try await Task.sleep(for: .milliseconds(700))250 #expect(await b.engine.concurrencyState().adaptive == 3)251 b.setOffline(false)252 await b.settle()253 }254255 @Test func downloadFinishedWhileTheAppWasDeadIsAdoptedNotFetchedAgain() async throws {256 let a = try await Device()257 let ws = try await a.workspace("crash-down")258 let data = randomData(400_000)259 let item = try await upload(a, "survivant.bin", data, into: ws.id)260261 // first life: the system finishes the download, but the process dies before hearing about it262 let dying = Shared<ScriptedDriver?>(nil)263 let b = try await Device(host: "127.0.0.1", driver: { staging, config in let d = ScriptedDriver(staging: staging, configuration: config, deliver: 0); dying.withLock { $0 = d }; return d })264 await b.engine.sync()265 try await b.engine.pin(item.id)266 let first = try #require(dying.withLock { $0 })267 #expect(await eventually { !first.captured.isEmpty })268 let t = try #require(b.store.activeTransfer(itemID: item.id, kind: .download))269 #expect(t.state == .running) // what the database says when the process is killed270 #expect(b.store.localState(item.id)?.hasCopy != true)271272 // second life: the system hands the finished task back at launch273 let reborn = Shared<ScriptedDriver?>(nil)274 let captured = first.captured275 let b2 = try await b.relaunched(driver: { staging, config in let d = ScriptedDriver(staging: staging, configuration: config, replay: captured); reborn.withLock { $0 = d }; return d })276 #expect(await eventually { b2.store.transfer(t.id)?.state == .done })277 let second = try #require(reborn.withLock { $0 })278 #expect(second.downloads == 0, "the bytes were already on the device: nothing may be fetched twice")279 #expect(try Data(contentsOf: try #require(b2.store.localState(item.id).flatMap(b2.files.url(for:)))) == data)280 #expect(b2.engine.badge(for: item) == .pinned)281 }282283 @Test func uploadInterruptedByACrashResumesFromTheServersOffset() async throws {284 let dying = Shared<ScriptedDriver?>(nil)285 let a = try await Device(driver: { staging, config in let d = ScriptedDriver(staging: staging, configuration: config, deliver: 1); dying.withLock { $0 = d }; return d })286 let ws = try await a.workspace("crash-up")287 let data = randomData(20 * 1024 * 1024 + 777) // three blocks288 let item = try await a.engine.importFile(at: a.tempFile("long.bin", data), into: ws.id)289 await a.engine.sync()290 let first = try #require(dying.withLock { $0 })291 // the first block was acknowledged, the second was handed over… and the process died292 #expect(await eventually(60) { first.ignored >= 1 })293 let t = try #require(a.store.activeTransfer(itemID: item.id, kind: .upload))294 let session = try #require(t.uploadID)295 #expect(t.state == .running && t.done == 8 * 1024 * 1024)296297 let reborn = Shared<ScriptedDriver?>(nil)298 let a2 = try await a.relaunched(driver: { staging, config in let d = ScriptedDriver(staging: staging, configuration: config); reborn.withLock { $0 = d }; return d })299 await a2.settle(timeout: 120)300 let done = try #require(a2.store.transfer(t.id))301 #expect(done.state == .done)302 #expect(done.uploadID == session, "the same server-side session is continued")303 #expect(try #require(reborn.withLock { $0 }).uploads == 2, "only the two missing blocks travel")304 #expect(a2.child("long.bin", of: ws.id)?.sha256 == IntegrityVerifier.sha256(data))305 #expect(a2.store.ops().isEmpty)306 }307308 @Test func selectiveOfflineStaysConsistentWhenItemsMove() async throws {309 let a = try await Device(), b = try await Device(host: "127.0.0.1")310 let ws = try await a.workspace("pins")311 let kept = try await a.engine.createFolder(name: "Gardé", in: ws.id)312 await a.settle()313 let folder = try #require(a.child("Gardé", of: ws.id))314 _ = kept315 let inside = try await upload(a, "dedans.txt", Data("dedans".utf8), into: folder.id)316 let outside = try await upload(a, "dehors.txt", Data("dehors".utf8), into: ws.id)317 await b.engine.sync()318 try await b.engine.pin(folder.id)319 await b.settle()320 #expect(b.engine.pinStatus(of: folder.id) == .init(files: 1, availableFiles: 1, bytes: 6, availableBytes: 6))321 _ = try await b.engine.localCopy(of: outside.id) // an ordinary cached copy322 #expect(b.store.localState(outside.id)?.location == .cache)323324 // offline: move one file out of the kept folder and the other one in325 b.setOffline(true)326 defer { NetworkGate.set("127.0.0.1", offline: false) }327 try await b.engine.move([inside.id], to: ws.id)328 try await b.engine.move([outside.id], to: folder.id)329 #expect(b.store.localState(inside.id)?.location == .cache) // no longer covered by a pin: an ordinary copy again330 #expect(b.store.localState(outside.id)?.location == .offline) // now covered: kept for good331 #expect(b.engine.badge(for: try #require(b.store.item(outside.id))) == .waiting) // the move itself is still to be sent332 #expect(try Data(contentsOf: try await b.engine.localCopy(of: outside.id)) == Data("dehors".utf8))333 b.setOffline(false)334 await b.settle()335 #expect(b.engine.badge(for: try #require(b.store.item(outside.id))) == .pinned)336 #expect(b.engine.badge(for: try #require(b.store.item(inside.id))) == .available)337338 // a file arriving in the kept folder from elsewhere, and a sub-folder pinned then unpinned inside a pinned folder339 let sub = try await a.engine.createFolder(name: "Sous-dossier", in: folder.id)340 await a.settle()341 let subID = try #require(a.child(sub.name, of: folder.id)).id342 let deep = try await upload(a, "profond.txt", Data("profond".utf8), into: subID)343 await b.settle()344 #expect(b.engine.badge(for: deep) == .pinned)345 try await b.engine.pin(subID)346 await b.engine.unpin(subID)347 await b.settle()348 #expect(b.engine.badge(for: deep) == .pinned, "still covered by the parent's pin")349 #expect(b.engine.pinStatus(of: folder.id).isComplete)350351 // unpinning the folder frees the copies and touches nothing on the Drive352 await b.engine.unpin(folder.id)353 #expect(b.store.localState(deep.id)?.hasCopy != true)354 await a.engine.sync()355 #expect(a.store.item(deep.id)?.isTrashed == false)356 }357358 @Test func offlineFirstBrowseEditQueueThenReconnect() async throws {359 let a = try await Device(), b = try await Device(host: "127.0.0.1")360 let ws = try await a.workspace("offline-first")361 let report = try await upload(a, "rapport.txt", Data("v1".utf8), into: ws.id)362 let photo = try await upload(a, "photo.jpg", randomData(12_000), into: ws.id)363 let archive = try await a.engine.createFolder(name: "Archives", in: ws.id)364 await a.settle()365 let archiveID = try #require(a.child(archive.name, of: ws.id)).id366 await b.engine.sync()367 try await b.engine.pin(report.id)368 await b.settle()369370 b.setOffline(true)371 defer { NetworkGate.set("127.0.0.1", offline: false) }372 await b.engine.sync()373 #expect(await b.engine.status == .offline)374 // browse the cached metadata, search it375 #expect(Set(b.store.children(of: ws.id).map(\.name)) == ["Archives", "rapport.txt", "photo.jpg"])376 #expect(b.store.search(text: "rapp", within: ws.id).map(\.name) == ["rapport.txt"])377 // a pinned file opens; a file that is not on the device says so clearly instead of spinning378 #expect(try Data(contentsOf: try await b.engine.localCopy(of: report.id)) == Data("v1".utf8))379 #expect(b.engine.badge(for: report, online: false) == .pinned)380 #expect(b.engine.badge(for: photo, online: false) == .unavailableOffline)381 await #expect(throws: EngineError.notAvailableOffline) { _ = try await b.engine.localCopy(of: photo.id) }382383 // rename, move, create a folder, favourite, queue an upload — all through the journal384 try await b.engine.rename(report.id, to: "rapport final.txt")385 try await b.engine.move([photo.id], to: archiveID)386 let created = try await b.engine.createFolder(name: "Nouveau", in: ws.id)387 try await b.engine.setStarred([archiveID], true)388 let queued = try await b.engine.importFile(at: b.tempFile("note.md", Data("écrit sans réseau".utf8)), into: created.id)389 // the interface already shows the result, each item with its state390 #expect(b.child("rapport final.txt", of: ws.id)?.pending == true)391 #expect(b.child("photo.jpg", of: archiveID) != nil)392 #expect(b.store.item(archiveID)?.starred == true)393 #expect(b.engine.badge(for: queued) == .waiting)394 #expect(b.store.ops().map(\.kind) == [.rename, .move, .createFolder, .star, .uploadNew])395 // nothing reached the server396 await a.engine.sync()397 #expect(a.child("rapport.txt", of: ws.id) != nil && a.child("Nouveau", of: ws.id) == nil)398399 b.setOffline(false)400 await b.engine.networkBecameAvailable()401 await b.settle()402 #expect(b.store.ops().isEmpty)403 await a.engine.sync()404 #expect(a.child("rapport final.txt", of: ws.id)?.id == report.id)405 #expect(a.child("photo.jpg", of: archiveID)?.id == photo.id)406 #expect(a.store.item(archiveID)?.starred == true)407 let nouveau = try #require(a.child("Nouveau", of: ws.id))408 #expect(a.child("note.md", of: nouveau.id)?.sha256 == IntegrityVerifier.sha256(Data("écrit sans réseau".utf8)))409 #expect(b.child("note.md", of: nouveau.id)?.pending == false)410 }411412 @Test func conflictIsDescribedOnBothSidesAndNeverOverwrittenSilently() async throws {413 let a = try await Device(), b = try await Device(host: "127.0.0.1")414 let ws = try await a.workspace("sides")415 let item = try await upload(a, "contrat.txt", Data("version de départ".utf8), into: ws.id)416 await b.engine.sync()417 try await a.engine.pin(item.id)418 await a.settle()419420 a.setOffline(true)421 defer { NetworkGate.set("localhost", offline: false) }422 let mine = Data("ma version, plus longue que l’autre".utf8)423 try mine.write(to: try await a.engine.localCopy(of: item.id))424 try await a.engine.noteLocalEdit(item.id)425 let theirs = Data("version du serveur".utf8)426 try await b.engine.replaceContent(of: item.id, with: b.tempFile("contrat.txt", theirs))427 await b.settle()428 a.setOffline(false)429 await a.engine.sync()430 #expect(await eventually { a.store.conflicts().count == 1 })431432 let c = try #require(a.store.conflicts().first)433 #expect(c.reason == .bothModified)434 let sides = try #require(await a.engine.conflictSides(c.id))435 let local = try #require(sides.local), server = try #require(sides.server)436 #expect(sides.serverReachable)437 #expect(local.size == Int64(mine.count) && local.baseVersionID == item.versionID)438 #expect(local.modifiedAt != nil)439 #expect(server.size == Int64(theirs.count) && server.versionSeq == 2)440 #expect(server.item.sha256 == IntegrityVerifier.sha256(theirs))441 // until the user chooses: the Drive holds the other device's version, this device holds its own, syncing again changes nothing442 await a.settle()443 #expect(try await a.api.fileDetail(id: item.id).item.sha256 == IntegrityVerifier.sha256(theirs))444 #expect(try Data(contentsOf: local.url) == mine)445 #expect(a.store.conflicts().count == 1)446 // unreachable server: the mirror's knowledge is shown, flagged as such447 a.setOffline(true)448 let blind = try #require(await a.engine.conflictSides(c.id))449 #expect(!blind.serverReachable && blind.local?.size == Int64(mine.count))450 a.setOffline(false)451452 // « keep mine as a new version »: the server's version stays in the history453 try await a.engine.resolve(c.id, choice: .keepMine, deviceName: "iPhone de test")454 await a.settle()455 let detail = try await a.api.fileDetail(id: item.id)456 #expect(detail.item.sha256 == IntegrityVerifier.sha256(mine))457 #expect(detail.versions.count == 3 && detail.versions.contains { $0.sha256 == IntegrityVerifier.sha256(theirs) })458 #expect(await a.engine.conflictSides(c.id) == nil)459460 // deleted on the Drive while edited here: there is no server side to show461 try Data("encore modifié".utf8).write(to: try await a.engine.localCopy(of: item.id))462 a.setOffline(true)463 try await a.engine.noteLocalEdit(item.id)464 await b.engine.sync()465 try await b.engine.trash([item.id])466 await b.settle()467 a.setOffline(false)468 await a.engine.sync()469 #expect(await eventually { a.store.conflicts().first?.reason == .remoteDeleted })470 let goneID = try #require(a.store.conflicts().first).id471 let gone = try #require(await a.engine.conflictSides(goneID))472 #expect(gone.server == nil && gone.serverReachable && gone.local != nil)473 try await a.engine.resolve(gone.conflict.id, choice: .keepServer, deviceName: "iPhone de test")474 #expect(a.store.conflicts().isEmpty)475 }476477 @Test func changeListenerUsesHintsFallsBackToPollingAndReconnects() async throws {478 let a = try await Device(), b = try await Device(host: "127.0.0.1")479 let ws = try await a.workspace("events")480 await b.engine.sync()481 let source = FakeEventSource()482 let listener = ChangeListener(source: source, configuration: .init(pollInterval: .milliseconds(250), safetyInterval: .seconds(600), reconnectBase: 0.05, reconnectCap: 0.4)) { await b.engine.sync() }483 await listener.start()484 #expect(await eventually { source.connections == 1 })485 #expect(await listener.mode == .polling) // not « streaming » before the server said hello486 source.send(.connected(head: 1))487 #expect(await eventually { await listener.mode == .streaming })488489 // streaming: a hint brings the change at once (the safety poll is ten minutes away)490 _ = try await a.engine.createFolder(name: "Par évènement", in: ws.id)491 await a.settle()492 try await Task.sleep(for: .milliseconds(600))493 #expect(b.child("Par évènement", of: ws.id) == nil, "no hint, no poll: not fetched yet")494 source.send(.changed(head: 2))495 #expect(await eventually(5) { b.child("Par évènement", of: ws.id) != nil })496497 // the stream breaks: polling takes over, and the listener keeps trying to reconnect, with growing delays498 source.accept = false499 source.breakStream()500 #expect(await eventually { await listener.mode == .polling })501 _ = try await a.engine.createFolder(name: "Par sondage", in: ws.id)502 await a.settle()503 #expect(await eventually(5) { b.child("Par sondage", of: ws.id) != nil })504 #expect(await eventually(5) { source.connections >= 4 })505 let gaps = zip(source.attemptTimes, source.attemptTimes.dropFirst()).map { $1.timeIntervalSince($0) }506 #expect(gaps.dropFirst().allSatisfy { $0 <= 0.6 }, "capped: \(gaps)")507 #expect((gaps.dropFirst().max() ?? 0) > (gaps.dropFirst().first ?? 1) * 1.2 || gaps.count < 4, "growing: \(gaps)")508509 // the stream comes back510 source.accept = true511 #expect(await eventually(5) { source.live })512 source.send(.connected(head: 9))513 #expect(await eventually { await listener.mode == .streaming })514 await listener.stop()515 #expect(await listener.mode == .stopped)516517 // no source at all (a 1.0 server): polling only518 let plain = ChangeListener(source: nil, configuration: .init(pollInterval: .milliseconds(200))) { await b.engine.sync() }519 await plain.start()520 _ = try await a.engine.createFolder(name: "Sans flux", in: ws.id)521 await a.settle()522 #expect(await eventually(5) { b.child("Sans flux", of: ws.id) != nil })523 await plain.stop()524 }525}526527/// A controllable stand-in for the server's event stream (the stream itself arrives with the 2.0 backend).528final class FakeEventSource: ChangeEventSource, @unchecked Sendable {529 private let lock = NSLock()530 private var continuation: AsyncThrowingStream<ChangeHint, Error>.Continuation?531 private var _connections = 0532 private var _times: [Date] = []533 private var _accept = true534 var connections: Int { lock.lock(); defer { lock.unlock() }; return _connections }535 var attemptTimes: [Date] { lock.lock(); defer { lock.unlock() }; return _times }536 var live: Bool { lock.lock(); defer { lock.unlock() }; return continuation != nil }537 var accept: Bool { get { lock.lock(); defer { lock.unlock() }; return _accept } set { lock.lock(); _accept = newValue; lock.unlock() } }538539 func hints() -> AsyncThrowingStream<ChangeHint, Error> {540 AsyncThrowingStream { c in541 lock.lock()542 _connections += 1543 _times.append(.now)544 let ok = _accept545 if ok { continuation = c }546 lock.unlock()547 if !ok { c.finish(throwing: URLError(.cannotConnectToHost)) }548 }549 }550 func send(_ h: ChangeHint) { lock.lock(); let c = continuation; lock.unlock(); c?.yield(h) }551 func breakStream() { lock.lock(); let c = continuation; continuation = nil; lock.unlock(); c?.finish(throwing: URLError(.networkConnectionLost)) }552}553