oficina / docs Public

Pace Docs stream reconnects with NativeReconnect

Review of #67 (Astra):
- P2: a connectivity wake crossed the server's Retry-After, because the
  loop passed it to Backoff as a floor and then waited with a wakeable
  wait. NativeReconnect keeps it as a deadline no wake crosses.
- P2: the stable-stream clock started before the stream opened, so a
  slow refusal or a long access check reset the backoff. The clock now
  starts in onOpen (reconnect.opened()).
The fix lives in the kit (rastrillo/native fix/k2-retry-deadline,
67cd5ef, pinned here), so Sheets gets the same pacing.

Tests: a 429 with Retry-After: 1 holds the stream off for a second
through a foreground wake; stream attempts that each fail after 10 s
(by an injected clock) without opening keep backing off (at most three
attempts in 1.6 s).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev c521f9de3bcec918efcb00a47c339b396a062bbf parent f71d4e5
7 files changed, +79 −19
  • native/apple/Package.resolved +1 −1
  • native/apple/Package.swift +2 −2
  • native/apple/Sources/DocsKit/DocsModel.swift +10 −13
  • native/apple/Tests/DocsKitTests/StreamConnectivityTests.swift +63 −0
  • native/ios/project.yml +1 −1
  • native/macos/project.yml +1 −1
  • native/smoke/document-window/Package.resolved +1 −1

CI passed — run details

diff --git a/native/apple/Package.resolved b/native/apple/Package.resolved
index 3cb1703..ee7efac 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" : "daf6e652d78552fe468a91ef45b4b1dcf3165926"
+ "revision" : "67cd5efe420f7c813254022598b7328a555781ef"
}
},
{
diff --git a/native/apple/Package.swift b/native/apple/Package.swift
index 5b5b1a9..8629f28 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: "daf6e652d78552fe468a91ef45b4b1dcf3165926")
+ ?? .package(url: "https://amadan.net/rastrillo/native", revision: "67cd5efe420f7c813254022598b7328a555781ef")
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"), .product(name: "RastrilloNative", package: "native")], resources: [.process("Resources")]),
+ .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", .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 2fd68ca..1121011 100644
--- a/native/apple/Sources/DocsKit/DocsModel.swift
+++ b/native/apple/Sources/DocsKit/DocsModel.swift
@@ -1,7 +1,6 @@
import Foundation
import Observation
import RastrilloApple
-import RastrilloNative
@MainActor @Observable final class DocsModel {
enum ListState { case loading, loaded, failed }
@@ -47,6 +46,8 @@ import RastrilloNative
/// 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
@@ -325,31 +326,27 @@ import RastrilloNative
}
private func listen(_ sqid: String) async {
let epoch = documentEpoch
- var backoff = Backoff()
+ // 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()
- let opened = ContinuousClock.now
- var retryAfter: TimeInterval?
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 {
- if case NativeClientError.rateLimited(let after) = error { retryAfter = after }
+ reconnect.failed(error)
if !Task.isCancelled, documentEpoch == epoch {
errorKey = "docs.editor.status.retrying"
await refreshAccess(sqid, epoch: epoch)
}
}
- // 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() }
+ await reconnect.pause()
}
}
private func refresh(_ sqid: String, remoteSequence: Int64) async {
diff --git a/native/apple/Tests/DocsKitTests/StreamConnectivityTests.swift b/native/apple/Tests/DocsKitTests/StreamConnectivityTests.swift
index 42a7889..38f6731 100644
--- a/native/apple/Tests/DocsKitTests/StreamConnectivityTests.swift
+++ b/native/apple/Tests/DocsKitTests/StreamConnectivityTests.swift
@@ -65,3 +65,66 @@ final class StreamConnectivityTests: XCTestCase {
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 4a137b0..5651b16 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: daf6e652d78552fe468a91ef45b4b1dcf3165926
+ revision: 67cd5efe420f7c813254022598b7328a555781ef
settings:
base:
SWIFT_VERSION: '6.0'
diff --git a/native/macos/project.yml b/native/macos/project.yml
index 40ba674..69a78d9 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: daf6e652d78552fe468a91ef45b4b1dcf3165926
+ revision: 67cd5efe420f7c813254022598b7328a555781ef
settings:
base:
SWIFT_VERSION: '6.0'
diff --git a/native/smoke/document-window/Package.resolved b/native/smoke/document-window/Package.resolved
index 025c5eb..b2c8312 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" : "daf6e652d78552fe468a91ef45b4b1dcf3165926"
+ "revision" : "67cd5efe420f7c813254022598b7328a555781ef"
}
},
{