Pace the native live stream with NativeConnectivity and NativeReconnect (offline K2)
The fixed 2 s reconnect loop is gone. The stream waits for connectivity (no attempts while the path is down; reconnects under a second after it returns), honours Retry-After as a deadline that wakes can't cross, and resets its backoff only after a stream has opened and stayed open more than 5 s. It shows the shared offline banner. Pins rastrillo/native main 14ee567. Reviewed by GPT-6-Astra via Codex; findings fixed in the kit (rastrillo/native #8) and checked by the coordinating session. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Squashed from feat/k2-connectivity into main.
9 files changed,
+158
−9
native/apple/Package.resolved+1 −1native/apple/Package.swift+1 −1native/apple/Sources/DocsKit/DocsModel.swift+18 −4native/apple/Sources/DocsKit/DocsWorkspace.swift+4 −0native/apple/Sources/DocsKit/Resources/en.lproj/Localizable.strings+1 −0native/apple/Tests/DocsKitTests/StreamConnectivityTests.swift+130 −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..8032174 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" : "14ee567be2e1816002c7db4274acaf2926983b4c" |
| } |
| }, |
| { |
diff --git a/native/apple/Package.swift b/native/apple/Package.swift| index 9151f03..b33e766 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: "2986f5186d6ebdd4e72c42afd66b8316d81c0746") |
| + ?? .package(url: "https://amadan.net/rastrillo/native", revision: "14ee567be2e1816002c7db4274acaf2926983b4c") |
| let package = Package(name: "DocsNative", defaultLocalization: "en", platforms: [.macOS(.v26), .iOS(.v26)], |
| products: [.library(name: "DocsKit", targets: ["DocsKit"]), .executable(name: "DocsMac", targets: ["DocsMac"])], |
diff --git a/native/apple/Sources/DocsKit/DocsModel.swift b/native/apple/Sources/DocsKit/DocsModel.swift| index 6f5dad7..1121011 100644 |
| --- a/native/apple/Sources/DocsKit/DocsModel.swift |
| +++ b/native/apple/Sources/DocsKit/DocsModel.swift |
| @@ -43,11 +43,19 @@ 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 |
| + /// Monotonic seconds for the stream loop's pacing; tests substitute a fake. |
| + var reconnectClock: @MainActor () -> TimeInterval = { ProcessInfo.processInfo.systemUptime } |
| + 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,21 +326,27 @@ import RastrilloApple |
| } |
| private func listen(_ sqid: String) async { |
| let epoch = documentEpoch |
| + // Paces reconnects: a server's Retry-After is a deadline no wake |
| + // crosses; otherwise back off, cut short by a connectivity change, |
| + // with no timer while the path is down. The backoff resets only after |
| + // a stream that stayed open for 5 s, timed from onOpen. |
| + let reconnect = NativeReconnect(connectivity: connectivity, now: reconnectClock) |
| 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", onOpen: { await reconnect.opened() }) { [weak self] line in |
| if line.hasPrefix("data:"), let seq = Int64(line.dropFirst(5).trimmingCharacters(in: .whitespaces)) { |
| await self?.refresh(sqid, remoteSequence: seq) |
| } |
| } |
| } catch { |
| + reconnect.failed(error) |
| if !Task.isCancelled, documentEpoch == epoch { |
| errorKey = "docs.editor.status.retrying" |
| await refreshAccess(sqid, epoch: epoch) |
| } |
| } |
| - try? await Task.sleep(for: .seconds(2)) |
| + await reconnect.pause() |
| } |
| } |
| 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..38f6731 |
| --- /dev/null |
| +++ b/native/apple/Tests/DocsKitTests/StreamConnectivityTests.swift |
| @@ -0,0 +1,130 @@ |
| +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() |
| + } |
| +} |
| + |
| +/// Monotonic time the test moves by hand; the scripted server advances it. |
| +private final class FakeClock: @unchecked Sendable { |
| + private let lock = NSLock() |
| + private var value: TimeInterval = 1_000 |
| + var now: TimeInterval { lock.withLock { value } } |
| + func advance(_ seconds: TimeInterval) { lock.withLock { value += seconds } } |
| +} |
| + |
| +final class StreamPacingTests: XCTestCase { |
| + /// A 429 with Retry-After: 1 holds the stream off for a second even when |
| + /// the app is foregrounded during it. |
| + @MainActor func testRetryAfterSurvivesAWake() async throws { |
| + let connectivity = NativeConnectivity(source: ScriptedPathSource(.satisfied)) |
| + let server = documentServer(stream: .respond(status: 429, headers: ["Retry-After": "1"])) |
| + let model = DocsModel(client: server, connectivity: connectivity) |
| + await model.open("doc") |
| + await until(2) { streams(server) >= 1 } |
| + let refused = Date() |
| + try await Task.sleep(for: .milliseconds(200)) |
| + connectivity.foregrounded() |
| + try await Task.sleep(for: .milliseconds(500)) |
| + XCTAssertEqual(streams(server), 1, "A foreground wake crossed the server's Retry-After") |
| + await until(2) { streams(server) >= 2 } |
| + XCTAssertGreaterThanOrEqual(Date().timeIntervalSince(refused), 0.95) |
| + await model.discardAll() |
| + } |
| + |
| + /// Every stream attempt fails after 10 s (by the model's clock) without |
| + /// ever opening. That is not a stable stream, so the backoff keeps |
| + /// growing: at most three attempts in 1.6 s, where resetting after each |
| + /// slow failure would retry every 0.25 to 0.5 s. |
| + @MainActor func testSlowFailuresThatNeverOpenedKeepBackingOff() async throws { |
| + let clock = FakeClock() |
| + let connectivity = NativeConnectivity(source: ScriptedPathSource(.satisfied)) |
| + let slow = ScriptedTransport { call in |
| + if call.kind == .stream { clock.advance(10); return .respond(status: 500) } |
| + return nil |
| + } |
| + let server = documentServer(stream: .hang) |
| + let model = DocsModel(transport: { SplitTransport(requests: server, streams: slow) }, connectivity: connectivity) |
| + model.reconnectClock = { clock.now } |
| + await model.open("doc") |
| + await until(2) { streams(slow) >= 1 } |
| + try await Task.sleep(for: .milliseconds(1600)) |
| + XCTAssertLessThanOrEqual(streams(slow), 3, "A slow failure that never opened reset the backoff") |
| + await model.discardAll() |
| + } |
| +} |
| + |
| +/// Requests go to one transport and streams to another. |
| +private struct SplitTransport: NativeTransport { |
| + let requests: ScriptedTransport |
| + let streams: ScriptedTransport |
| + var origin: URL { requests.origin } |
| + func responseDetails(_ path: String, method: String, body: Data?, contentType: String, maxBytes: Int) async throws -> NativeResponse { |
| + try await requests.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 streams.stream(path, onOpen: onOpen, onLine: onLine) |
| + } |
| + func download(_ path: String, to destination: URL) async throws { try await requests.download(path, to: destination) } |
| +} |
diff --git a/native/ios/project.yml b/native/ios/project.yml| index c8bad27..28ec608 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: 14ee567be2e1816002c7db4274acaf2926983b4c |
| settings: |
| base: |
| SWIFT_VERSION: '6.0' |
diff --git a/native/macos/project.yml b/native/macos/project.yml| index 4faa32b..81fd871 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: 14ee567be2e1816002c7db4274acaf2926983b4c |
| settings: |
| base: |
| SWIFT_VERSION: '6.0' |
diff --git a/native/smoke/document-window/Package.resolved b/native/smoke/document-window/Package.resolved| index 8e60eba..0e15d8a 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" : "14ee567be2e1816002c7db4274acaf2926983b4c" |
| } |
| }, |
| { |