| 1 | import Foundation |
| 2 | import RastrilloApple |
| 3 | import RastrilloNative |
| 4 | import RastrilloTestSupport |
| 5 | import XCTest |
| 6 | @testable import DocsKit |
| 7 | |
| 8 | /// A Docs server in miniature, on the production WASM replica: an update POST |
| 9 | /// is committed as its document's next row and announced on every stream |
| 10 | /// before it is answered (as handlers.go `updatesPost` does), and answered |
| 11 | /// with its `Docs-Seq`. "doc" exists; POST /documents creates "new". It |
| 12 | /// counts what the client asks for. |
| 13 | private actor SequencedServer: NativeTransport { |
| 14 | nonisolated let origin = URL(string: "http://localhost:8099")! |
| 15 | private final class Document { |
| 16 | let replica = CRDTReplica(guid: "realtime-sync") |
| 17 | var sequence: Int64 = 0 |
| 18 | var rows: [Int64: Data] = [:] |
| 19 | var listeners: [UUID: AsyncStream<Int64>.Continuation] = [:] |
| 20 | } |
| 21 | private var documents: [String: Document] = [:] |
| 22 | private(set) var posts: [ContinuousClock.Instant] = [] |
| 23 | /// GET /updates?since=N: what a stream event costs when it is fetched. |
| 24 | private(set) var catchUps = 0 |
| 25 | private var peerBeforeNextPost: Data? |
| 26 | private var failNextPost = false |
| 27 | private var stallNextPost: Duration? |
| 28 | /// Catch-up GETs answer bytes no replica can apply. |
| 29 | private var poisoned = false |
| 30 | func open(_ seed: Data, as sqid: String = "doc") async throws { |
| 31 | let document = Document(); _ = try await document.replica.open(update: seed); documents[sqid] = document |
| 32 | } |
| 33 | /// Someone else's change lands just before this client's next POST; that |
| 34 | /// POST then fails after 300 ms, or answers only after `stall`. |
| 35 | func interleavePeer(_ update: Data, thenFail: Bool = false, stall: Duration? = nil) { |
| 36 | peerBeforeNextPost = update; failNextPost = thenFail; stallNextPost = stall |
| 37 | } |
| 38 | func poison(_ value: Bool) { poisoned = value } |
| 39 | func sequence(of sqid: String = "doc") -> Int64 { documents[sqid]?.sequence ?? 0 } |
| 40 | @discardableResult func commit(_ update: Data, to sqid: String = "doc") async throws -> Int64 { |
| 41 | guard let document = documents[sqid] else { throw NativeClientError.notFound } |
| 42 | _ = try await document.replica.apply(update); document.sequence += 1; document.rows[document.sequence] = update |
| 43 | let assigned = document.sequence |
| 44 | for listener in document.listeners.values { listener.yield(assigned) } |
| 45 | return assigned |
| 46 | } |
| 47 | func text(of sqid: String = "doc") async throws -> String { |
| 48 | try await documents[sqid]!.replica.projection().children.map(\.plainText).joined(separator: "\n") |
| 49 | } |
| 50 | private func sqid(_ path: String) -> String { |
| 51 | String(path.split(separator: "?")[0].split(separator: "/").dropFirst().first ?? "") |
| 52 | } |
| 53 | func responseDetails(_ path: String, method: String, body: Data?, contentType: String, maxBytes: Int) async throws -> NativeResponse { |
| 54 | if method == "POST", path == "/documents" { |
| 55 | if documents["new"] == nil { try await open(Data(), as: "new") } |
| 56 | return NativeResponse(data: Data(#"{"sqid":"new","title":"Untitled"}"#.utf8), status: 201, headers: [:]) |
| 57 | } |
| 58 | let sqid = sqid(path) |
| 59 | guard let document = documents[sqid] else { return NativeResponse(data: Data(), status: 404, headers: [:]) } |
| 60 | if method == "POST", path.hasSuffix("/title") { return NativeResponse(data: Data(), status: 200, headers: [:]) } |
| 61 | if method == "POST", path.hasSuffix("/updates"), let body { |
| 62 | posts.append(.now) |
| 63 | if let peer = peerBeforeNextPost { peerBeforeNextPost = nil; try await commit(peer, to: sqid) } |
| 64 | // A slow failure: the peer's event reaches the client while its POST waits. |
| 65 | if failNextPost { failNextPost = false; try await Task.sleep(for: .milliseconds(300)); throw NativeClientError.server(status: 503) } |
| 66 | if let stall = stallNextPost { stallNextPost = nil; try await Task.sleep(for: stall) } |
| 67 | let assigned = try await commit(body, to: sqid) |
| 68 | return NativeResponse(data: Data(), status: 204, headers: ["Docs-Seq": String(assigned)]) |
| 69 | } |
| 70 | if path.contains("/updates") { |
| 71 | let since = URLComponents(string: path)?.queryItems?.first(where: { $0.name == "since" })?.value.flatMap(Int64.init) ?? 0 |
| 72 | // Docs-Seq comes from the rows in hand, as handlers.go |
| 73 | // `updatesGet` derives it, never from a second read: this actor |
| 74 | // is reentrant, so a POST can commit a row while the merge below |
| 75 | // awaits, and a header read afterwards would claim a row the body |
| 76 | // does not carry (the client then skips it for good). |
| 77 | let data: Data, highest: Int64 |
| 78 | if path.contains("since=") { |
| 79 | catchUps += 1 |
| 80 | let rows = document.rows.keys.sorted().filter { $0 > since } |
| 81 | highest = rows.last ?? since |
| 82 | let updates = rows.compactMap { document.rows[$0] } |
| 83 | data = poisoned ? Data([255, 255, 255]) : updates.isEmpty ? Data() : try await document.replica.mergeUpdates(updates) |
| 84 | } else { |
| 85 | highest = document.sequence |
| 86 | data = try await document.replica.persistentState().state |
| 87 | } |
| 88 | return NativeResponse(data: data, status: 200, headers: ["Docs-Seq": String(highest)]) |
| 89 | } |
| 90 | let detail = DocumentDetail(sqid: sqid, title: "Doc", guid: "realtime-sync", can_write: true, can_share: false) |
| 91 | return NativeResponse(data: try JSONEncoder().encode(detail), status: 200, headers: [:]) |
| 92 | } |
| 93 | func stream(_ path: String, onOpen: @Sendable () async throws -> Void, onLine: @Sendable (String) async throws -> Void) async throws { |
| 94 | guard let document = documents[sqid(path)] else { throw NativeClientError.notFound } |
| 95 | let id = UUID(), events = AsyncStream<Int64>.makeStream(bufferingPolicy: .bufferingNewest(1)) |
| 96 | document.listeners[id] = events.continuation |
| 97 | defer { document.listeners.removeValue(forKey: id) } |
| 98 | try await onOpen(); try await onLine("data: \(document.sequence)") |
| 99 | for await sequence in events.stream { try Task.checkCancellation(); try await onLine("data: \(sequence)") } |
| 100 | } |
| 101 | func download(_ path: String, to destination: URL) async throws { throw NativeClientError.notFound } |
| 102 | var openStreams: Int { documents.values.reduce(0) { $0 + $1.listeners.count } } |
| 103 | } |
| 104 | |
| 105 | /// Counts reads of documents' metadata files (each one a decrypt in a sealed store). |
| 106 | private final class MetadataReadCounter: BlobStore, @unchecked Sendable { |
| 107 | let base = MemoryBlobStore() |
| 108 | private let lock = NSLock() |
| 109 | private var count = 0 |
| 110 | var reads: Int { lock.withLock { count } } |
| 111 | func read(_ path: String) throws -> Data? { |
| 112 | if path.hasSuffix("/meta") { lock.withLock { count += 1 } } |
| 113 | return try base.read(path) |
| 114 | } |
| 115 | func write(_ bytes: Data, to path: String) throws { try base.write(bytes, to: path) } |
| 116 | func remove(_ path: String) throws { try base.remove(path) } |
| 117 | func list(_ path: String) throws -> [String] { try base.list(path) } |
| 118 | } |
| 119 | |
| 120 | @MainActor private func until(_ seconds: Double, _ condition: () async -> Bool) async { |
| 121 | let deadline = Date().addingTimeInterval(seconds) |
| 122 | while await !condition(), Date() < deadline { try? await Task.sleep(for: .milliseconds(10)) } |
| 123 | } |
| 124 | |
| 125 | @MainActor final class RealtimeSyncTests: XCTestCase { |
| 126 | private var server: SequencedServer! |
| 127 | private var account: DocsOfflineAccount! |
| 128 | |
| 129 | private func seed() async throws -> Data { |
| 130 | let replica = CRDTReplica(guid: "realtime-sync") |
| 131 | _ = try await replica.open(update: Data()) |
| 132 | _ = try await replica.command(["op": .string("insert_element"), "at": .number(0), "type": .string("paragraph")]) |
| 133 | defer { Task { await replica.close() } } |
| 134 | return try await replica.persistentState().state |
| 135 | } |
| 136 | /// A peer's update typing `text` at the start of the document. |
| 137 | private func peerUpdate(_ text: String, in sqid: String = "doc") async throws -> Data { |
| 138 | let peer = CRDTReplica(guid: "realtime-sync") |
| 139 | let state = try await server.responseDetails("/d/\(sqid)/updates", method: "GET", body: nil, contentType: "", maxBytes: 1 << 20).data |
| 140 | _ = try await peer.open(update: state) |
| 141 | let update = try await peer.command(["op": .string("display_edit"), "at": .number(0), "length": .number(0), "text": .string(text)]) |
| 142 | await peer.close() |
| 143 | return update |
| 144 | } |
| 145 | private func openModel() async throws -> DocsModel { |
| 146 | let server = self.server! |
| 147 | let model = DocsModel(transport: { server }, connectivity: NativeConnectivity(source: ScriptedPathSource(.satisfied)), offlineAccount: account) |
| 148 | await model.open("doc") |
| 149 | XCTAssertNotNil(model.projection) |
| 150 | model.didRender(model.projectionGeneration) |
| 151 | try await Task.sleep(for: .milliseconds(100)) // the stream opens and its connect-time event settles |
| 152 | return model |
| 153 | } |
| 154 | private func type(_ model: DocsModel, _ text: String, every cadence: Duration = .zero) async throws { |
| 155 | for character in text { |
| 156 | let at = model.projection?.children.first?.plainText.utf16.count ?? 0 |
| 157 | XCTAssertTrue(model.enqueue(["op": .string("display_edit"), "at": .number(Double(at)), "length": .number(0), "text": .string(String(character))])) |
| 158 | await until(5) { !model.hasPendingInput } |
| 159 | model.didRender(model.projectionGeneration) |
| 160 | if cadence > .zero { try await Task.sleep(for: cadence) } |
| 161 | } |
| 162 | } |
| 163 | private func plain(_ model: DocsModel) -> String { model.projection?.children.map(\.plainText).joined(separator: "\n") ?? "" } |
| 164 | private func sent(_ model: DocsModel) async -> Bool { await account.outbox.summary.isEmpty && !model.hasPendingInput } |
| 165 | |
| 166 | override func setUp() async throws { |
| 167 | server = SequencedServer() |
| 168 | try await server.open(try await seed()) |
| 169 | let server = self.server! |
| 170 | account = DocsOfflineAccount(store: MemoryBlobStore(), accountID: UUID().uuidString, |
| 171 | connectivity: NativeConnectivity(source: ScriptedPathSource(.satisfied)), transport: { server }) |
| 172 | } |
| 173 | |
| 174 | /// Finding 5: the server's sequence for this client's own POST is |
| 175 | /// adopted, so its stream event is never fetched back. |
| 176 | func testOwnSavesAreNotFetchedBack() async throws { |
| 177 | let model = try await openModel() |
| 178 | try await type(model, "Hello", every: .milliseconds(60)) |
| 179 | await until(5) { await self.sent(model) } |
| 180 | try await Task.sleep(for: .milliseconds(300)) |
| 181 | let posts = await server.posts.count, catchUps = await server.catchUps |
| 182 | XCTAssertGreaterThan(posts, 0) |
| 183 | XCTAssertEqual(catchUps, 0, "an own save was fetched back") |
| 184 | let saved = try await server.text() |
| 185 | XCTAssertEqual(saved, "Hello") |
| 186 | // A peer's change is still fetched and shown. |
| 187 | try await server.commit(try await peerUpdate("Peer ")) |
| 188 | await until(5) { self.plain(model) == "Peer Hello" } |
| 189 | XCTAssertEqual(plain(model), "Peer Hello") |
| 190 | let after = await server.catchUps |
| 191 | XCTAssertEqual(after, 1) |
| 192 | await model.discardAll() |
| 193 | } |
| 194 | |
| 195 | /// Review note on #145: the echo skip adopts the server's sequence for an |
| 196 | /// own POST without applying anything, which is only safe because the |
| 197 | /// send path stores the sent update in the replica before the entry is |
| 198 | /// marked sent. Crash after typing (the edit only in the outbox), reopen, |
| 199 | /// send and adopt the sequence, reopen offline: the edit must be there. |
| 200 | func testAnAdoptedSequenceNeverOutrunsTheStoredReplica() async throws { |
| 201 | let server = self.server! |
| 202 | let disk = FaultingBlobStore(), id = UUID().uuidString |
| 203 | let offline = NativeConnectivity(source: ScriptedPathSource(.unsatisfied)) |
| 204 | let first = DocsOfflineAccount(store: disk, accountID: id, connectivity: offline, transport: { server }) |
| 205 | let writer = DocsModel(transport: { server }, connectivity: offline, offlineAccount: first) |
| 206 | await writer.open("doc") |
| 207 | writer.didRender(writer.projectionGeneration) |
| 208 | XCTAssertTrue(writer.enqueue(["op": .string("display_edit"), "at": .number(0), "length": .number(0), "text": .string("Kept")])) |
| 209 | await until(5) { !writer.hasPendingInput } |
| 210 | first.drainer.stop(); disk.crash(after: 0) |
| 211 | writer.suspendLiveUpdates() // the dead process hears nothing more |
| 212 | // A new process sends the lane and adopts the POST's sequence. |
| 213 | let store = disk.committed |
| 214 | // The network returns once the document is open, so it is this |
| 215 | // replica's POST whose answer is adopted. |
| 216 | // The outbox sends only once the document's stream is open, so the |
| 217 | // POST's answer reaches this replica, which adopts its sequence. |
| 218 | let path = ScriptedPathSource(.unsatisfied) |
| 219 | let sending = NativeConnectivity(source: path) |
| 220 | let second = DocsOfflineAccount(store: store, accountID: id, connectivity: sending, transport: { server }) |
| 221 | let sender = DocsModel(transport: { server }, connectivity: NativeConnectivity(source: ScriptedPathSource(.satisfied)), offlineAccount: second) |
| 222 | await sender.open("doc") |
| 223 | sender.didRender(sender.projectionGeneration) |
| 224 | XCTAssertEqual(plain(sender), "Kept") |
| 225 | await until(5) { await server.openStreams == 1 } |
| 226 | try await Task.sleep(for: .milliseconds(100)) |
| 227 | path.send(.satisfied) |
| 228 | await until(5) { sending.isPathSatisfied } |
| 229 | second.drainer.kick() |
| 230 | await until(5) { await second.outbox.summary.isEmpty } |
| 231 | try await Task.sleep(for: .milliseconds(300)) |
| 232 | let fetched = await server.catchUps |
| 233 | XCTAssertEqual(fetched, 0, "the own save's sequence was adopted, not fetched") |
| 234 | let row = await server.sequence() |
| 235 | XCTAssertEqual(try second.replicaCache.load("doc")?.sequence ?? 0 <= row, true) |
| 236 | await sender.stop(); second.drainer.stop() |
| 237 | XCTAssertEqual(try second.replicaCache.load("doc")?.sequence, row, "the stored replica reached the adopted row") |
| 238 | // Offline again, from the stored bytes only: the edit is there. |
| 239 | let third = DocsOfflineAccount(store: MemoryBlobStore(store.contents), accountID: id, connectivity: offline, transport: { server }) |
| 240 | let reader = DocsModel(transport: { server }, connectivity: offline, offlineAccount: third) |
| 241 | await reader.open("doc") |
| 242 | XCTAssertEqual(plain(reader), "Kept") |
| 243 | let empty = await third.outbox.summary.isEmpty |
| 244 | XCTAssertTrue(empty) |
| 245 | await reader.stop(); third.drainer.stop() |
| 246 | } |
| 247 | |
| 248 | /// The web's guard: a POST whose sequence is not exactly the next row |
| 249 | /// must not move the cursor past the row someone else wrote first. |
| 250 | func testAPeerRowBeforeAnOwnSaveIsNeverSkipped() async throws { |
| 251 | let model = try await openModel() |
| 252 | try await type(model, "A") |
| 253 | await until(5) { await self.sent(model) } |
| 254 | await server.interleavePeer(try await peerUpdate("Peer ")) |
| 255 | try await type(model, "B") |
| 256 | await until(5) { self.plain(model).hasPrefix("Peer ") } |
| 257 | XCTAssertEqual(plain(model), "Peer AB") |
| 258 | await until(5) { await self.sent(model) } |
| 259 | let saved = try await server.text() |
| 260 | XCTAssertEqual(saved, "Peer AB") |
| 261 | await model.discardAll() |
| 262 | } |
| 263 | |
| 264 | /// A stream event held for an own POST that then fails is fetched at once. |
| 265 | func testAHeldEventIsFetchedWhenTheOwnSaveFails() async throws { |
| 266 | let model = try await openModel() |
| 267 | try await type(model, "A") |
| 268 | await until(5) { await self.sent(model) } |
| 269 | await server.interleavePeer(try await peerUpdate("Peer "), thenFail: true) |
| 270 | let typed = Date() |
| 271 | try await type(model, "B") |
| 272 | await until(5) { self.plain(model).hasPrefix("Peer ") } |
| 273 | XCTAssertEqual(plain(model), "Peer AB") |
| 274 | XCTAssertLessThan(Date().timeIntervalSince(typed), 0.8, "the peer's change waited for the hold's timeout") |
| 275 | await until(10) { await self.sent(model) } |
| 276 | let saved = try await server.text() |
| 277 | XCTAssertEqual(saved, "Peer AB") |
| 278 | await model.discardAll() |
| 279 | } |
| 280 | |
| 281 | /// The hold's one-second cap holds: a POST that does not answer cannot |
| 282 | /// hide a peer's change for longer (review finding 1). |
| 283 | func testAStalledSaveHoldsAPeerChangeForAtMostASecond() async throws { |
| 284 | let model = try await openModel() |
| 285 | try await type(model, "A") |
| 286 | await until(5) { await self.sent(model) } |
| 287 | await server.interleavePeer(try await peerUpdate("Peer "), stall: .seconds(4)) |
| 288 | let typed = Date() |
| 289 | try await type(model, "B") |
| 290 | await until(3) { self.plain(model).hasPrefix("Peer ") } |
| 291 | XCTAssertEqual(plain(model), "Peer AB") |
| 292 | XCTAssertLessThan(Date().timeIntervalSince(typed), 1.8, "the peer's change waited for the stalled POST") |
| 293 | await until(10) { await self.sent(model) } |
| 294 | let saved = try await server.text() |
| 295 | XCTAssertEqual(saved, "Peer AB") |
| 296 | await model.discardAll() |
| 297 | } |
| 298 | |
| 299 | /// The model is reused for the next document (iPhone New: save, discard, |
| 300 | /// new draft). The draft must not keep the previous document's cursor, or |
| 301 | /// every announcement up to it is ignored (review finding 2b). |
| 302 | func testANewDraftAfterADocumentStartsFromItsOwnCursor() async throws { |
| 303 | let model = try await openModel() |
| 304 | for text in ["c", "b", "a"] { try await server.commit(try await peerUpdate(text)) } |
| 305 | await until(5) { self.plain(model) == "abc" } |
| 306 | XCTAssertEqual(plain(model), "abc") |
| 307 | await model.discardAll() |
| 308 | await model.newDraft() |
| 309 | await until(5) { !model.isDraft && model.detail?.sqid == "new" } |
| 310 | await until(5) { let streams = await self.server.openStreams; let sent = await self.sent(model); return streams == 1 && sent } |
| 311 | XCTAssertEqual(model.detail?.sqid, "new") |
| 312 | try await server.commit(try await peerUpdate("Peer", in: "new"), to: "new") |
| 313 | await until(5) { self.plain(model) == "Peer" } |
| 314 | XCTAssertEqual(plain(model), "Peer", "the draft ignored the new document's first rows") |
| 315 | await model.discardAll() |
| 316 | } |
| 317 | |
| 318 | /// The same after `stop` (a window closing), where only newDraft resets. |
| 319 | func testANewDraftAfterStopStartsFromItsOwnCursor() async throws { |
| 320 | let model = try await openModel() |
| 321 | for text in ["c", "b", "a"] { try await server.commit(try await peerUpdate(text)) } |
| 322 | await until(5) { self.plain(model) == "abc" } |
| 323 | await model.stop() |
| 324 | XCTAssertNil(model.detail) |
| 325 | await model.newDraft() |
| 326 | await until(5) { !model.isDraft && model.detail?.sqid == "new" } |
| 327 | await until(5) { let streams = await self.server.openStreams; let sent = await self.sent(model); return streams == 1 && sent } |
| 328 | try await server.commit(try await peerUpdate("Peer", in: "new"), to: "new") |
| 329 | await until(5) { self.plain(model) == "Peer" } |
| 330 | XCTAssertEqual(plain(model), "Peer", "the draft ignored the new document's first rows") |
| 331 | await model.discardAll() |
| 332 | } |
| 333 | |
| 334 | /// Rows that will not apply are not fetched and re-applied on every |
| 335 | /// announcement: the model backs off, says it is retrying, and recovers |
| 336 | /// once they apply (review finding 3). |
| 337 | func testRowsThatWillNotApplyAreRetriedWithBackoff() async throws { |
| 338 | let model = try await openModel() |
| 339 | await server.poison(true) |
| 340 | for text in ["d", "c", "b", "a"] { |
| 341 | try await server.commit(try await peerUpdate(text)) |
| 342 | try await Task.sleep(for: .milliseconds(150)) |
| 343 | } |
| 344 | try await Task.sleep(for: .milliseconds(300)) |
| 345 | let refused = await server.catchUps |
| 346 | XCTAssertEqual(refused, 1, "every announcement fetched the same rows again") |
| 347 | XCTAssertEqual(model.errorKey, "docs.editor.status.retrying") |
| 348 | XCTAssertEqual(plain(model), "") |
| 349 | await server.poison(false) |
| 350 | await until(4) { self.plain(model) == "abcd" } |
| 351 | XCTAssertEqual(plain(model), "abcd") |
| 352 | XCTAssertNil(model.errorKey) |
| 353 | await model.discardAll() |
| 354 | } |
| 355 | |
| 356 | /// Keys typed while a POST waits for the throttle join the next POST |
| 357 | /// rather than the one after it (review finding 5): six keys about |
| 358 | /// 70 ms apart take three POSTs (reserving before the wait took four). |
| 359 | func testKeysTypedDuringTheWaitJoinTheNextPost() async throws { |
| 360 | let model = try await openModel() |
| 361 | try await type(model, "Six ke", every: .milliseconds(60)) |
| 362 | await until(5) { await self.sent(model) } |
| 363 | let posts = await server.posts |
| 364 | XCTAssertLessThanOrEqual(posts.count, 3, "keys typed during the wait missed the next POST") |
| 365 | XCTAssertGreaterThanOrEqual(zip(posts.dropFirst(), posts).map { $0.0 - $0.1 }.min() ?? .seconds(1), .milliseconds(240)) |
| 366 | let saved = try await server.text() |
| 367 | XCTAssertEqual(saved, "Six ke") |
| 368 | await model.discardAll() |
| 369 | } |
| 370 | |
| 371 | /// A discard while a POST waits for the throttle is not sent (finding 6). |
| 372 | func testADiscardDuringTheThrottleIsNotSent() async throws { |
| 373 | let model = try await openModel() |
| 374 | try await type(model, "A") |
| 375 | await until(5) { await self.sent(model) } |
| 376 | try await type(model, "B") |
| 377 | await model.discardAll() |
| 378 | try await Task.sleep(for: .milliseconds(400)) |
| 379 | let posts = await server.posts.count, saved = try await server.text() |
| 380 | XCTAssertEqual(posts, 1) |
| 381 | XCTAssertEqual(saved, "A") |
| 382 | } |
| 383 | |
| 384 | /// Backgrounded before an open finishes: no stream starts until the app |
| 385 | /// is active again (finding 4). |
| 386 | func testAnOpenThatFinishesInTheBackgroundStartsNoStream() async throws { |
| 387 | let server = self.server! |
| 388 | let model = DocsModel(transport: { server }, connectivity: NativeConnectivity(source: ScriptedPathSource(.satisfied)), offlineAccount: account) |
| 389 | model.suspendLiveUpdates() |
| 390 | await model.open("doc") |
| 391 | XCTAssertNotNil(model.projection) |
| 392 | try await Task.sleep(for: .milliseconds(200)) |
| 393 | let background = await server.openStreams |
| 394 | XCTAssertEqual(background, 0, "a stream started in the background") |
| 395 | model.resumeLiveUpdates() |
| 396 | await until(2) { await server.openStreams == 1 } |
| 397 | let active = await server.openStreams |
| 398 | XCTAssertEqual(active, 1) |
| 399 | await model.discardAll() |
| 400 | } |
| 401 | |
| 402 | /// Another window of the same document writes entries this window's |
| 403 | /// replica does not hold: their sequence is never adopted here. |
| 404 | func testAnotherWindowsSaveIsFetched() async throws { |
| 405 | let first = try await openModel(), second = try await openModel() |
| 406 | try await type(first, "One") |
| 407 | await until(5) { self.plain(second) == "One" } |
| 408 | XCTAssertEqual(plain(second), "One") |
| 409 | await first.discardAll(); await second.discardAll() |
| 410 | } |
| 411 | |
| 412 | /// Finding 6: typing at 8 keys a second sends at most one POST per |
| 413 | /// 250 ms, every keystroke is in the outbox before anything is sent, |
| 414 | /// and everything arrives. |
| 415 | func testTypingIsThrottledToFourPostsASecond() async throws { |
| 416 | let model = try await openModel() |
| 417 | final class Most: @unchecked Sendable { var queued = 0 } |
| 418 | let most = Most() |
| 419 | let durable = Task { [account] in |
| 420 | for await summary in await account!.outbox.changes { most.queued = max(most.queued, summary.lanes.values.map { $0.pending + $0.held }.max() ?? 0) } |
| 421 | } |
| 422 | defer { durable.cancel() } |
| 423 | let started = ContinuousClock.now |
| 424 | try await type(model, "Sixteen keys now", every: .milliseconds(125)) |
| 425 | let typing = started.duration(to: .now) |
| 426 | await until(5) { await self.sent(model) } |
| 427 | let posts = await server.posts |
| 428 | let gaps = zip(posts.dropFirst(), posts).map { $0.0 - $0.1 } |
| 429 | XCTAssertGreaterThanOrEqual(gaps.min() ?? .seconds(1), .milliseconds(240), "two POSTs closer than the throttle") |
| 430 | let seconds = Double(typing.components.seconds) + Double(typing.components.attoseconds) / 1e18 |
| 431 | XCTAssertLessThanOrEqual(Double(posts.count), seconds * 4 + 2, "\(posts.count) POSTs in \(typing)") |
| 432 | XCTAssertLessThan(posts.count, 16, "one POST per keystroke") |
| 433 | XCTAssertGreaterThan(most.queued, 1, "keystrokes waiting to be sent were not in the outbox") |
| 434 | let saved = try await server.text() |
| 435 | XCTAssertEqual(saved, "Sixteen keys now") |
| 436 | await model.discardAll() |
| 437 | } |
| 438 | |
| 439 | /// The iPhone in the background holds no stream (no heartbeat keeping |
| 440 | /// the radio up) and says nothing went wrong; back in the foreground it |
| 441 | /// reopens and fetches what arrived meanwhile. |
| 442 | func testBackgroundClosesTheStreamAndForegroundCatchesUp() async throws { |
| 443 | let model = try await openModel() |
| 444 | let open = await server.openStreams |
| 445 | XCTAssertEqual(open, 1) |
| 446 | model.suspendLiveUpdates() |
| 447 | await until(2) { await self.server.openStreams == 0 } |
| 448 | let closed = await server.openStreams |
| 449 | XCTAssertEqual(closed, 0, "the stream stayed open in the background") |
| 450 | try await server.commit(try await peerUpdate("Away")) |
| 451 | try await Task.sleep(for: .milliseconds(200)) |
| 452 | XCTAssertEqual(plain(model), "") |
| 453 | XCTAssertNil(model.errorKey) |
| 454 | model.resumeLiveUpdates() |
| 455 | await until(2) { self.plain(model) == "Away" } |
| 456 | XCTAssertEqual(plain(model), "Away") |
| 457 | let reopened = await server.openStreams |
| 458 | XCTAssertEqual(reopened, 1) |
| 459 | XCTAssertNil(model.errorKey) |
| 460 | await model.discardAll() |
| 461 | } |
| 462 | |
| 463 | /// Finding 15: the metadata file is read (and decrypted) only when it |
| 464 | /// may have changed, not on every outbox change. |
| 465 | func testTypingDoesNotRereadMetadataForEveryOutboxChange() async throws { |
| 466 | let store = MetadataReadCounter(), server = self.server! |
| 467 | account = DocsOfflineAccount(store: store, accountID: UUID().uuidString, |
| 468 | connectivity: NativeConnectivity(source: ScriptedPathSource(.satisfied)), transport: { server }) |
| 469 | let model = try await openModel() |
| 470 | let before = store.reads |
| 471 | try await type(model, "Twelve keys!", every: .milliseconds(30)) |
| 472 | await until(5) { await self.sent(model) } |
| 473 | let perKey = Double(store.reads - before) / 12 |
| 474 | print("metadata reads per key: \(perKey)") |
| 475 | XCTAssertLessThanOrEqual(perKey, 2, "metadata was re-read for every outbox change") |
| 476 | await model.discardAll() |
| 477 | } |
| 478 | |
| 479 | /// Save does not wait out the throttle. |
| 480 | func testSaveSendsWithoutTheThrottle() async throws { |
| 481 | let model = try await openModel() |
| 482 | try await type(model, "A") |
| 483 | await until(5) { await self.sent(model) } |
| 484 | try await type(model, "B") |
| 485 | let saved = await model.saveAll() |
| 486 | XCTAssertTrue(saved) |
| 487 | let posts = await server.posts |
| 488 | XCTAssertEqual(posts.count, 2) |
| 489 | XCTAssertLessThan(posts[1] - posts[0], .milliseconds(200), "Save waited for the throttle") |
| 490 | await model.discardAll() |
| 491 | } |
| 492 | } |
| 493 | |