| 1 | import CryptoKit |
| 2 | import Foundation |
| 3 | import RastrilloApple |
| 4 | import RastrilloNative |
| 5 | import RastrilloTestSupport |
| 6 | import XCTest |
| 7 | @testable import DocsKit |
| 8 | |
| 9 | /// Live-push latency probe (spec/live-push, 2026-11-26). Skipped unless |
| 10 | /// DOCS_LIVE_NATIVE_CONN names a connection.json from |
| 11 | /// native/benchmarks/live-push/run-probe.py SERVER_ONLY=1. The production |
| 12 | /// DocsModel with a sealed on-disk store, playing the text view's part as |
| 13 | /// RealtimeAuditE2ETests does (render + reconcile into an NSTextStorage once |
| 14 | /// per published projection). One process types (`testTypes`), another |
| 15 | /// watches (`testWatches`), so native to native is two apps, each with its own |
| 16 | /// main thread, as two devices are. Times are Unix ms, comparable with the |
| 17 | /// browser probe's and the server's log. Results: DOCS_LIVE_NATIVE_OUT (JSON). |
| 18 | @MainActor final class LivePushLatencyTests: XCTestCase { |
| 19 | struct Cookie: Decodable { let Name: String; let Value: String } |
| 20 | struct Conn: Decodable { let origin: String; let sqids: [String]; let cookies: [Cookie] } |
| 21 | |
| 22 | static func now() -> Double { Date().timeIntervalSince1970 * 1000 } |
| 23 | var env: [String: String] { ProcessInfo.processInfo.environment } |
| 24 | |
| 25 | func openModel() async throws -> (DocsModel, DocsOfflineAccount, URL) { |
| 26 | guard let path = env["DOCS_LIVE_NATIVE_CONN"] else { throw XCTSkip("Run native/benchmarks/live-push/run-native.sh") } |
| 27 | let conn = try JSONDecoder().decode(Conn.self, from: Data(contentsOf: URL(fileURLWithPath: path))) |
| 28 | let sqid = conn.sqids[Int(env["DOCS_LIVE_NATIVE_INDEX"] ?? "0") ?? 0] |
| 29 | let value = ([conn.cookies[0].Value] + conn.cookies.dropFirst().map { "\($0.Name)=\($0.Value)" }).joined(separator: "; ") |
| 30 | let client = NativeHTTP(origin: URL(string: conn.origin)!, credential: NativeSession(name: conn.cookies[0].Name, value: value)) |
| 31 | let connectivity = NativeConnectivity(source: ScriptedPathSource(.satisfied)) |
| 32 | let root = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("docs-live-push-\(UUID().uuidString)") |
| 33 | let id = UUID().uuidString |
| 34 | let store = NativeSealedStore(root: root, accountID: id, keys: ScriptedKeyProvider(key: SymmetricKey(data: Data(repeating: 7, count: 32)))) |
| 35 | let account = DocsOfflineAccount(store: store, accountID: id, connectivity: connectivity, transport: { client }) |
| 36 | let model = DocsModel(transport: { client }, connectivity: connectivity, offlineAccount: account) |
| 37 | await model.open(sqid) |
| 38 | XCTAssertNotNil(model.projection, "open failed: \(model.errorKey ?? "")") |
| 39 | try await Task.sleep(for: .seconds(2)) |
| 40 | return (model, account, root) |
| 41 | } |
| 42 | |
| 43 | final class Flag: @unchecked Sendable { var changed = true } |
| 44 | @MainActor final class View { |
| 45 | let storage: NSTextStorage |
| 46 | var shown: UInt64 = 0 |
| 47 | let flag = Flag() |
| 48 | init(_ model: DocsModel) { |
| 49 | storage = NSTextStorage(attributedString: NativeTextProjection.render(model.projection!)) |
| 50 | shown = model.projectionGeneration; model.didRender(shown) |
| 51 | } |
| 52 | func observe(_ model: DocsModel) { |
| 53 | withObservationTracking { _ = model.projectionGeneration } onChange: { [flag] in flag.changed = true } |
| 54 | } |
| 55 | /// The text view's part: render and reconcile a new publication. |
| 56 | func render(_ model: DocsModel) -> Bool { |
| 57 | guard flag.changed, let projection = model.projection, model.canRender(model.projectionGeneration) else { return false } |
| 58 | flag.changed = false; observe(model) |
| 59 | DocumentRenderReconciliation.apply(NativeTextProjection.render(projection), to: storage) |
| 60 | shown = model.projectionGeneration; model.didRender(shown) |
| 61 | return true |
| 62 | } |
| 63 | var qs: Int { storage.string.reduce(0) { $0 + ($1 == "Q" ? 1 : 0) } } |
| 64 | } |
| 65 | |
| 66 | /// Same distribution as live_push_probe_test.go and browser-probe.mjs. |
| 67 | static func schedule(_ keys: Int, mean: Double, seed: UInt64) -> [Double] { |
| 68 | var s = seed |
| 69 | func rand() -> Double { s = (s &* 1103515245 &+ 12345) % 2147483648; return Double(s) / 2147483648 } |
| 70 | var out: [Double] = [], at = 0.0, nextPause = 30 + Int(rand() * 30) |
| 71 | for k in 0..<keys { |
| 72 | out.append(at) |
| 73 | at += 60 + -log(1 - rand()) * (mean - 60) |
| 74 | if k == nextPause { at += 700 + rand() * 800; nextPause += 30 + Int(rand() * 30) } |
| 75 | } |
| 76 | return out |
| 77 | } |
| 78 | |
| 79 | func write(_ object: [String: Any]) throws { |
| 80 | guard let out = env["DOCS_LIVE_NATIVE_OUT"] else { return } |
| 81 | try JSONSerialization.data(withJSONObject: object).write(to: URL(fileURLWithPath: out)) |
| 82 | } |
| 83 | |
| 84 | func testTypes() async throws { |
| 85 | let (model, account, root) = try await openModel() |
| 86 | let view = View(model); view.observe(model) |
| 87 | let keys = Int(env["DOCS_LIVE_NATIVE_KEYS"] ?? "120") ?? 120 |
| 88 | let mean = Double(env["DOCS_LIVE_NATIVE_MEAN_MS"] ?? "150") ?? 150 |
| 89 | if let startAt = Double(env["START_AT"] ?? ""), startAt > Self.now() { try await Task.sleep(for: .milliseconds(Int(startAt - Self.now()))) } |
| 90 | let s = view.storage.string as NSString |
| 91 | var at = s.length / 2 |
| 92 | while at < s.length, s.character(at: at) == 10 || s.character(at: at) == 0x2028 { at += 1 } |
| 93 | var times: [Double] = [] |
| 94 | let renderer = Task { @MainActor in |
| 95 | while !Task.isCancelled { _ = view.render(model); try? await Task.sleep(for: .milliseconds(1)) } |
| 96 | } |
| 97 | let clock = ContinuousClock.now |
| 98 | for due in Self.schedule(keys, mean: mean, seed: 4242) { |
| 99 | let deadline = clock.advanced(by: .milliseconds(Int(due))) |
| 100 | if deadline > .now { try await Task.sleep(until: deadline) } |
| 101 | guard var cmd = TextEditMapping.displayCommand(in: view.storage, range: NSRange(location: at, length: 0), replacement: "Q") else { XCTFail(); break } |
| 102 | cmd["generation"] = .number(Double(view.shown)) |
| 103 | times.append(Self.now()) |
| 104 | XCTAssertTrue(model.enqueue(cmd), "input paused: \(model.errorKey ?? "")") |
| 105 | view.storage.replaceCharacters(in: NSRange(location: at, length: 0), with: "Q") |
| 106 | at += 1 |
| 107 | } |
| 108 | let end = ContinuousClock.now.advanced(by: .seconds(30)) |
| 109 | while (model.hasUnsavedChanges || model.hasPendingInput) && .now < end { try await Task.sleep(for: .milliseconds(5)) } |
| 110 | try await Task.sleep(for: .seconds(3)) |
| 111 | renderer.cancel() |
| 112 | try write(["mode": "native-types", "keys": times]) |
| 113 | print("LIVENATIVE types \(times.count) keys; errorKey=\(model.errorKey ?? "nil")") |
| 114 | await model.stop(); account.drainer.stop() |
| 115 | try? FileManager.default.removeItem(at: root) |
| 116 | } |
| 117 | |
| 118 | func testWatches() async throws { |
| 119 | let (model, account, root) = try await openModel() |
| 120 | // The moment a publication lands (projectionGeneration moves), which is |
| 121 | // when the app's per-block drawing starts (S1a: 1-3 ms to reconciled). |
| 122 | func qs() -> Int { (model.projection?.children ?? []).reduce(0) { $0 + $1.plainText.reduce(0) { $0 + ($1 == "Q" ? 1 : 0) } } } |
| 123 | let base = qs() |
| 124 | var seen: [[Double]] = [] |
| 125 | if let ready = env["DOCS_LIVE_NATIVE_OUT"] { FileManager.default.createFile(atPath: ready + ".ready", contents: Data()) } |
| 126 | let until = ContinuousClock.now.advanced(by: .milliseconds(Int(env["WATCH_MS"] ?? "60000") ?? 60000)) |
| 127 | var count = base, generation = model.projectionGeneration |
| 128 | while .now < until { |
| 129 | if model.projectionGeneration != generation { |
| 130 | let t = Self.now() |
| 131 | generation = model.projectionGeneration |
| 132 | model.didRender(generation) |
| 133 | let c = qs() |
| 134 | if c > count { for i in count..<c { seen.append([Double(i - base), t]) }; count = c } |
| 135 | } |
| 136 | try await Task.sleep(for: .milliseconds(1)) |
| 137 | } |
| 138 | try write(["mode": "native-watches", "seen": seen]) |
| 139 | print("LIVENATIVE watches \(seen.count) seen; errorKey=\(model.errorKey ?? "nil")") |
| 140 | await model.stop(); account.drainer.stop() |
| 141 | try? FileManager.default.removeItem(at: root) |
| 142 | } |
| 143 | } |
| 144 | |