import Foundation import RastrilloApple import RastrilloNative import RastrilloTestSupport import XCTest @testable import DocsKit /// A Docs server in miniature, on the production WASM replica: an update POST /// is committed as its document's next row and announced on every stream /// before it is answered (as handlers.go `updatesPost` does), and answered /// with its `Docs-Seq`. "doc" exists; POST /documents creates "new". It /// counts what the client asks for. private actor SequencedServer: NativeTransport { nonisolated let origin = URL(string: "http://localhost:8099")! private final class Document { let replica = CRDTReplica(guid: "realtime-sync") var sequence: Int64 = 0 var rows: [Int64: Data] = [:] var listeners: [UUID: AsyncStream.Continuation] = [:] } private var documents: [String: Document] = [:] private(set) var posts: [ContinuousClock.Instant] = [] /// GET /updates?since=N: what a stream event costs when it is fetched. private(set) var catchUps = 0 private var peerBeforeNextPost: Data? private var failNextPost = false private var stallNextPost: Duration? /// Catch-up GETs answer bytes no replica can apply. private var poisoned = false func open(_ seed: Data, as sqid: String = "doc") async throws { let document = Document(); _ = try await document.replica.open(update: seed); documents[sqid] = document } /// Someone else's change lands just before this client's next POST; that /// POST then fails after 300 ms, or answers only after `stall`. func interleavePeer(_ update: Data, thenFail: Bool = false, stall: Duration? = nil) { peerBeforeNextPost = update; failNextPost = thenFail; stallNextPost = stall } func poison(_ value: Bool) { poisoned = value } func sequence(of sqid: String = "doc") -> Int64 { documents[sqid]?.sequence ?? 0 } @discardableResult func commit(_ update: Data, to sqid: String = "doc") async throws -> Int64 { guard let document = documents[sqid] else { throw NativeClientError.notFound } _ = try await document.replica.apply(update); document.sequence += 1; document.rows[document.sequence] = update let assigned = document.sequence for listener in document.listeners.values { listener.yield(assigned) } return assigned } func text(of sqid: String = "doc") async throws -> String { try await documents[sqid]!.replica.projection().children.map(\.plainText).joined(separator: "\n") } private func sqid(_ path: String) -> String { String(path.split(separator: "?")[0].split(separator: "/").dropFirst().first ?? "") } func responseDetails(_ path: String, method: String, body: Data?, contentType: String, maxBytes: Int) async throws -> NativeResponse { if method == "POST", path == "/documents" { if documents["new"] == nil { try await open(Data(), as: "new") } return NativeResponse(data: Data(#"{"sqid":"new","title":"Untitled"}"#.utf8), status: 201, headers: [:]) } let sqid = sqid(path) guard let document = documents[sqid] else { return NativeResponse(data: Data(), status: 404, headers: [:]) } if method == "POST", path.hasSuffix("/title") { return NativeResponse(data: Data(), status: 200, headers: [:]) } if method == "POST", path.hasSuffix("/updates"), let body { posts.append(.now) if let peer = peerBeforeNextPost { peerBeforeNextPost = nil; try await commit(peer, to: sqid) } // A slow failure: the peer's event reaches the client while its POST waits. if failNextPost { failNextPost = false; try await Task.sleep(for: .milliseconds(300)); throw NativeClientError.server(status: 503) } if let stall = stallNextPost { stallNextPost = nil; try await Task.sleep(for: stall) } let assigned = try await commit(body, to: sqid) return NativeResponse(data: Data(), status: 204, headers: ["Docs-Seq": String(assigned)]) } if path.contains("/updates") { let since = URLComponents(string: path)?.queryItems?.first(where: { $0.name == "since" })?.value.flatMap(Int64.init) ?? 0 // Docs-Seq comes from the rows in hand, as handlers.go // `updatesGet` derives it, never from a second read: this actor // is reentrant, so a POST can commit a row while the merge below // awaits, and a header read afterwards would claim a row the body // does not carry (the client then skips it for good). let data: Data, highest: Int64 if path.contains("since=") { catchUps += 1 let rows = document.rows.keys.sorted().filter { $0 > since } highest = rows.last ?? since let updates = rows.compactMap { document.rows[$0] } data = poisoned ? Data([255, 255, 255]) : updates.isEmpty ? Data() : try await document.replica.mergeUpdates(updates) } else { highest = document.sequence data = try await document.replica.persistentState().state } return NativeResponse(data: data, status: 200, headers: ["Docs-Seq": String(highest)]) } let detail = DocumentDetail(sqid: sqid, title: "Doc", guid: "realtime-sync", can_write: true, can_share: false) return NativeResponse(data: try JSONEncoder().encode(detail), status: 200, headers: [:]) } func stream(_ path: String, onOpen: @Sendable () async throws -> Void, onLine: @Sendable (String) async throws -> Void) async throws { guard let document = documents[sqid(path)] else { throw NativeClientError.notFound } let id = UUID(), events = AsyncStream.makeStream(bufferingPolicy: .bufferingNewest(1)) document.listeners[id] = events.continuation defer { document.listeners.removeValue(forKey: id) } try await onOpen(); try await onLine("data: \(document.sequence)") for await sequence in events.stream { try Task.checkCancellation(); try await onLine("data: \(sequence)") } } func download(_ path: String, to destination: URL) async throws { throw NativeClientError.notFound } var openStreams: Int { documents.values.reduce(0) { $0 + $1.listeners.count } } } /// Counts reads of documents' metadata files (each one a decrypt in a sealed store). private final class MetadataReadCounter: BlobStore, @unchecked Sendable { let base = MemoryBlobStore() private let lock = NSLock() private var count = 0 var reads: Int { lock.withLock { count } } func read(_ path: String) throws -> Data? { if path.hasSuffix("/meta") { lock.withLock { count += 1 } } return try base.read(path) } func write(_ bytes: Data, to path: String) throws { try base.write(bytes, to: path) } func remove(_ path: String) throws { try base.remove(path) } func list(_ path: String) throws -> [String] { try base.list(path) } } @MainActor private func until(_ seconds: Double, _ condition: () async -> Bool) async { let deadline = Date().addingTimeInterval(seconds) while await !condition(), Date() < deadline { try? await Task.sleep(for: .milliseconds(10)) } } @MainActor final class RealtimeSyncTests: XCTestCase { private var server: SequencedServer! private var account: DocsOfflineAccount! private func seed() async throws -> Data { let replica = CRDTReplica(guid: "realtime-sync") _ = try await replica.open(update: Data()) _ = try await replica.command(["op": .string("insert_element"), "at": .number(0), "type": .string("paragraph")]) defer { Task { await replica.close() } } return try await replica.persistentState().state } /// A peer's update typing `text` at the start of the document. private func peerUpdate(_ text: String, in sqid: String = "doc") async throws -> Data { let peer = CRDTReplica(guid: "realtime-sync") let state = try await server.responseDetails("/d/\(sqid)/updates", method: "GET", body: nil, contentType: "", maxBytes: 1 << 20).data _ = try await peer.open(update: state) let update = try await peer.command(["op": .string("display_edit"), "at": .number(0), "length": .number(0), "text": .string(text)]) await peer.close() return update } private func openModel() async throws -> DocsModel { let server = self.server! let model = DocsModel(transport: { server }, connectivity: NativeConnectivity(source: ScriptedPathSource(.satisfied)), offlineAccount: account) await model.open("doc") XCTAssertNotNil(model.projection) model.didRender(model.projectionGeneration) try await Task.sleep(for: .milliseconds(100)) // the stream opens and its connect-time event settles return model } private func type(_ model: DocsModel, _ text: String, every cadence: Duration = .zero) async throws { for character in text { let at = model.projection?.children.first?.plainText.utf16.count ?? 0 XCTAssertTrue(model.enqueue(["op": .string("display_edit"), "at": .number(Double(at)), "length": .number(0), "text": .string(String(character))])) await until(5) { !model.hasPendingInput } model.didRender(model.projectionGeneration) if cadence > .zero { try await Task.sleep(for: cadence) } } } private func plain(_ model: DocsModel) -> String { model.projection?.children.map(\.plainText).joined(separator: "\n") ?? "" } private func sent(_ model: DocsModel) async -> Bool { await account.outbox.summary.isEmpty && !model.hasPendingInput } override func setUp() async throws { server = SequencedServer() try await server.open(try await seed()) let server = self.server! account = DocsOfflineAccount(store: MemoryBlobStore(), accountID: UUID().uuidString, connectivity: NativeConnectivity(source: ScriptedPathSource(.satisfied)), transport: { server }) } /// Finding 5: the server's sequence for this client's own POST is /// adopted, so its stream event is never fetched back. func testOwnSavesAreNotFetchedBack() async throws { let model = try await openModel() try await type(model, "Hello", every: .milliseconds(60)) await until(5) { await self.sent(model) } try await Task.sleep(for: .milliseconds(300)) let posts = await server.posts.count, catchUps = await server.catchUps XCTAssertGreaterThan(posts, 0) XCTAssertEqual(catchUps, 0, "an own save was fetched back") let saved = try await server.text() XCTAssertEqual(saved, "Hello") // A peer's change is still fetched and shown. try await server.commit(try await peerUpdate("Peer ")) await until(5) { self.plain(model) == "Peer Hello" } XCTAssertEqual(plain(model), "Peer Hello") let after = await server.catchUps XCTAssertEqual(after, 1) await model.discardAll() } /// Review note on #145: the echo skip adopts the server's sequence for an /// own POST without applying anything, which is only safe because the /// send path stores the sent update in the replica before the entry is /// marked sent. Crash after typing (the edit only in the outbox), reopen, /// send and adopt the sequence, reopen offline: the edit must be there. func testAnAdoptedSequenceNeverOutrunsTheStoredReplica() async throws { let server = self.server! let disk = FaultingBlobStore(), id = UUID().uuidString let offline = NativeConnectivity(source: ScriptedPathSource(.unsatisfied)) let first = DocsOfflineAccount(store: disk, accountID: id, connectivity: offline, transport: { server }) let writer = DocsModel(transport: { server }, connectivity: offline, offlineAccount: first) await writer.open("doc") writer.didRender(writer.projectionGeneration) XCTAssertTrue(writer.enqueue(["op": .string("display_edit"), "at": .number(0), "length": .number(0), "text": .string("Kept")])) await until(5) { !writer.hasPendingInput } first.drainer.stop(); disk.crash(after: 0) writer.suspendLiveUpdates() // the dead process hears nothing more // A new process sends the lane and adopts the POST's sequence. let store = disk.committed // The network returns once the document is open, so it is this // replica's POST whose answer is adopted. // The outbox sends only once the document's stream is open, so the // POST's answer reaches this replica, which adopts its sequence. let path = ScriptedPathSource(.unsatisfied) let sending = NativeConnectivity(source: path) let second = DocsOfflineAccount(store: store, accountID: id, connectivity: sending, transport: { server }) let sender = DocsModel(transport: { server }, connectivity: NativeConnectivity(source: ScriptedPathSource(.satisfied)), offlineAccount: second) await sender.open("doc") sender.didRender(sender.projectionGeneration) XCTAssertEqual(plain(sender), "Kept") await until(5) { await server.openStreams == 1 } try await Task.sleep(for: .milliseconds(100)) path.send(.satisfied) await until(5) { sending.isPathSatisfied } second.drainer.kick() await until(5) { await second.outbox.summary.isEmpty } try await Task.sleep(for: .milliseconds(300)) let fetched = await server.catchUps XCTAssertEqual(fetched, 0, "the own save's sequence was adopted, not fetched") let row = await server.sequence() XCTAssertEqual(try second.replicaCache.load("doc")?.sequence ?? 0 <= row, true) await sender.stop(); second.drainer.stop() XCTAssertEqual(try second.replicaCache.load("doc")?.sequence, row, "the stored replica reached the adopted row") // Offline again, from the stored bytes only: the edit is there. let third = DocsOfflineAccount(store: MemoryBlobStore(store.contents), accountID: id, connectivity: offline, transport: { server }) let reader = DocsModel(transport: { server }, connectivity: offline, offlineAccount: third) await reader.open("doc") XCTAssertEqual(plain(reader), "Kept") let empty = await third.outbox.summary.isEmpty XCTAssertTrue(empty) await reader.stop(); third.drainer.stop() } /// The web's guard: a POST whose sequence is not exactly the next row /// must not move the cursor past the row someone else wrote first. func testAPeerRowBeforeAnOwnSaveIsNeverSkipped() async throws { let model = try await openModel() try await type(model, "A") await until(5) { await self.sent(model) } await server.interleavePeer(try await peerUpdate("Peer ")) try await type(model, "B") await until(5) { self.plain(model).hasPrefix("Peer ") } XCTAssertEqual(plain(model), "Peer AB") await until(5) { await self.sent(model) } let saved = try await server.text() XCTAssertEqual(saved, "Peer AB") await model.discardAll() } /// A stream event held for an own POST that then fails is fetched at once. func testAHeldEventIsFetchedWhenTheOwnSaveFails() async throws { let model = try await openModel() try await type(model, "A") await until(5) { await self.sent(model) } await server.interleavePeer(try await peerUpdate("Peer "), thenFail: true) let typed = Date() try await type(model, "B") await until(5) { self.plain(model).hasPrefix("Peer ") } XCTAssertEqual(plain(model), "Peer AB") XCTAssertLessThan(Date().timeIntervalSince(typed), 0.8, "the peer's change waited for the hold's timeout") await until(10) { await self.sent(model) } let saved = try await server.text() XCTAssertEqual(saved, "Peer AB") await model.discardAll() } /// The hold's one-second cap holds: a POST that does not answer cannot /// hide a peer's change for longer (review finding 1). func testAStalledSaveHoldsAPeerChangeForAtMostASecond() async throws { let model = try await openModel() try await type(model, "A") await until(5) { await self.sent(model) } await server.interleavePeer(try await peerUpdate("Peer "), stall: .seconds(4)) let typed = Date() try await type(model, "B") await until(3) { self.plain(model).hasPrefix("Peer ") } XCTAssertEqual(plain(model), "Peer AB") XCTAssertLessThan(Date().timeIntervalSince(typed), 1.8, "the peer's change waited for the stalled POST") await until(10) { await self.sent(model) } let saved = try await server.text() XCTAssertEqual(saved, "Peer AB") await model.discardAll() } /// The model is reused for the next document (iPhone New: save, discard, /// new draft). The draft must not keep the previous document's cursor, or /// every announcement up to it is ignored (review finding 2b). func testANewDraftAfterADocumentStartsFromItsOwnCursor() async throws { let model = try await openModel() for text in ["c", "b", "a"] { try await server.commit(try await peerUpdate(text)) } await until(5) { self.plain(model) == "abc" } XCTAssertEqual(plain(model), "abc") await model.discardAll() await model.newDraft() await until(5) { !model.isDraft && model.detail?.sqid == "new" } await until(5) { let streams = await self.server.openStreams; let sent = await self.sent(model); return streams == 1 && sent } XCTAssertEqual(model.detail?.sqid, "new") try await server.commit(try await peerUpdate("Peer", in: "new"), to: "new") await until(5) { self.plain(model) == "Peer" } XCTAssertEqual(plain(model), "Peer", "the draft ignored the new document's first rows") await model.discardAll() } /// The same after `stop` (a window closing), where only newDraft resets. func testANewDraftAfterStopStartsFromItsOwnCursor() async throws { let model = try await openModel() for text in ["c", "b", "a"] { try await server.commit(try await peerUpdate(text)) } await until(5) { self.plain(model) == "abc" } await model.stop() XCTAssertNil(model.detail) await model.newDraft() await until(5) { !model.isDraft && model.detail?.sqid == "new" } await until(5) { let streams = await self.server.openStreams; let sent = await self.sent(model); return streams == 1 && sent } try await server.commit(try await peerUpdate("Peer", in: "new"), to: "new") await until(5) { self.plain(model) == "Peer" } XCTAssertEqual(plain(model), "Peer", "the draft ignored the new document's first rows") await model.discardAll() } /// Rows that will not apply are not fetched and re-applied on every /// announcement: the model backs off, says it is retrying, and recovers /// once they apply (review finding 3). func testRowsThatWillNotApplyAreRetriedWithBackoff() async throws { let model = try await openModel() await server.poison(true) for text in ["d", "c", "b", "a"] { try await server.commit(try await peerUpdate(text)) try await Task.sleep(for: .milliseconds(150)) } try await Task.sleep(for: .milliseconds(300)) let refused = await server.catchUps XCTAssertEqual(refused, 1, "every announcement fetched the same rows again") XCTAssertEqual(model.errorKey, "docs.editor.status.retrying") XCTAssertEqual(plain(model), "") await server.poison(false) await until(4) { self.plain(model) == "abcd" } XCTAssertEqual(plain(model), "abcd") XCTAssertNil(model.errorKey) await model.discardAll() } /// Keys typed while a POST waits for the throttle join the next POST /// rather than the one after it (review finding 5): six keys about /// 70 ms apart take three POSTs (reserving before the wait took four). func testKeysTypedDuringTheWaitJoinTheNextPost() async throws { let model = try await openModel() try await type(model, "Six ke", every: .milliseconds(60)) await until(5) { await self.sent(model) } let posts = await server.posts XCTAssertLessThanOrEqual(posts.count, 3, "keys typed during the wait missed the next POST") XCTAssertGreaterThanOrEqual(zip(posts.dropFirst(), posts).map { $0.0 - $0.1 }.min() ?? .seconds(1), .milliseconds(240)) let saved = try await server.text() XCTAssertEqual(saved, "Six ke") await model.discardAll() } /// A discard while a POST waits for the throttle is not sent (finding 6). func testADiscardDuringTheThrottleIsNotSent() async throws { let model = try await openModel() try await type(model, "A") await until(5) { await self.sent(model) } try await type(model, "B") await model.discardAll() try await Task.sleep(for: .milliseconds(400)) let posts = await server.posts.count, saved = try await server.text() XCTAssertEqual(posts, 1) XCTAssertEqual(saved, "A") } /// Backgrounded before an open finishes: no stream starts until the app /// is active again (finding 4). func testAnOpenThatFinishesInTheBackgroundStartsNoStream() async throws { let server = self.server! let model = DocsModel(transport: { server }, connectivity: NativeConnectivity(source: ScriptedPathSource(.satisfied)), offlineAccount: account) model.suspendLiveUpdates() await model.open("doc") XCTAssertNotNil(model.projection) try await Task.sleep(for: .milliseconds(200)) let background = await server.openStreams XCTAssertEqual(background, 0, "a stream started in the background") model.resumeLiveUpdates() await until(2) { await server.openStreams == 1 } let active = await server.openStreams XCTAssertEqual(active, 1) await model.discardAll() } /// Another window of the same document writes entries this window's /// replica does not hold: their sequence is never adopted here. func testAnotherWindowsSaveIsFetched() async throws { let first = try await openModel(), second = try await openModel() try await type(first, "One") await until(5) { self.plain(second) == "One" } XCTAssertEqual(plain(second), "One") await first.discardAll(); await second.discardAll() } /// Finding 6: typing at 8 keys a second sends at most one POST per /// 250 ms, every keystroke is in the outbox before anything is sent, /// and everything arrives. func testTypingIsThrottledToFourPostsASecond() async throws { let model = try await openModel() final class Most: @unchecked Sendable { var queued = 0 } let most = Most() let durable = Task { [account] in for await summary in await account!.outbox.changes { most.queued = max(most.queued, summary.lanes.values.map { $0.pending + $0.held }.max() ?? 0) } } defer { durable.cancel() } let started = ContinuousClock.now try await type(model, "Sixteen keys now", every: .milliseconds(125)) let typing = started.duration(to: .now) await until(5) { await self.sent(model) } let posts = await server.posts let gaps = zip(posts.dropFirst(), posts).map { $0.0 - $0.1 } XCTAssertGreaterThanOrEqual(gaps.min() ?? .seconds(1), .milliseconds(240), "two POSTs closer than the throttle") let seconds = Double(typing.components.seconds) + Double(typing.components.attoseconds) / 1e18 XCTAssertLessThanOrEqual(Double(posts.count), seconds * 4 + 2, "\(posts.count) POSTs in \(typing)") XCTAssertLessThan(posts.count, 16, "one POST per keystroke") XCTAssertGreaterThan(most.queued, 1, "keystrokes waiting to be sent were not in the outbox") let saved = try await server.text() XCTAssertEqual(saved, "Sixteen keys now") await model.discardAll() } /// The iPhone in the background holds no stream (no heartbeat keeping /// the radio up) and says nothing went wrong; back in the foreground it /// reopens and fetches what arrived meanwhile. func testBackgroundClosesTheStreamAndForegroundCatchesUp() async throws { let model = try await openModel() let open = await server.openStreams XCTAssertEqual(open, 1) model.suspendLiveUpdates() await until(2) { await self.server.openStreams == 0 } let closed = await server.openStreams XCTAssertEqual(closed, 0, "the stream stayed open in the background") try await server.commit(try await peerUpdate("Away")) try await Task.sleep(for: .milliseconds(200)) XCTAssertEqual(plain(model), "") XCTAssertNil(model.errorKey) model.resumeLiveUpdates() await until(2) { self.plain(model) == "Away" } XCTAssertEqual(plain(model), "Away") let reopened = await server.openStreams XCTAssertEqual(reopened, 1) XCTAssertNil(model.errorKey) await model.discardAll() } /// Finding 15: the metadata file is read (and decrypted) only when it /// may have changed, not on every outbox change. func testTypingDoesNotRereadMetadataForEveryOutboxChange() async throws { let store = MetadataReadCounter(), server = self.server! account = DocsOfflineAccount(store: store, accountID: UUID().uuidString, connectivity: NativeConnectivity(source: ScriptedPathSource(.satisfied)), transport: { server }) let model = try await openModel() let before = store.reads try await type(model, "Twelve keys!", every: .milliseconds(30)) await until(5) { await self.sent(model) } let perKey = Double(store.reads - before) / 12 print("metadata reads per key: \(perKey)") XCTAssertLessThanOrEqual(perKey, 2, "metadata was re-read for every outbox change") await model.discardAll() } /// Save does not wait out the throttle. func testSaveSendsWithoutTheThrottle() async throws { let model = try await openModel() try await type(model, "A") await until(5) { await self.sent(model) } try await type(model, "B") let saved = await model.saveAll() XCTAssertTrue(saved) let posts = await server.posts XCTAssertEqual(posts.count, 2) XCTAssertLessThan(posts[1] - posts[0], .milliseconds(200), "Save waited for the throttle") await model.discardAll() } }