| 1 | import Foundation |
| 2 | import RastrilloApple |
| 3 | @testable import SheetsKit |
| 4 | |
| 5 | /// An in-process Sheets server for value edits: it applies each batch, moves |
| 6 | /// the version by one per cell (as the real server's stamps do), and can hold |
| 7 | /// a send until the test releases it, or refuse the next few. |
| 8 | final class SheetServerFixture: NativeTransport, @unchecked Sendable { |
| 9 | struct Sent: Equatable, Sendable { |
| 10 | let r: Int |
| 11 | let c: Int |
| 12 | let raw: String |
| 13 | } |
| 14 | let origin = URL(string: "https://sheets-fixture.invalid")! |
| 15 | private let lock = NSLock() |
| 16 | private var holding = false |
| 17 | private var waiting: [CheckedContinuation<Void, Never>] = [] |
| 18 | private var refusals = 0 |
| 19 | private var unauthorized = 0 |
| 20 | private var losses = 0 |
| 21 | private var holdingPages = false |
| 22 | private var waitingPages: [CheckedContinuation<Void, Never>] = [] |
| 23 | private var stamp: UInt64 = 0 |
| 24 | private var sent: [[Sent]] = [] |
| 25 | private var requested: [String] = [] |
| 26 | /// Every request's method and path, in order. |
| 27 | var requests: [String] { lock.withLock { requested } } |
| 28 | private var cells: [Coordinate: String] = [:] |
| 29 | /// Every batch the server received, in order, refused ones included. |
| 30 | var batches: [[Sent]] { lock.withLock { sent } } |
| 31 | var heldCount: Int { lock.withLock { waiting.count } } |
| 32 | var version: UInt64 { lock.withLock { stamp } } |
| 33 | func value(_ r: Int, _ c: Int) -> String? { lock.withLock { cells[Coordinate(r: r, c: c)] } } |
| 34 | |
| 35 | /// From now on, each batch waits for `release()`. |
| 36 | func hold() { lock.withLock { holding = true } } |
| 37 | /// Lets the oldest waiting batch through; `stopHolding` lets every later one through too. |
| 38 | func release(stopHolding: Bool = false) { |
| 39 | let next: CheckedContinuation<Void, Never>? = lock.withLock { |
| 40 | if stopHolding { holding = false } |
| 41 | return waiting.isEmpty ? nil : waiting.removeFirst() |
| 42 | } |
| 43 | next?.resume() |
| 44 | } |
| 45 | func refuseNext(_ count: Int = 1) { lock.withLock { refusals = count } } |
| 46 | /// The next batches meet an ended session: 401, applied nowhere. |
| 47 | func unauthorizeNext(_ count: Int = 1) { lock.withLock { unauthorized = count } } |
| 48 | /// The next batch is applied, then its answer is lost on the way back. |
| 49 | func loseNextResponse() { lock.withLock { losses = 1 } } |
| 50 | /// Opening a sheet (GET /sheets/<id>) waits for `releasePages`. |
| 51 | func holdPages() { lock.withLock { holdingPages = true } } |
| 52 | func releasePages() { |
| 53 | let all: [CheckedContinuation<Void, Never>] = lock.withLock { |
| 54 | holdingPages = false |
| 55 | defer { waitingPages = [] } |
| 56 | return waitingPages |
| 57 | } |
| 58 | all.forEach { $0.resume() } |
| 59 | } |
| 60 | |
| 61 | static func display(_ raw: String) -> String { raw.hasPrefix("=") ? "computed" : raw } |
| 62 | |
| 63 | /// Another person's edit, as the live stream would deliver it. |
| 64 | func peer(_ r: Int, _ c: Int, _ raw: String) -> GridResponse { |
| 65 | lock.withLock { |
| 66 | stamp += 1 |
| 67 | cells[Coordinate(r: r, c: c)] = raw |
| 68 | return GridResponse( |
| 69 | version: stamp, cells: [Cell(r: r, c: c, raw: raw, display: Self.display(raw))], stamps: 1) |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | func responseDetails(_ path: String, method: String, body: Data?, contentType: String, maxBytes: Int) async throws |
| 74 | -> NativeResponse |
| 75 | { |
| 76 | lock.withLock { requested.append(method + " " + (path.split(separator: "?").first.map(String.init) ?? path)) } |
| 77 | if method == "GET", path.hasPrefix("/sheets/"), let id = UInt64(path.dropFirst("/sheets/".count)) { |
| 78 | await withCheckedContinuation { continuation in |
| 79 | let wait = lock.withLock { () -> Bool in |
| 80 | if holdingPages { waitingPages.append(continuation) } |
| 81 | return holdingPages |
| 82 | } |
| 83 | if !wait { continuation.resume() } |
| 84 | } |
| 85 | let page = #"{"Sheet":{"ID":\#(id),"Title":"Sheet \#(id)","TabID":\#(id),"TabName":"Tab"},"Rows":6,"Cols":4,"Truncated":false,"MayWrite":true,"MayComment":true,"MayShare":false,"FillSwatches":[],"InkSwatches":[],"NumberFormats":[]}"# |
| 86 | return NativeResponse(data: Data(page.utf8), status: 200) |
| 87 | } |
| 88 | if method == "GET", path.contains("/cells?") { |
| 89 | // A snapshot, as a refetch after a version gap reads it. |
| 90 | return lock.withLock { |
| 91 | let all = cells.map { |
| 92 | #"{"r":\#($0.key.r),"c":\#($0.key.c),"raw":"\#($0.value)","display":"\#(Self.display($0.value))"}"# |
| 93 | }.joined(separator: ",") |
| 94 | return NativeResponse(data: Data(#"{"version":\#(stamp + 1),"cells":[\#(all)]}"#.utf8), status: 200) |
| 95 | } |
| 96 | } |
| 97 | guard method == "POST", path.hasSuffix("/cells/batch"), let body else { |
| 98 | return NativeResponse(data: Data(), status: 404) |
| 99 | } |
| 100 | struct Batch: Decodable { let cells: [Wire] } |
| 101 | struct Wire: Decodable { let r: Int; let c: Int; let raw: String } |
| 102 | let batch = try JSONDecoder().decode(Batch.self, from: body).cells.map { Sent(r: $0.r, c: $0.c, raw: $0.raw) } |
| 103 | await withCheckedContinuation { continuation in |
| 104 | let wait = lock.withLock { () -> Bool in |
| 105 | sent.append(batch) |
| 106 | if holding { waiting.append(continuation) } |
| 107 | return holding |
| 108 | } |
| 109 | if !wait { continuation.resume() } |
| 110 | } |
| 111 | let outcome = lock.withLock { () -> NativeResponse? in |
| 112 | if unauthorized > 0 { |
| 113 | unauthorized -= 1 |
| 114 | return NativeResponse(data: Data(), status: 401) |
| 115 | } |
| 116 | if refusals > 0 { |
| 117 | refusals -= 1 |
| 118 | return NativeResponse(data: Data(), status: 503) |
| 119 | } |
| 120 | stamp += UInt64(batch.count) |
| 121 | // A cleared cell is deleted, as the real server deletes it. |
| 122 | for cell in batch { cells[Coordinate(r: cell.r, c: cell.c)] = cell.raw.isEmpty ? nil : cell.raw } |
| 123 | let changed = batch.map { |
| 124 | #"{"r":\#($0.r),"c":\#($0.c),"raw":"\#($0.raw)","display":"\#(Self.display($0.raw))"}"# |
| 125 | }.joined(separator: ",") |
| 126 | if losses > 0 { |
| 127 | losses -= 1 |
| 128 | return nil |
| 129 | } |
| 130 | return NativeResponse( |
| 131 | data: Data(#"{"version":\#(stamp),"stamps":\#(batch.count),"cells":[\#(changed)]}"#.utf8), status: 200) |
| 132 | } |
| 133 | guard let outcome else { throw NativeClientError.offline(.networkConnectionLost) } |
| 134 | return outcome |
| 135 | } |
| 136 | func stream(_ path: String, onOpen: @Sendable () async throws -> Void, onLine: @Sendable (String) async throws -> Void) |
| 137 | async throws |
| 138 | { |
| 139 | try await Task.sleep(for: .seconds(3600)) |
| 140 | } |
| 141 | func download(_ path: String, to destination: URL) async throws {} |
| 142 | } |
| 143 | |
| 144 | @MainActor func fixtureModel(_ server: SheetServerFixture, rows: Int = 6, cols: Int = 4) -> SheetModel { |
| 145 | let model = SheetModel(client: server) |
| 146 | model.page = SheetPage( |
| 147 | Sheet: SheetSummary(ID: 1, Title: "Fixture", TabID: 1, TabName: "Sheet 1"), Rows: rows, Cols: cols, |
| 148 | Truncated: false, MayWrite: true, MayComment: true, MayShare: false, FillSwatches: [], InkSwatches: [], |
| 149 | NumberFormats: [], Warned: nil) |
| 150 | return model |
| 151 | } |
| 152 | |
| 153 | /// Polls the main actor until `condition` holds or `seconds` pass. |
| 154 | @MainActor func eventually(_ seconds: Double = 2, _ condition: () -> Bool) async -> Bool { |
| 155 | let deadline = ProcessInfo.processInfo.systemUptime + seconds |
| 156 | while !condition() { |
| 157 | if ProcessInfo.processInfo.systemUptime > deadline { return false } |
| 158 | try? await Task.sleep(for: .milliseconds(2)) |
| 159 | } |
| 160 | return true |
| 161 | } |
| 162 | |