Docs asks for its native transport per request (offline K1)
DocsModel takes a @MainActor () -> NativeTransport? supplier and asks it on every request, instead of capturing a client at init. The account-ID guard (DocsKit.DocsAccountTransport.supplier) hands out a session only while the model's own account is active, so an in-flight request keeps its own client and nothing is sent with another account's session. Pins rastrillo/native main 2986f51 (typed errors, NativeTransport). Reviewed by GPT-6-Astra via Codex (#66); nits addressed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Squashed from feat/k1-transport-supplier into main.
11 files changed,
+323
−23
native/apple/Package.resolved+1 −1native/apple/Package.swift+2 −2native/apple/Sources/DocsApp/DocsAccountWindow.swift+9 −2native/apple/Sources/DocsKit/DocsAccountTransport.swift+22 −0native/apple/Sources/DocsKit/DocsModel.swift+25 −13native/apple/Sources/DocsKit/DocsWorkspace.swift+4 −2native/apple/Tests/DocsKitTests/AccountBoundaryTests.swift+178 −0native/apple/Tests/DocsKitTests/TransportSupplierTests.swift+79 −0native/ios/project.yml+1 −1native/macos/project.yml+1 −1native/smoke/document-window/Package.resolved+1 −1
CI passed — run details
diff --git a/native/apple/Package.resolved b/native/apple/Package.resolved| index b97f847..a081e96 100644 |
| --- a/native/apple/Package.resolved |
| +++ b/native/apple/Package.resolved |
| @@ -6,7 +6,7 @@ |
| "kind" : "remoteSourceControl", |
| "location" : "https://amadan.net/rastrillo/native", |
| "state" : { |
| - "revision" : "2a5d07b2c8d3dfb3fd8526dc7e1c802f97865c67" |
| + "revision" : "2986f5186d6ebdd4e72c42afd66b8316d81c0746" |
| } |
| }, |
| { |
diff --git a/native/apple/Package.swift b/native/apple/Package.swift| index 12a98cb..9151f03 100644 |
| --- a/native/apple/Package.swift |
| +++ b/native/apple/Package.swift |
| @@ -3,7 +3,7 @@ import PackageDescription |
| import Foundation |
| let sharedNative: Package.Dependency = ProcessInfo.processInfo.environment["OFICINA_NATIVE_PACKAGE_PATH"].map { .package(name: "native", path: $0) } |
| - ?? .package(url: "https://amadan.net/rastrillo/native", revision: "2a5d07b2c8d3dfb3fd8526dc7e1c802f97865c67") |
| + ?? .package(url: "https://amadan.net/rastrillo/native", revision: "2986f5186d6ebdd4e72c42afd66b8316d81c0746") |
| let package = Package(name: "DocsNative", defaultLocalization: "en", platforms: [.macOS(.v26), .iOS(.v26)], |
| products: [.library(name: "DocsKit", targets: ["DocsKit"]), .executable(name: "DocsMac", targets: ["DocsMac"])], |
| @@ -12,6 +12,6 @@ let package = Package(name: "DocsNative", defaultLocalization: "en", platforms: |
| .binaryTarget(name: "DocsCRDT", path: "Artifacts/DocsCRDT.xcframework"), |
| .target(name: "DocsKit", dependencies: ["DocsCRDT", .product(name: "RastrilloApple", package: "native")], resources: [.process("Resources")]), |
| .executableTarget(name: "DocsMac", dependencies: [.product(name: "RastrilloMacUpdates", package: "native", condition: .when(platforms: [.macOS])), "DocsKit", .product(name: "RastrilloApple", package: "native")], path: "Sources/DocsApp"), |
| - .testTarget(name: "DocsKitTests", dependencies: ["DocsKit"]), |
| + .testTarget(name: "DocsKitTests", dependencies: ["DocsKit", .product(name: "RastrilloTestSupport", package: "native")]), |
| .testTarget(name: "DocsWindowTests", dependencies: ["DocsMac", .product(name: "RastrilloApple", package: "native")]), |
| ]) |
diff --git a/native/apple/Sources/DocsApp/DocsAccountWindow.swift b/native/apple/Sources/DocsApp/DocsAccountWindow.swift| index 4ae4781..6f33d51 100644 |
| --- a/native/apple/Sources/DocsApp/DocsAccountWindow.swift |
| +++ b/native/apple/Sources/DocsApp/DocsAccountWindow.swift |
| @@ -10,12 +10,19 @@ struct DocsAccountWindow: View { |
| @Bindable var windows: DocsWindows |
| @Environment(\.openWindow) private var openWindow |
| #endif |
| + private func transport(for account: String?) -> @MainActor () -> NativeTransport? { |
| + let connection = connection |
| + return DocsAccountTransport.supplier(account: account, |
| + active: { [weak connection] in connection?.activeAccountID }, |
| + client: { [weak connection] in connection?.client }) |
| + } |
| + |
| var body: some View { |
| Group { |
| if let client = connection.client { |
| #if os(macOS) |
| if let account = connection.activeAccountID { |
| - DocsWorkspace(client: client, accounts: connection.showAccounts, signOut: { |
| + DocsWorkspace(client: client, transport: transport(for: account), accounts: connection.showAccounts, signOut: { |
| guard connection.activeAccountID == account, windows.canSignOut(account) else { return } |
| windows.entries.removeAll { $0.account == account } |
| connection.signOut() |
| @@ -34,7 +41,7 @@ struct DocsAccountWindow: View { |
| .id(account) |
| } |
| #else |
| - DocsWorkspace(client: client, accounts: connection.showAccounts, signOut: connection.signOut) |
| + DocsWorkspace(client: client, transport: transport(for: connection.activeAccountID), accounts: connection.showAccounts, signOut: connection.signOut) |
| .id(connection.activeAccountID) |
| #endif |
| } else { |
diff --git a/native/apple/Sources/DocsKit/DocsAccountTransport.swift b/native/apple/Sources/DocsKit/DocsAccountTransport.swift| new file mode 100644 |
| index 0000000..4cf5786 |
| --- /dev/null |
| +++ b/native/apple/Sources/DocsKit/DocsAccountTransport.swift |
| @@ -0,0 +1,22 @@ |
| +import Foundation |
| +import RastrilloApple |
| + |
| +/// The transport supplier a window hands its workspace, for one account. |
| +/// |
| +/// A workspace's model can outlive a session of its account, so it asks for |
| +/// the connection's current client on every request instead of keeping one. |
| +/// It must never be handed another account's session, even for a moment: |
| +/// SwiftUI can still be finishing a request or holding a stream for the old |
| +/// workspace after the window switches accounts. |
| +public enum DocsAccountTransport { |
| + @MainActor public static func supplier(account: String?, |
| + active: @escaping @MainActor () -> String?, |
| + client: @escaping @MainActor () -> NativeTransport?) -> @MainActor () -> NativeTransport? { |
| + return { |
| + // Checked on every request, not when the supplier is made: a |
| + // switch can land while a save or stream reconnect is in flight. |
| + guard let account, active() == account else { return nil } |
| + return client() |
| + } |
| + } |
| +} |
diff --git a/native/apple/Sources/DocsKit/DocsModel.swift b/native/apple/Sources/DocsKit/DocsModel.swift| index 545f7f0..6f5dad7 100644 |
| --- a/native/apple/Sources/DocsKit/DocsModel.swift |
| +++ b/native/apple/Sources/DocsKit/DocsModel.swift |
| @@ -38,8 +38,20 @@ import RastrilloApple |
| private var saving = false |
| private var documentEpoch = UUID() |
| private let publications = DocumentPublication() |
| - private let client: NativeHTTP |
| - init(client: NativeHTTP, draft: Bool = false) { self.client = client; if draft { draftToken = UUID().uuidString } } |
| + /// Resolved on every request, never captured: this model can hold unsent |
| + /// edits for longer than one session, and signing in again replaces the |
| + /// transport under it. A captured client would keep sending with the ended |
| + /// session. nil means no session; requests then fail as `.unauthorized`. |
| + private let transport: @MainActor () -> NativeTransport? |
| + init(transport: @escaping @MainActor () -> NativeTransport?, draft: Bool = false) { |
| + self.transport = transport |
| + if draft { draftToken = UUID().uuidString } |
| + } |
| + convenience init(client: NativeTransport, draft: Bool = false) { self.init(transport: { client }, draft: draft) } |
| + private func client() throws -> NativeTransport { |
| + guard let current = transport() else { throw NativeClientError.unauthorized } |
| + return current |
| + } |
| var hasPendingInput: Bool { !editing.isEmpty || editingTask != nil } |
| var hasUnsavedChanges: Bool { (renameInput != nil && renameInput != detail?.title) || isDraft || pendingTitle != nil || composing || !pending.isEmpty || !editing.isEmpty || editingTask != nil } |
| func load(query: String = "") async { |
| @@ -48,7 +60,7 @@ import RastrilloApple |
| do { |
| var components = URLComponents(); components.queryItems = [URLQueryItem(name: "q", value: query)] |
| let q = (components.percentEncodedQuery ?? "").replacingOccurrences(of: "+", with: "%2B") |
| - let response: DocumentList = try await client.request("/?\(q)") |
| + let response: DocumentList = try await client().request("/?\(q)") |
| guard listRequest == request, !Task.isCancelled else { return } |
| documents = response.documents; canCreate = response.can_create |
| listState = .loaded; errorKey = nil |
| @@ -91,12 +103,12 @@ import RastrilloApple |
| guard let token = draftToken, let local = replica else { return } |
| do { |
| let body = Self.form(["title": detail?.title ?? "", "creation_token": token]) |
| - let (data, status) = try await client.response("/documents", method: "POST", body: body, contentType: "application/x-www-form-urlencoded") |
| + let (data, status) = try await client().response("/documents", method: "POST", body: body, contentType: "application/x-www-form-urlencoded") |
| guard status == 201 else { throw CRDTReplica.Failure.rejected } |
| let item = try JSONDecoder().decode(DocumentSummary.self, from: data) |
| guard documentEpoch == epoch else { return } |
| - let attached: DocumentDetail = try await client.request("/d/\(item.sqid)") |
| - let reply = try await client.responseDetails("/d/\(item.sqid)/updates", maxBytes: 8 * 1024 * 1024) |
| + let attached: DocumentDetail = try await client().request("/d/\(item.sqid)") |
| + let reply = try await client().responseDetails("/d/\(item.sqid)/updates", maxBytes: 8 * 1024 * 1024) |
| guard reply.status == 200, let seq = Int64(reply.header("Docs-Seq") ?? ""), attached.can_write else { throw CRDTReplica.Failure.rejected } |
| guard documentEpoch == epoch else { return } |
| if !reply.data.isEmpty { _ = try await local.apply(reply.data) } |
| @@ -142,8 +154,8 @@ import RastrilloApple |
| guard documentEpoch == epoch else { return } |
| defer { if documentEpoch == epoch { loading = false } } |
| do { |
| - let detail: DocumentDetail = try await client.request("/d/\(sqid)") |
| - let reply = try await client.responseDetails("/d/\(sqid)/updates", maxBytes: 8 * 1024 * 1024) |
| + let detail: DocumentDetail = try await client().request("/d/\(sqid)") |
| + let reply = try await client().responseDetails("/d/\(sqid)/updates", maxBytes: 8 * 1024 * 1024) |
| guard reply.status == 200, let seq = Int64(reply.header("Docs-Seq") ?? "") else { throw CRDTReplica.Failure.rejected } |
| guard documentEpoch == epoch else { return } |
| let replica = CRDTReplica(guid: detail.guid) |
| @@ -267,7 +279,7 @@ import RastrilloApple |
| while !pending.isEmpty || pendingTitle != nil { |
| if let title = pendingTitle { |
| do { |
| - let (_, status) = try await client.response("/d/\(detail.sqid)/title", method: "POST", body: Self.form(["title": title]), contentType: "application/x-www-form-urlencoded") |
| + let (_, status) = try await client().response("/d/\(detail.sqid)/title", method: "POST", body: Self.form(["title": title]), contentType: "application/x-www-form-urlencoded") |
| guard documentEpoch == epoch else { return } |
| guard status == 204 else { throw CRDTReplica.Failure.rejected } |
| if pendingTitle == title { pendingTitle = nil } |
| @@ -293,7 +305,7 @@ import RastrilloApple |
| count = 1 |
| } |
| guard documentEpoch == epoch else { return } |
| - let (_, status) = try await client.response("/d/\(detail.sqid)/updates", method: "POST", body: update, contentType: "application/octet-stream") |
| + let (_, status) = try await client().response("/d/\(detail.sqid)/updates", method: "POST", body: update, contentType: "application/octet-stream") |
| guard documentEpoch == epoch else { return } |
| guard status == 204 else { |
| if status == 401 || status == 403 || status == 404 { await refreshAccess(detail.sqid, epoch: epoch) } |
| @@ -309,7 +321,7 @@ import RastrilloApple |
| while !Task.isCancelled, documentEpoch == epoch, detail?.sqid == sqid { |
| await flush() |
| do { |
| - try await client.stream("/d/\(sqid)/stream") { [weak self] line in |
| + try await client().stream("/d/\(sqid)/stream") { [weak self] line in |
| if line.hasPrefix("data:"), let seq = Int64(line.dropFirst(5).trimmingCharacters(in: .whitespaces)) { |
| await self?.refresh(sqid, remoteSequence: seq) |
| } |
| @@ -327,7 +339,7 @@ import RastrilloApple |
| let epoch = documentEpoch |
| guard detail?.sqid == sqid, remoteSequence > sequence, let replica else { return } |
| do { |
| - let reply = try await client.responseDetails("/d/\(sqid)/updates?since=\(sequence)", maxBytes: 8 * 1024 * 1024) |
| + 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 } |
| guard self.detail?.sqid == sqid, self.replica === replica else { return } |
| _ = try await replica.apply(reply.data) |
| @@ -342,7 +354,7 @@ import RastrilloApple |
| let revision = titleRevision |
| let hadPendingTitle = pendingTitle != nil |
| do { |
| - let reply = try await client.responseDetails("/d/\(sqid)", maxBytes: 1024 * 1024) |
| + let reply = try await client().responseDetails("/d/\(sqid)", maxBytes: 1024 * 1024) |
| guard documentEpoch == epoch else { return } |
| if reply.status == 200 { |
| let current = try JSONDecoder().decode(DocumentDetail.self, from: reply.data) |
diff --git a/native/apple/Sources/DocsKit/DocsWorkspace.swift b/native/apple/Sources/DocsKit/DocsWorkspace.swift| index 5c28ab3..1ecf7bd 100644 |
| --- a/native/apple/Sources/DocsKit/DocsWorkspace.swift |
| +++ b/native/apple/Sources/DocsKit/DocsWorkspace.swift |
| @@ -27,10 +27,12 @@ import SwiftUI |
| private let signOut: () -> Void |
| private let accounts: (() -> Void)? |
| private let client: NativeHTTP |
| - public init(client: NativeHTTP, accounts: (() -> Void)? = nil, signOut: @escaping () -> Void, documentID: String? = nil, newDocument: Bool = false, createDocument: (() -> Void)? = nil, documentChanged: ((String, String) -> Void)? = nil, canSignOut: Bool = true, createRequested: Binding<Bool> = .constant(false), accountsRequested: Binding<Bool> = .constant(false), openDocument: ((String, String) -> Void)? = nil, updateRecents: (([(String, String)]) -> Void)? = nil) { |
| + /// `transport` supplies the account's current session to the model on every |
| + /// request; without one the model keeps `client` for its whole lifetime. |
| + public init(client: NativeHTTP, transport: (@MainActor () -> NativeTransport?)? = nil, accounts: (() -> Void)? = nil, signOut: @escaping () -> Void, documentID: String? = nil, newDocument: Bool = false, createDocument: (() -> Void)? = nil, documentChanged: ((String, String) -> Void)? = nil, canSignOut: Bool = true, createRequested: Binding<Bool> = .constant(false), accountsRequested: Binding<Bool> = .constant(false), openDocument: ((String, String) -> Void)? = nil, updateRecents: (([(String, String)]) -> Void)? = nil) { |
| self.updateRecents = updateRecents; self.canSignOut = canSignOut; self._createRequested = createRequested; self._accountsRequested = accountsRequested; self.documentID = documentID; self.openDocument = openDocument |
| self.newDocument = newDocument; self.createDocument = createDocument; self.documentChanged = documentChanged |
| - _model = State(initialValue: DocsModel(client: client, draft: newDocument)); self.signOut = signOut; self.accounts = accounts; self.client = client |
| + _model = State(initialValue: transport.map { DocsModel(transport: $0, draft: newDocument) } ?? DocsModel(client: client, draft: newDocument)); self.signOut = signOut; self.accounts = accounts; self.client = client |
| } |
| private var library: some View { |
| List { |
diff --git a/native/apple/Tests/DocsKitTests/AccountBoundaryTests.swift b/native/apple/Tests/DocsKitTests/AccountBoundaryTests.swift| new file mode 100644 |
| index 0000000..eb1a25f |
| --- /dev/null |
| +++ b/native/apple/Tests/DocsKitTests/AccountBoundaryTests.swift |
| @@ -0,0 +1,178 @@ |
| +import Foundation |
| +import RastrilloApple |
| +import RastrilloTestSupport |
| +import XCTest |
| +@testable import DocsKit |
| + |
| +/// Stands in for NativeConnection: which account is active, and each |
| +/// account's current session. |
| +@MainActor private final class Connection { |
| + var active: String? |
| + var sessions: [String: NativeTransport] = [:] |
| + init(active: String?) { self.active = active } |
| + var client: NativeTransport? { active.flatMap { sessions[$0] } } |
| + /// The production guard, wired the way DocsAccountWindow wires it. |
| + func supplier(for account: String?) -> @MainActor () -> NativeTransport? { |
| + DocsAccountTransport.supplier(account: account, active: { [weak self] in self?.active }, |
| + client: { [weak self] in self?.client }) |
| + } |
| +} |
| + |
| +/// Holds a request until the test releases it, so an account can switch |
| +/// while the request is in flight. |
| +private actor Gate { |
| + private var waiters: [CheckedContinuation<Void, Never>] = [] |
| + private var released = false |
| + var waiting: Int { waiters.count } |
| + func pass() async { |
| + if released { return } |
| + await withCheckedContinuation { waiters.append($0) } |
| + } |
| + func release() { |
| + released = true |
| + waiters.forEach { $0.resume() } |
| + waiters.removeAll() |
| + } |
| +} |
| + |
| +private final class GatedTransport: NativeTransport, @unchecked Sendable { |
| + let inner: ScriptedTransport |
| + let gate = Gate() |
| + let gatedPath: String |
| + init(_ inner: ScriptedTransport, gating path: String) { self.inner = inner; gatedPath = path } |
| + var origin: URL { inner.origin } |
| + func responseDetails(_ path: String, method: String, body: Data?, contentType: String, maxBytes: Int) async throws -> NativeResponse { |
| + if path == gatedPath { await gate.pass() } |
| + return try await inner.responseDetails(path, method: method, body: body, contentType: contentType, maxBytes: maxBytes) |
| + } |
| + func stream(_ path: String, onOpen: @Sendable () async throws -> Void, onLine: @Sendable (String) async throws -> Void) async throws { |
| + try await inner.stream(path, onOpen: onOpen, onLine: onLine) |
| + } |
| + func download(_ path: String, to destination: URL) async throws { try await inner.download(path, to: destination) } |
| +} |
| + |
| +private let listBody = Data(#"{"documents":[{"sqid":"d1","title":"Mine"}],"can_create":true}"#.utf8) |
| + |
| +/// One writable, empty document. `stream` says how its live stream answers. |
| +private func documentServer(stream: ScriptedTransport.Step = .hang) -> ScriptedTransport { |
| + ScriptedTransport { call in |
| + switch (call.kind, call.method, call.path) { |
| + case (.request, "GET", "/?q="): return .respond(status: 200, body: listBody) |
| + case (.request, "GET", "/d/doc"): |
| + return .respond(status: 200, body: Data(#"{"sqid":"doc","title":"Doc","guid":"doc-guid","can_write":true,"can_share":false}"#.utf8)) |
| + case (.request, "GET", "/d/doc/updates"): return .respond(status: 200, headers: ["Docs-Seq": "0"]) |
| + case (.stream, _, "/d/doc/stream"): return stream |
| + case (.request, "POST", "/d/doc/updates"): return .respond(status: 204) |
| + default: return nil |
| + } |
| + } |
| +} |
| + |
| +private func posts(_ transport: ScriptedTransport) -> Int { transport.committed.filter { $0.method == "POST" }.count } |
| + |
| +@MainActor private func settle(_ model: DocsModel, _ deadline: ContinuousClock.Instant) async throws { |
| + while model.hasUnsavedChanges && .now < deadline { try await Task.sleep(for: .milliseconds(10)) } |
| +} |
| + |
| +@MainActor private func edit(_ model: DocsModel, _ text: String) -> Bool { |
| + model.didRender(model.projectionGeneration) |
| + return model.enqueue(["op": .string("display_edit"), "at": .number(0), "length": .number(0), "text": .string(text)]) |
| +} |
| + |
| +final class AccountBoundaryTests: XCTestCase { |
| + @MainActor func testSupplierNeverHandsOverAnotherAccountsSession() async { |
| + let mine = documentServer(), theirs = documentServer() |
| + let connection = Connection(active: "a") |
| + connection.sessions = ["a": mine, "b": theirs] |
| + let model = DocsModel(transport: connection.supplier(for: "a")) |
| + await model.load() |
| + XCTAssertEqual(model.listState, .loaded) |
| + |
| + connection.active = "b" |
| + XCTAssertNil(connection.supplier(for: "a")(), "Account a's supplier returned b's session") |
| + await model.load() |
| + XCTAssertEqual(model.listState, .failed) |
| + XCTAssertTrue(theirs.calls.isEmpty, "Account a's model sent a request with account b's session") |
| + |
| + connection.active = "a" |
| + await model.load() |
| + XCTAssertEqual(model.listState, .loaded) |
| + XCTAssertEqual(mine.calls.count, 2) |
| + XCTAssertNil(Connection(active: nil).supplier(for: nil)(), "A window with no account got a session") |
| + } |
| + |
| + /// A signed-out account (the connection has no client) sends nothing, and |
| + /// the same model picks the session up when it comes back. |
| + @MainActor func testNilSupplierSendsNothingUntilTheSessionReturns() async { |
| + let connection = Connection(active: "a") |
| + let model = DocsModel(transport: connection.supplier(for: "a")) |
| + await model.load() |
| + XCTAssertEqual(model.listState, .failed) |
| + let session = documentServer() |
| + connection.sessions["a"] = session |
| + await model.load() |
| + XCTAssertEqual(model.listState, .loaded, "The model kept the missing session it started with") |
| + XCTAssertEqual(session.calls.count, 1) |
| + } |
| + |
| + /// A save in flight when the window switches accounts finishes on the |
| + /// session it started with; the next edit waits instead of going out on |
| + /// the other account's session, and is sent when its own account returns. |
| + @MainActor func testAccountSwitchDuringAnInFlightSave() async throws { |
| + let mine = GatedTransport(documentServer(), gating: "/d/doc/updates") |
| + let theirs = documentServer() |
| + let connection = Connection(active: "a") |
| + connection.sessions = ["a": mine, "b": theirs] |
| + let model = DocsModel(transport: connection.supplier(for: "a")) |
| + await mine.gate.release() |
| + await model.open("doc") |
| + let deadline = ContinuousClock.now.advanced(by: .seconds(5)) |
| + try await settle(model, deadline) |
| + XCTAssertFalse(model.hasUnsavedChanges) |
| + |
| + let gated = GatedTransport(mine.inner, gating: "/d/doc/updates") |
| + connection.sessions["a"] = gated |
| + XCTAssertTrue(edit(model, "In flight ")) |
| + while await gated.gate.waiting == 0 && .now < deadline { try await Task.sleep(for: .milliseconds(5)) } |
| + connection.active = "b" |
| + await gated.gate.release() |
| + try await settle(model, deadline) |
| + XCTAssertFalse(model.hasUnsavedChanges, "The in-flight save was lost") |
| + let sent = posts(mine.inner) |
| + |
| + XCTAssertTrue(edit(model, "Queued ")) |
| + let wait = ContinuousClock.now.advanced(by: .milliseconds(500)) |
| + try await settle(model, wait) |
| + XCTAssertTrue(model.hasUnsavedChanges, "An edit was acknowledged with no session for its account") |
| + XCTAssertTrue(theirs.calls.isEmpty, "Account a's edit went out on account b's session") |
| + XCTAssertEqual(posts(mine.inner), sent) |
| + |
| + connection.active = "a" |
| + await model.retry() |
| + try await settle(model, deadline) |
| + XCTAssertFalse(model.hasUnsavedChanges) |
| + XCTAssertEqual(posts(mine.inner), sent + 1) |
| + await model.discardAll() |
| + } |
| + |
| + /// The live stream reconnects every two seconds. After a switch, those |
| + /// reconnects must reach neither the other account nor, with the old |
| + /// account inactive, anyone. |
| + @MainActor func testAccountSwitchDuringAStream() async throws { |
| + let mine = documentServer(stream: .respond(status: 200)) |
| + let theirs = documentServer() |
| + let connection = Connection(active: "a") |
| + connection.sessions = ["a": mine, "b": theirs] |
| + let model = DocsModel(transport: connection.supplier(for: "a")) |
| + await model.open("doc") |
| + let deadline = ContinuousClock.now.advanced(by: .seconds(5)) |
| + while !mine.calls.contains(where: { $0.kind == .stream }) && .now < deadline { try await Task.sleep(for: .milliseconds(10)) } |
| + try await settle(model, deadline) |
| + connection.active = "b" |
| + let before = mine.calls.count |
| + try await Task.sleep(for: .milliseconds(2500)) |
| + XCTAssertTrue(theirs.calls.isEmpty, "The stream reconnected with account b's session: \(theirs.calls.map(\.path))") |
| + XCTAssertEqual(mine.calls.count, before, "The stream reconnected for an account that is no longer active") |
| + await model.discardAll() |
| + } |
| +} |
diff --git a/native/apple/Tests/DocsKitTests/TransportSupplierTests.swift b/native/apple/Tests/DocsKitTests/TransportSupplierTests.swift| new file mode 100644 |
| index 0000000..69dc031 |
| --- /dev/null |
| +++ b/native/apple/Tests/DocsKitTests/TransportSupplierTests.swift |
| @@ -0,0 +1,79 @@ |
| +import Foundation |
| +import RastrilloApple |
| +import RastrilloTestSupport |
| +import XCTest |
| +@testable import DocsKit |
| + |
| +/// Stands in for NativeConnection: which transport the account has right now. |
| +@MainActor private final class Session { |
| + var current: NativeTransport? |
| + init(_ current: NativeTransport?) { self.current = current } |
| +} |
| + |
| +private func list(_ titles: [String]) -> Data { |
| + let documents = titles.enumerated().map { #"{"sqid":"d\#($0.offset)","title":"\#($0.element)"}"# } |
| + return Data(#"{"documents":[\#(documents.joined(separator: ","))],"can_create":true}"#.utf8) |
| +} |
| + |
| +/// A server for one writable, empty document: its stream stays open without |
| +/// events, and every update is accepted. Answers by request, since the model's |
| +/// stream and saves race. |
| +private func documentServer() -> ScriptedTransport { |
| + ScriptedTransport { call in |
| + switch (call.kind, call.method, call.path) { |
| + case (.request, "GET", "/d/doc"): |
| + return .respond(status: 200, body: Data(#"{"sqid":"doc","title":"Doc","guid":"doc-guid","can_write":true,"can_share":false}"#.utf8)) |
| + case (.request, "GET", "/d/doc/updates"): |
| + return .respond(status: 200, headers: ["Docs-Seq": "0"]) |
| + case (.stream, _, "/d/doc/stream"): |
| + return .hang |
| + case (.request, "POST", "/d/doc/updates"): |
| + return .respond(status: 204) |
| + default: |
| + return nil |
| + } |
| + } |
| +} |
| + |
| +final class TransportSupplierTests: XCTestCase { |
| + @MainActor func testEachRequestUsesTheSessionsCurrentTransport() async { |
| + let first = ScriptedTransport([.respond(status: 200, body: list(["Before"]))]) |
| + let replacement = ScriptedTransport([.respond(status: 200, body: list(["After", "Signing in again"]))]) |
| + let session = Session(first) |
| + let model = DocsModel(transport: { session.current }) |
| + await model.load() |
| + XCTAssertEqual(model.documents.map(\.title), ["Before"]) |
| + session.current = replacement |
| + await model.load() |
| + XCTAssertEqual(model.listState, .loaded) |
| + XCTAssertEqual(model.documents.map(\.title), ["After", "Signing in again"]) |
| + XCTAssertEqual(first.calls.count, 1, "The model kept using the transport it was created with") |
| + XCTAssertEqual(replacement.calls.count, 1) |
| + } |
| + |
| + /// The case the supplier exists for: an edit made while one session |
| + /// is in place is sent with whichever session is current when it is sent. |
| + @MainActor func testUnsentEditGoesOutOnTheReplacementTransport() async throws { |
| + let ended = documentServer() |
| + let session = Session(ended) |
| + let model = DocsModel(transport: { session.current }) |
| + await model.open("doc") |
| + XCTAssertEqual(model.detail?.sqid, "doc") |
| + let deadline = ContinuousClock.now.advanced(by: .seconds(5)) |
| + // Opening an empty document inserts its first paragraph and saves it. |
| + while model.hasUnsavedChanges && .now < deadline { try await Task.sleep(for: .milliseconds(10)) } |
| + XCTAssertFalse(model.hasUnsavedChanges) |
| + let sentBefore = ended.committed.filter { $0.method == "POST" }.count |
| + |
| + let replacement = documentServer() |
| + session.current = replacement |
| + model.didRender(model.projectionGeneration) |
| + XCTAssertTrue(model.enqueue(["op": .string("display_edit"), "at": .number(0), "length": .number(0), "text": .string("Hello")])) |
| + while model.hasUnsavedChanges && .now < deadline { try await Task.sleep(for: .milliseconds(10)) } |
| + XCTAssertFalse(model.hasUnsavedChanges, "The edit was never acknowledged") |
| + |
| + XCTAssertEqual(ended.committed.filter { $0.method == "POST" }.count, sentBefore, "The edit went out on the ended session") |
| + XCTAssertEqual(replacement.committed.map(\.path), ["/d/doc/updates"]) |
| + await model.discardAll() |
| + } |
| +} |
diff --git a/native/ios/project.yml b/native/ios/project.yml| index 12b17bc..c8bad27 100644 |
| --- a/native/ios/project.yml |
| +++ b/native/ios/project.yml |
| @@ -8,7 +8,7 @@ packages: |
| path: ../apple |
| RastrilloNative: |
| url: https://amadan.net/rastrillo/native |
| - revision: 2a5d07b2c8d3dfb3fd8526dc7e1c802f97865c67 |
| + revision: 2986f5186d6ebdd4e72c42afd66b8316d81c0746 |
| settings: |
| base: |
| SWIFT_VERSION: '6.0' |
diff --git a/native/macos/project.yml b/native/macos/project.yml| index 2ce2237..4faa32b 100644 |
| --- a/native/macos/project.yml |
| +++ b/native/macos/project.yml |
| @@ -7,7 +7,7 @@ packages: |
| path: ../apple |
| RastrilloNative: |
| url: https://amadan.net/rastrillo/native |
| - revision: 2a5d07b2c8d3dfb3fd8526dc7e1c802f97865c67 |
| + revision: 2986f5186d6ebdd4e72c42afd66b8316d81c0746 |
| settings: |
| base: |
| SWIFT_VERSION: '6.0' |
diff --git a/native/smoke/document-window/Package.resolved b/native/smoke/document-window/Package.resolved| index 7ebafdc..8e60eba 100644 |
| --- a/native/smoke/document-window/Package.resolved |
| +++ b/native/smoke/document-window/Package.resolved |
| @@ -6,7 +6,7 @@ |
| "kind" : "remoteSourceControl", |
| "location" : "https://amadan.net/rastrillo/native", |
| "state" : { |
| - "revision" : "2a5d07b2c8d3dfb3fd8526dc7e1c802f97865c67" |
| + "revision" : "2986f5186d6ebdd4e72c42afd66b8316d81c0746" |
| } |
| }, |
| { |