Docs native: no echo download, a 250 ms send throttle, metadata read when it changed, no stream in the background
Audit findings 5, 6, 14 and 15 (native-levelup/docs-realtime-audit.md). - Echo: every POST's Docs-Seq now reaches the open document. It is adopted by the web's rule (live-updates.mjs noteOwnSeq), only when it is exactly the next row, and only when the replica holds every outbox entry the POST carried (another window of the document may have written some). The server announces a POST before answering it, so a stream event for the next row while this document's POST is on the wire is held until the answer (at most a second); a failed POST releases it at once. - Throttle: update POSTs for one document are at least 250 ms apart, like the web's save throttle. The first send after a pause goes at once. Keystrokes still reach the outbox on disk one by one before anything is sent. Save, closing and backgrounding send at once. - Metadata: an open document re-reads (and decrypts) its metadata only when this account has written it since, and assigns observed state only when it changed (3.6 reads per key to 0.6 in the new test). - iPhone: the live stream closes when the app goes to the background and reopens, catching up, when it is active again. No error is shown. RealtimeSyncTests covers each; each test was seen to fail with its fix removed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
6 files changed,
+442
−11
native/apple/Sources/DocsKit/DocsModel.swift+80 −6native/apple/Sources/DocsKit/DocsModels.swift+1 −1native/apple/Sources/DocsKit/DocsOfflineAccount.swift+67 −1native/apple/Sources/DocsKit/DocsPersistence.swift+11 −3native/apple/Sources/DocsKit/DocsWorkspace.swift+6 −0native/apple/Tests/DocsKitTests/RealtimeSyncTests.swift+277 −0
diff --git a/native/apple/Sources/DocsKit/DocsModel.swift b/native/apple/Sources/DocsKit/DocsModel.swift| index 44c5836..5701ff8 100644 |
| --- a/native/apple/Sources/DocsKit/DocsModel.swift |
| +++ b/native/apple/Sources/DocsKit/DocsModel.swift |
| @@ -42,6 +42,13 @@ import RastrilloNative |
| private let writer = CoalescedRunner() |
| private var laneSummary = OutboxSummary() |
| private var summaryTask: Task<Void, Never>? |
| + private var sendObserver: UUID? |
| + /// A stream event that may be only this client's own POST, held until |
| + /// that POST's answer says (see `refresh`). |
| + private var heldRemoteSequence: Int64? |
| + private var heldRemoteTask: Task<Void, Never>? |
| + /// The metadata revision `reloadMetadata` last read for this document. |
| + private var loadedMetadataRevision: Int? |
| var syncStatus: SyncStatus { offlineAccount.drainer.status(lane: documentKey.map { "doc:" + $0 }, localFailure: localFailure) } |
| var lostChangesNotice: String? { outboxSummary.lostUnsent ? NativeSyncStrings.kit.unsentLost : nil } |
| func dismissLostChangesNotice() async { await offlineAccount.outbox.acknowledgeLoss() } |
| @@ -84,6 +91,9 @@ import RastrilloNative |
| private func configurePersistence(key: String, replica: CRDTReplica) { |
| documentKey = key |
| persistence = DocsPersistence(store: offlineAccount.store, outbox: offlineAccount.outbox, key: key, replica: replica, cache: offlineAccount.replicaCache) |
| + loadedMetadataRevision = nil |
| + if let sendObserver { offlineAccount.stopObservingSends(sendObserver) } |
| + sendObserver = offlineAccount.observeSends { [weak self] result in self?.sent(result) } |
| summaryTask?.cancel() |
| summaryTask = Task { [weak self, outbox = offlineAccount.outbox] in |
| for await summary in await outbox.changes { |
| @@ -102,10 +112,18 @@ import RastrilloNative |
| localFailure = nil; inputPaused = detail?.can_write != true || summary.held > 0 |
| } |
| } |
| + /// Every outbox change calls this (several per keystroke), so it reads |
| + /// and decrypts the file only when this account has written it since, |
| + /// and assigns observed state only when it differs. |
| private func reloadMetadata() { |
| - guard !metadataDirty, let key = documentKey, let stored = try? offlineAccount.metadata(key) else { return } |
| + guard !metadataDirty, let key = documentKey else { return } |
| + let revision = offlineAccount.metadataRevisions[key, default: 0] |
| + guard revision != loadedMetadataRevision, let stored = try? offlineAccount.metadata(key) else { return } |
| + loadedMetadataRevision = revision |
| let attached = draftToken != nil && stored.draftToken == nil |
| - detail = stored.detail; pendingTitle = stored.pendingTitle; draftToken = stored.draftToken |
| + if detail != stored.detail { detail = stored.detail } |
| + if pendingTitle != stored.pendingTitle { pendingTitle = stored.pendingTitle } |
| + if draftToken != stored.draftToken { draftToken = stored.draftToken } |
| if attached, streamTask == nil { |
| streamTask = Task { [weak self] in await self?.listen(stored.detail.sqid) } |
| } |
| @@ -377,10 +395,11 @@ import RastrilloNative |
| } |
| func stop() async { |
| lifetime = UUID() |
| + offlineAccount.sendNow() |
| await persistReplica() |
| guard !hasUnsavedChanges else { return } |
| documentEpoch = UUID(); streamTask?.cancel(); streamTask = nil |
| - writerTask?.cancel(); summaryTask?.cancel() |
| + writerTask?.cancel(); summaryTask?.cancel(); stopObservingSends() |
| let previous = replica; replica = nil; detail = nil; projection = nil |
| if let previous { await previous.close() } |
| } |
| @@ -391,9 +410,9 @@ import RastrilloNative |
| writerTask?.cancel(); editingTask?.cancel(); streamTask?.cancel() |
| do { |
| try await persistence?.discard() |
| - if let documentKey { try offlineAccount.store.remove("cache/docs/\(documentKey)/meta") } |
| + if let documentKey { try offlineAccount.removeMetadata(documentKey) } |
| } catch { localFailure = .cannotSaveOnDevice; return } |
| - writerTask?.cancel(); summaryTask?.cancel(); persistence = nil; documentKey = nil |
| + writerTask?.cancel(); summaryTask?.cancel(); stopObservingSends(); persistence = nil; documentKey = nil |
| laneSummary = OutboxSummary(); failedUpdate = nil; localFailure = nil |
| documentEpoch = UUID() |
| creationTask?.cancel(); creationTask = nil; creatingDocument = false |
| @@ -411,6 +430,7 @@ import RastrilloNative |
| guard commitRename() else { return false } |
| if isDraft { startCreation(); await creationTask?.value } |
| if let editingTask { await editingTask.value } |
| + offlineAccount.sendNow() |
| while saving { try? await Task.sleep(for: .milliseconds(20)) } |
| await flush() |
| await persistReplica() |
| @@ -458,6 +478,22 @@ import RastrilloNative |
| private func refresh(_ sqid: String, remoteSequence: Int64) async { |
| let epoch = documentEpoch |
| guard detail?.sqid == sqid, remoteSequence > sequence, let replica else { return } |
| + // The server announces a POST before answering it, so the next row |
| + // may be this client's own update, already in the replica. Hold the |
| + // event until that POST's answer says (`sent`); a POST that does not |
| + // answer within a second no longer holds it. |
| + if remoteSequence == sequence + 1, let documentKey, offlineAccount.postingUpdates.contains(documentKey) { |
| + heldRemoteSequence = max(heldRemoteSequence ?? 0, remoteSequence) |
| + if heldRemoteTask == nil { |
| + heldRemoteTask = Task { [weak self] in |
| + try? await Task.sleep(for: .seconds(1)) |
| + guard let self, !Task.isCancelled else { return } |
| + self.heldRemoteTask = nil |
| + await self.releaseHeldRemote(sqid) |
| + } |
| + } |
| + return |
| + } |
| do { |
| let reply = try await client().responseDetails("/d/\(sqid)/updates?since=\(sequence)", maxBytes: 8 * 1024 * 1024) |
| guard reply.status == 200, let seq = Int64(reply.header("Docs-Seq") ?? "") else { throw CRDTReplica.Failure.rejected } |
| @@ -469,7 +505,45 @@ import RastrilloNative |
| await persistReplica() |
| if editing.isEmpty && editingTask == nil { await publish() } |
| await flush() |
| - } catch { if documentEpoch == epoch { errorKey = "docs.editor.status.retrying" } } |
| + } catch { if documentEpoch == epoch, !Task.isCancelled { errorKey = "docs.editor.status.retrying" } } |
| + } |
| + /// An update POST came back. The web's rule (live-updates.mjs |
| + /// `noteOwnSeq`): adopt the server's sequence for it only when it is |
| + /// exactly the next row, so nothing anyone else wrote can be skipped, and |
| + /// only when this replica holds every entry the POST carried (another |
| + /// window of the document may have written some). Then the stream's |
| + /// event for it is not fetched back and applied a second time. |
| + private func sent(_ result: DocsSentUpdates) { |
| + guard result.key == documentKey, let persistence, let replica, let sqid = detail?.sqid else { return } |
| + if let assigned = result.sequence, assigned == sequence + 1, !result.entries.isEmpty, result.entries.isSubset(of: persistence.held) { |
| + sequence = assigned |
| + Task { await replica.setSequence(assigned) } |
| + } |
| + if heldRemoteSequence != nil { Task { await releaseHeldRemote(sqid) } } |
| + } |
| + private func releaseHeldRemote(_ sqid: String) async { |
| + guard let held = heldRemoteSequence else { return } |
| + heldRemoteSequence = nil |
| + heldRemoteTask?.cancel(); heldRemoteTask = nil |
| + if held > sequence { await refresh(sqid, remoteSequence: held) } |
| + } |
| + private func stopObservingSends() { |
| + if let sendObserver { offlineAccount.stopObservingSends(sendObserver) } |
| + sendObserver = nil |
| + heldRemoteTask?.cancel(); heldRemoteTask = nil; heldRemoteSequence = nil |
| + } |
| + /// The iPhone app going to the background: close the live stream rather |
| + /// than keep the radio up for its heartbeat, and send what is waiting. |
| + /// A suspended app's connection would only come back as an error anyway. |
| + func suspendLiveUpdates() { |
| + offlineAccount.sendNow() |
| + streamTask?.cancel(); streamTask = nil |
| + } |
| + /// Back in the foreground: reopen the stream. Its connect-time event |
| + /// fetches whatever arrived meanwhile. |
| + func resumeLiveUpdates() { |
| + guard streamTask == nil, replica != nil, !isDraft, let sqid = detail?.sqid else { return } |
| + streamTask = Task { [weak self] in await self?.listen(sqid) } |
| } |
| /// Revalidate capability after stream/write rejection while retaining the draft. |
| private func refreshAccess(_ sqid: String, epoch: UUID) async { |
diff --git a/native/apple/Sources/DocsKit/DocsModels.swift b/native/apple/Sources/DocsKit/DocsModels.swift| index 4585b32..77b47c5 100644 |
| --- a/native/apple/Sources/DocsKit/DocsModels.swift |
| +++ b/native/apple/Sources/DocsKit/DocsModels.swift |
| @@ -8,7 +8,7 @@ struct DocumentSummary: Decodable, Identifiable, Sendable { |
| var id: String { sqid } |
| } |
| struct DocumentList: Decodable, Sendable { let documents: [DocumentSummary]; let can_create: Bool } |
| -struct DocumentDetail: Codable, Sendable { |
| +struct DocumentDetail: Codable, Sendable, Equatable { |
| let sqid: String |
| let title: String |
| let guid: String |
diff --git a/native/apple/Sources/DocsKit/DocsOfflineAccount.swift b/native/apple/Sources/DocsKit/DocsOfflineAccount.swift| index d76c85c..bfd0f27 100644 |
| --- a/native/apple/Sources/DocsKit/DocsOfflineAccount.swift |
| +++ b/native/apple/Sources/DocsKit/DocsOfflineAccount.swift |
| @@ -9,6 +9,15 @@ struct DocsOfflineMetadata: Codable { |
| var draftToken: String? |
| } |
| +/// What one POST of a document's updates came back with: the sequence the |
| +/// server gave it (nil if it failed or carried none) and the outbox entries |
| +/// whose bytes it carried. |
| +struct DocsSentUpdates: Sendable { |
| + let key: String |
| + let sequence: Int64? |
| + let entries: Set<UUID> |
| +} |
| + |
| /// All windows for an account share the same outbox and send reservation. |
| @MainActor @Observable final class DocsOfflineAccount { |
| static var accounts: [String: DocsOfflineAccount] = [:] |
| @@ -20,6 +29,20 @@ struct DocsOfflineMetadata: Codable { |
| /// supplies its transport. |
| @ObservationIgnored private var supplier: @MainActor () -> NativeTransport? |
| private(set) var drainer: OutboxDrainer! |
| + /// The least time between two update POSTs for one document, as the web |
| + /// editor's 250 ms save throttle. The first send after a pause goes at |
| + /// once; while typing continues, keystrokes that arrive during the wait |
| + /// go in the next POST. Each keystroke still reaches the outbox on disk |
| + /// first, so this only delays the network, never durability. |
| + @ObservationIgnored var sendInterval: Duration = .milliseconds(250) |
| + @ObservationIgnored private var lastUpdatePost: [String: ContinuousClock.Instant] = [:] |
| + @ObservationIgnored private var pacing: (id: UUID, wake: CheckedContinuation<Void, Never>)? |
| + /// Documents whose update POST is on the wire now. |
| + @ObservationIgnored private(set) var postingUpdates: Set<String> = [] |
| + @ObservationIgnored private var sendObservers: [UUID: @MainActor (DocsSentUpdates) -> Void] = [:] |
| + /// Bumped by every metadata write this account makes, so an open |
| + /// document re-reads (and decrypts) its metadata only when it changed. |
| + @ObservationIgnored private(set) var metadataRevisions: [String: Int] = [:] |
| /// The account's shared store, outbox and drainer, made on first use. |
| /// Called from a view's initialiser, which runs inside its window's body |
| /// on every pass: anything observed it reads joins that body's |
| @@ -104,6 +127,7 @@ struct DocsOfflineMetadata: Codable { |
| try store.read("cache/docs/index").map { try JSONDecoder().decode([String: String].self, from: $0) } ?? [:] |
| } |
| func saveMetadata(_ metadata: DocsOfflineMetadata, key: String) throws { |
| + defer { metadataRevisions[key, default: 0] += 1 } |
| // Register the immutable key first. A crash may leave an empty slot, |
| // never undiscoverable metadata or a rename that Home cannot replay. |
| var index = try index() |
| @@ -117,6 +141,41 @@ struct DocsOfflineMetadata: Codable { |
| try store.write(JSONEncoder().encode(index), to: "cache/docs/index") |
| } |
| } |
| + func removeMetadata(_ key: String) throws { |
| + defer { metadataRevisions[key, default: 0] += 1 } |
| + try store.remove("cache/docs/\(key)/meta") |
| + } |
| + /// An open document hears every update POST's answer, to skip fetching |
| + /// its own change back (see `DocsModel.sent`). |
| + func observeSends(_ observer: @escaping @MainActor (DocsSentUpdates) -> Void) -> UUID { |
| + let id = UUID(); sendObservers[id] = observer; return id |
| + } |
| + func stopObservingSends(_ id: UUID) { sendObservers[id] = nil } |
| + /// Send what is waiting now, without the typing throttle: Save, closing |
| + /// a document, the app going to the background. |
| + func sendNow() { |
| + lastUpdatePost.removeAll() |
| + if let pacing { self.pacing = nil; pacing.wake.resume() } |
| + drainer.kick() |
| + } |
| + private func pace(_ key: String) async { |
| + guard let last = lastUpdatePost[key] else { return } |
| + let due = last.advanced(by: sendInterval) |
| + guard due > .now else { return } |
| + let id = UUID() |
| + await withCheckedContinuation { (wake: CheckedContinuation<Void, Never>) in |
| + pacing = (id, wake) |
| + Task { [weak self] in |
| + try? await Task.sleep(until: due) |
| + guard let self, let pacing = self.pacing, pacing.id == id else { return } |
| + self.pacing = nil; pacing.wake.resume() |
| + } |
| + } |
| + } |
| + private func posted(_ result: DocsSentUpdates) { |
| + postingUpdates.remove(result.key) |
| + for observer in sendObservers.values { observer(result) } |
| + } |
| func key(for sqid: String) throws -> String { |
| let index = try index() |
| if let key = index[sqid] { return key } |
| @@ -191,7 +250,14 @@ struct DocsOfflineMetadata: Codable { |
| catch { sending = Array(updates.prefix(1)); update = sending[0].payload } |
| await merger.close() |
| } catch { await merger.close(); throw error } |
| - let reply = try await transport.responseDetails("/d/\(metadata.detail.sqid)/updates", method: "POST", body: update, contentType: "application/octet-stream") |
| + await pace(key) |
| + lastUpdatePost[key] = .now |
| + postingUpdates.insert(key) |
| + let reply: NativeResponse |
| + do { reply = try await transport.responseDetails("/d/\(metadata.detail.sqid)/updates", method: "POST", body: update, contentType: "application/octet-stream") } |
| + catch { posted(DocsSentUpdates(key: key, sequence: nil, entries: [])); throw error } |
| + let assigned = (200..<300).contains(reply.status) ? Int64(reply.header("Docs-Seq") ?? "") : nil |
| + posted(DocsSentUpdates(key: key, sequence: assigned, entries: Set(sending.map(\.id)))) |
| try reply.requireSuccess() |
| var state = update, sequence: Int64 = 0 |
| if try store.read("cache/docs/\(key)/replica") == nil { |
diff --git a/native/apple/Sources/DocsKit/DocsPersistence.swift b/native/apple/Sources/DocsKit/DocsPersistence.swift| index dc0c8a0..d38e36c 100644 |
| --- a/native/apple/Sources/DocsKit/DocsPersistence.swift |
| +++ b/native/apple/Sources/DocsKit/DocsPersistence.swift |
| @@ -17,6 +17,10 @@ struct PersistedReplica: Codable, Sendable { |
| let key: String |
| let replica: CRDTReplica |
| private(set) var commandsDurable = 0 |
| + /// Outbox entries whose bytes this replica holds: replayed at reopen, |
| + /// enqueued from it, or compacted from only such entries. Another window |
| + /// of the same document writes entries this replica has not seen. |
| + private(set) var held: Set<UUID> = [] |
| private var active = true |
| let cache: DocsReplicaCache |
| private let generation: Int |
| @@ -36,11 +40,12 @@ struct PersistedReplica: Codable, Sendable { |
| await replica.setSequence(saved?.sequence ?? sequence) |
| // Replay includes held entries: the editor must show everything kept |
| // here, even when it cannot currently send it. |
| - for entry in entries where entry.kind == "update" { _ = try await replica.apply(entry.payload) } |
| + for entry in entries where entry.kind == "update" { _ = try await replica.apply(entry.payload); held.insert(entry.id) } |
| commandsDurable = 0 |
| } |
| func enqueue(_ update: Data) async throws { |
| - try await outbox.enqueue(lane: lane, kind: "update", payload: update) |
| + let entry = try await outbox.enqueue(lane: lane, kind: "update", payload: update) |
| + held.insert(entry.id) |
| commandsDurable += 1 |
| } |
| @discardableResult func persist() async throws -> Bool { |
| @@ -67,7 +72,10 @@ struct PersistedReplica: Codable, Sendable { |
| guard merged.count <= 512 * 1024 else { return } |
| // A send can reserve the batch while mergeUpdates suspends. Refusing |
| // that compaction is expected; it must never delete the reservation. |
| - do { try await outbox.replace(batch.map(\.id), with: merged) } |
| + do { |
| + let replaced = try await outbox.replace(batch.map(\.id), with: merged) |
| + if batch.allSatisfy({ held.contains($0.id) }) { held.insert(replaced.id) } |
| + } |
| catch OutboxError.inFlight { } |
| catch OutboxError.unknownEntry { } |
| } |
diff --git a/native/apple/Sources/DocsKit/DocsWorkspace.swift b/native/apple/Sources/DocsKit/DocsWorkspace.swift| index b2777a1..918d3f4 100644 |
| --- a/native/apple/Sources/DocsKit/DocsWorkspace.swift |
| +++ b/native/apple/Sources/DocsKit/DocsWorkspace.swift |
| @@ -140,6 +140,12 @@ import SwiftUI |
| .sheet(isPresented: $jumping) { DocsJumpSheet(model: model, client: liveClient) } |
| .onDisappear { Task { await model.stop() } } |
| .onChange(of: scenePhase) { _, phase in |
| + #if os(iOS) |
| + // No stream in the background: its heartbeat would keep the radio |
| + // up, and a suspended app's connection only returns as an error. |
| + if phase == .background { model.suspendLiveUpdates() } |
| + if phase == .active { model.resumeLiveUpdates() } |
| + #endif |
| if phase == .background { Task { await model.persistReplica() } } |
| if phase == .active { Task { try? await model.offlineAccount.activate() } } |
| } |
diff --git a/native/apple/Tests/DocsKitTests/RealtimeSyncTests.swift b/native/apple/Tests/DocsKitTests/RealtimeSyncTests.swift| new file mode 100644 |
| index 0000000..409aa78 |
| --- /dev/null |
| +++ b/native/apple/Tests/DocsKitTests/RealtimeSyncTests.swift |
| @@ -0,0 +1,277 @@ |
| +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 the next row and announced on every stream before it is |
| +/// answered (as handlers.go `updatesPost` does), and answered with its |
| +/// `Docs-Seq`. It counts what the client asks for. |
| +private actor SequencedServer: NativeTransport { |
| + nonisolated let origin = URL(string: "http://localhost:8099")! |
| + private let replica = CRDTReplica(guid: "realtime-sync") |
| + private(set) var sequence: Int64 = 0 |
| + private var rows: [Int64: Data] = [:] |
| + private var listeners: [UUID: AsyncStream<Int64>.Continuation] = [:] |
| + 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 |
| + func open(_ seed: Data) async throws { _ = try await replica.open(update: seed) } |
| + /// Someone else's change lands just before this client's next POST. |
| + func interleavePeer(_ update: Data, thenFail: Bool = false) { peerBeforeNextPost = update; failNextPost = thenFail } |
| + func commit(_ update: Data) async throws { |
| + _ = try await replica.apply(update); sequence += 1; rows[sequence] = update |
| + for listener in listeners.values { listener.yield(sequence) } |
| + } |
| + func text() async throws -> String { try await replica.projection().children.map(\.plainText).joined(separator: "\n") } |
| + func responseDetails(_ path: String, method: String, body: Data?, contentType: String, maxBytes: Int) async throws -> NativeResponse { |
| + if method == "POST", path.hasSuffix("/updates"), let body { |
| + posts.append(.now) |
| + if let peer = peerBeforeNextPost { peerBeforeNextPost = nil; try await commit(peer) } |
| + // 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) } |
| + try await commit(body) |
| + return NativeResponse(data: Data(), status: 204, headers: ["Docs-Seq": String(sequence)]) |
| + } |
| + if path.contains("/updates") { |
| + let since = URLComponents(string: path)?.queryItems?.first(where: { $0.name == "since" })?.value.flatMap(Int64.init) ?? 0 |
| + let data: Data |
| + if since > 0 { |
| + catchUps += 1 |
| + let updates = rows.keys.sorted().filter { $0 > since }.compactMap { rows[$0] } |
| + data = updates.isEmpty ? Data() : try await replica.mergeUpdates(updates) |
| + } else { data = try await replica.persistentState().state } |
| + return NativeResponse(data: data, status: 200, headers: ["Docs-Seq": String(sequence)]) |
| + } |
| + let detail = DocumentDetail(sqid: "doc", 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 { |
| + let id = UUID(), events = AsyncStream<Int64>.makeStream(bufferingPolicy: .bufferingNewest(1)) |
| + listeners[id] = events.continuation |
| + defer { listeners.removeValue(forKey: id) } |
| + try await onOpen(); try await onLine("data: \(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 { 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) async throws -> Data { |
| + let peer = CRDTReplica(guid: "realtime-sync") |
| + let state = try await server.responseDetails("/d/doc/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() |
| + } |
| + |
| + /// 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() |
| + } |
| + |
| + /// 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() |
| + } |
| +} |