Docs listen waits on connectivity and backs off; show the offline banner
K2 of the offline-kit spec, Docs half. The stream loop slept a fixed 2 s between attempts (DocsModel listen): a restored network waited out the sleep, and an offline Mac or iPhone retried on a timer for ever. - listen now backs off with the kit's Backoff (0.5 s doubling to 10 s, jittered, Retry-After honoured, reset after a stream that lived more than 5 s) and waits with NativeConnectivity.wait, which a path change or foreground cuts short and which runs no timer while the path is down. A change also resets the backoff. - DocsModel takes a connectivity (default: the shared one); the workspace shows NativeOfflineBanner for its server. The copy says only "You're offline. Waiting for a connection.": edits are not durable across a relaunch until K3, so it must not claim they are saved. English only for now (other languages fall back to it until the wording is reviewed and translated). - Pins rastrillo/native feat/k2-connectivity-backoff (daf6e65). Tests with ScriptedTransport and ScriptedPathSource: no stream attempts over 2.6 s with the path down and a reconnect within 1 s of it coming back; quick stream failures retried two or three times in 1.5 s, not once every 2 s.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
9 files changed,
+98
−9
native/apple/Package.resolved+1 −1native/apple/Package.swift+2 −2native/apple/Sources/DocsKit/DocsModel.swift+20 −3native/apple/Sources/DocsKit/DocsWorkspace.swift+4 −0native/apple/Sources/DocsKit/Resources/en.lproj/Localizable.strings+1 −0native/apple/Tests/DocsKitTests/StreamConnectivityTests.swift+67 −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 a081e96..3cb1703 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" : "2986f5186d6ebdd4e72c42afd66b8316d81c0746" |
| + "revision" : "daf6e652d78552fe468a91ef45b4b1dcf3165926" |
| } |
| }, |
| { |
diff --git a/native/apple/Package.swift b/native/apple/Package.swift| index 9151f03..5b5b1a9 100644 |
| --- a/native/apple/Package.swift |
| +++ b/native/apple/Package.swift |
| @@ -3,14 +3,14 @@ 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: "2986f5186d6ebdd4e72c42afd66b8316d81c0746") |
| + ?? .package(url: "https://amadan.net/rastrillo/native", revision: "daf6e652d78552fe468a91ef45b4b1dcf3165926") |
| let package = Package(name: "DocsNative", defaultLocalization: "en", platforms: [.macOS(.v26), .iOS(.v26)], |
| products: [.library(name: "DocsKit", targets: ["DocsKit"]), .executable(name: "DocsMac", targets: ["DocsMac"])], |
| dependencies: [sharedNative], |
| targets: [ |
| .binaryTarget(name: "DocsCRDT", path: "Artifacts/DocsCRDT.xcframework"), |
| - .target(name: "DocsKit", dependencies: ["DocsCRDT", .product(name: "RastrilloApple", package: "native")], resources: [.process("Resources")]), |
| + .target(name: "DocsKit", dependencies: ["DocsCRDT", .product(name: "RastrilloApple", package: "native"), .product(name: "RastrilloNative", 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", .product(name: "RastrilloTestSupport", package: "native")]), |
| .testTarget(name: "DocsWindowTests", dependencies: ["DocsMac", .product(name: "RastrilloApple", package: "native")]), |
diff --git a/native/apple/Sources/DocsKit/DocsModel.swift b/native/apple/Sources/DocsKit/DocsModel.swift| index 6f5dad7..2fd68ca 100644 |
| --- a/native/apple/Sources/DocsKit/DocsModel.swift |
| +++ b/native/apple/Sources/DocsKit/DocsModel.swift |
| @@ -1,6 +1,7 @@ |
| import Foundation |
| import Observation |
| import RastrilloApple |
| +import RastrilloNative |
| @MainActor @Observable final class DocsModel { |
| enum ListState { case loading, loaded, failed } |
| @@ -43,11 +44,17 @@ import RastrilloApple |
| /// 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) { |
| + /// The stream loop waits on this between attempts, so a restored network |
| + /// reconnects at once and an offline device makes no timed attempts. |
| + let connectivity: NativeConnectivity |
| + init(transport: @escaping @MainActor () -> NativeTransport?, connectivity: NativeConnectivity? = nil, draft: Bool = false) { |
| self.transport = transport |
| + self.connectivity = connectivity ?? .shared |
| if draft { draftToken = UUID().uuidString } |
| } |
| - convenience init(client: NativeTransport, draft: Bool = false) { self.init(transport: { client }, draft: draft) } |
| + convenience init(client: NativeTransport, connectivity: NativeConnectivity? = nil, draft: Bool = false) { |
| + self.init(transport: { client }, connectivity: connectivity, draft: draft) |
| + } |
| private func client() throws -> NativeTransport { |
| guard let current = transport() else { throw NativeClientError.unauthorized } |
| return current |
| @@ -318,8 +325,11 @@ import RastrilloApple |
| } |
| private func listen(_ sqid: String) async { |
| let epoch = documentEpoch |
| + var backoff = Backoff() |
| while !Task.isCancelled, documentEpoch == epoch, detail?.sqid == sqid { |
| await flush() |
| + let opened = ContinuousClock.now |
| + var retryAfter: TimeInterval? |
| do { |
| try await client().stream("/d/\(sqid)/stream") { [weak self] line in |
| if line.hasPrefix("data:"), let seq = Int64(line.dropFirst(5).trimmingCharacters(in: .whitespaces)) { |
| @@ -327,12 +337,19 @@ import RastrilloApple |
| } |
| } |
| } catch { |
| + if case NativeClientError.rateLimited(let after) = error { retryAfter = after } |
| if !Task.isCancelled, documentEpoch == epoch { |
| errorKey = "docs.editor.status.retrying" |
| await refreshAccess(sqid, epoch: epoch) |
| } |
| } |
| - try? await Task.sleep(for: .seconds(2)) |
| + // A fixed sleep here reconnected two seconds after the network came |
| + // back and kept retrying on a timer while it was gone. Back off |
| + // instead, cut short by any connectivity change, with no timer at |
| + // all while the path is down. |
| + let lived = opened.duration(to: .now) |
| + backoff.connectionEnded(after: Double(lived.components.seconds) + Double(lived.components.attoseconds) / 1e18) |
| + if await connectivity.wait(upTo: backoff.next(retryAfter: retryAfter)) { backoff.reset() } |
| } |
| } |
| private func refresh(_ sqid: String, remoteSequence: Int64) async { |
diff --git a/native/apple/Sources/DocsKit/DocsWorkspace.swift b/native/apple/Sources/DocsKit/DocsWorkspace.swift| index 1ecf7bd..004cb35 100644 |
| --- a/native/apple/Sources/DocsKit/DocsWorkspace.swift |
| +++ b/native/apple/Sources/DocsKit/DocsWorkspace.swift |
| @@ -67,6 +67,10 @@ import SwiftUI |
| NavigationSplitView(preferredCompactColumn: $column) { library } detail: { editor } |
| #endif |
| } |
| + .safeAreaInset(edge: .top, spacing: 0) { |
| + NativeOfflineBanner(connectivity: model.connectivity, origin: client.origin, |
| + message: String(localized: "docs.offline.banner", defaultValue: "You’re offline. Waiting for a connection.", bundle: DocsResources.bundle)) |
| + } |
| .onChange(of: model.documents.map { "\($0.sqid)\u{0}\($0.title)" }) { |
| if query.isEmpty { updateRecents?(model.documents.map { ($0.sqid, $0.title) }) } |
diff --git a/native/apple/Sources/DocsKit/Resources/en.lproj/Localizable.strings b/native/apple/Sources/DocsKit/Resources/en.lproj/Localizable.strings| index 806b558..875281e 100644 |
| --- a/native/apple/Sources/DocsKit/Resources/en.lproj/Localizable.strings |
| +++ b/native/apple/Sources/DocsKit/Resources/en.lproj/Localizable.strings |
| @@ -177,3 +177,4 @@ |
| "native.discard.action" = "Discard changes"; |
| "docs.document.rename" = "Rename document"; |
| +"docs.offline.banner" = "You’re offline. Waiting for a connection."; |
diff --git a/native/apple/Tests/DocsKitTests/StreamConnectivityTests.swift b/native/apple/Tests/DocsKitTests/StreamConnectivityTests.swift| new file mode 100644 |
| index 0000000..42a7889 |
| --- /dev/null |
| +++ b/native/apple/Tests/DocsKitTests/StreamConnectivityTests.swift |
| @@ -0,0 +1,67 @@ |
| +import Foundation |
| +import RastrilloApple |
| +import RastrilloTestSupport |
| +import XCTest |
| +@testable import DocsKit |
| + |
| +/// One writable, empty document whose stream answers with `stream`. |
| +private func documentServer(stream: ScriptedTransport.Step) -> 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 stream |
| + case (.request, "POST", "/d/doc/updates"): return .respond(status: 204) |
| + default: return nil |
| + } |
| + } |
| +} |
| + |
| +private func streams(_ transport: ScriptedTransport) -> Int { transport.calls.filter { $0.kind == .stream }.count } |
| + |
| +@MainActor private func until(_ seconds: Double, _ condition: () -> Bool) async { |
| + let deadline = Date().addingTimeInterval(seconds) |
| + while !condition() && Date() < deadline { try? await Task.sleep(for: .milliseconds(10)) } |
| +} |
| + |
| +final class StreamConnectivityTests: XCTestCase { |
| + /// Offline, the stream loop makes no timed attempts; when the path comes |
| + /// back it reconnects at once rather than after a fixed sleep. |
| + @MainActor func testStreamWaitsForThePathAndReconnectsWhenItReturns() async throws { |
| + let path = ScriptedPathSource(.satisfied) |
| + let connectivity = NativeConnectivity(source: path) |
| + let server = documentServer(stream: .offline(.notConnectedToInternet)) |
| + let model = DocsModel(client: server, connectivity: connectivity) |
| + await model.open("doc") |
| + await until(2) { streams(server) >= 1 } |
| + path.send(.unsatisfied) |
| + await until(2) { connectivity.isPathSatisfied == false } |
| + try await Task.sleep(for: .milliseconds(600)) |
| + let offline = streams(server) |
| + try await Task.sleep(for: .milliseconds(2600)) |
| + XCTAssertEqual(streams(server), offline, "The stream retried on a timer while the path was down") |
| + let restored = Date() |
| + path.send(.satisfied) |
| + await until(2) { streams(server) > offline } |
| + XCTAssertGreaterThan(streams(server), offline, "The restored path never reconnected the stream") |
| + XCTAssertLessThan(Date().timeIntervalSince(restored), 1, "The reconnect waited out a sleep") |
| + await model.discardAll() |
| + } |
| + |
| + /// A stream that keeps closing at once is retried at 0.5 s, then 1 s, then |
| + /// 2 s (with jitter), not at a fixed interval. |
| + @MainActor func testStreamBacksOffBetweenQuickFailures() async throws { |
| + let connectivity = NativeConnectivity(source: ScriptedPathSource(.satisfied)) |
| + let server = documentServer(stream: .respond(status: 200)) |
| + let model = DocsModel(client: server, connectivity: connectivity) |
| + await model.open("doc") |
| + await until(2) { streams(server) >= 1 } |
| + try await Task.sleep(for: .milliseconds(1500)) |
| + let early = streams(server) |
| + // Attempts at 0, then +[0.25, 0.5], +[0.5, 1], +[1, 2]: two or three by 1.5 s. |
| + XCTAssertGreaterThanOrEqual(early, 2, "The first retry waited longer than the first backoff step") |
| + XCTAssertLessThanOrEqual(early, 3, "Retries did not back off") |
| + await model.discardAll() |
| + } |
| +} |
diff --git a/native/ios/project.yml b/native/ios/project.yml| index c8bad27..4a137b0 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: 2986f5186d6ebdd4e72c42afd66b8316d81c0746 |
| + revision: daf6e652d78552fe468a91ef45b4b1dcf3165926 |
| settings: |
| base: |
| SWIFT_VERSION: '6.0' |
diff --git a/native/macos/project.yml b/native/macos/project.yml| index 4faa32b..40ba674 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: 2986f5186d6ebdd4e72c42afd66b8316d81c0746 |
| + revision: daf6e652d78552fe468a91ef45b4b1dcf3165926 |
| settings: |
| base: |
| SWIFT_VERSION: '6.0' |
diff --git a/native/smoke/document-window/Package.resolved b/native/smoke/document-window/Package.resolved| index 8e60eba..025c5eb 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" : "2986f5186d6ebdd4e72c42afd66b8316d81c0746" |
| + "revision" : "daf6e652d78552fe468a91ef45b4b1dcf3165926" |
| } |
| }, |
| { |