import Foundation import RastrilloApple @testable import SheetsKit /// An in-process Sheets server for value edits: it applies each batch, moves /// the version by one per cell (as the real server's stamps do), and can hold /// a send until the test releases it, or refuse the next few. final class SheetServerFixture: NativeTransport, @unchecked Sendable { struct Sent: Equatable, Sendable { let r: Int let c: Int let raw: String } let origin = URL(string: "https://sheets-fixture.invalid")! private let lock = NSLock() private var holding = false private var waiting: [CheckedContinuation] = [] private var refusals = 0 private var unauthorized = 0 private var losses = 0 private var holdingPages = false private var waitingPages: [CheckedContinuation] = [] private var stamp: UInt64 = 0 private var sent: [[Sent]] = [] private var requested: [String] = [] /// Every request's method and path, in order. var requests: [String] { lock.withLock { requested } } private var cells: [Coordinate: String] = [:] /// Every batch the server received, in order, refused ones included. var batches: [[Sent]] { lock.withLock { sent } } var heldCount: Int { lock.withLock { waiting.count } } var version: UInt64 { lock.withLock { stamp } } func value(_ r: Int, _ c: Int) -> String? { lock.withLock { cells[Coordinate(r: r, c: c)] } } /// From now on, each batch waits for `release()`. func hold() { lock.withLock { holding = true } } /// Lets the oldest waiting batch through; `stopHolding` lets every later one through too. func release(stopHolding: Bool = false) { let next: CheckedContinuation? = lock.withLock { if stopHolding { holding = false } return waiting.isEmpty ? nil : waiting.removeFirst() } next?.resume() } func refuseNext(_ count: Int = 1) { lock.withLock { refusals = count } } /// The next batches meet an ended session: 401, applied nowhere. func unauthorizeNext(_ count: Int = 1) { lock.withLock { unauthorized = count } } /// The next batch is applied, then its answer is lost on the way back. func loseNextResponse() { lock.withLock { losses = 1 } } /// Opening a sheet (GET /sheets/) waits for `releasePages`. func holdPages() { lock.withLock { holdingPages = true } } func releasePages() { let all: [CheckedContinuation] = lock.withLock { holdingPages = false defer { waitingPages = [] } return waitingPages } all.forEach { $0.resume() } } static func display(_ raw: String) -> String { raw.hasPrefix("=") ? "computed" : raw } /// Another person's edit, as the live stream would deliver it. func peer(_ r: Int, _ c: Int, _ raw: String) -> GridResponse { lock.withLock { stamp += 1 cells[Coordinate(r: r, c: c)] = raw return GridResponse( version: stamp, cells: [Cell(r: r, c: c, raw: raw, display: Self.display(raw))], stamps: 1) } } func responseDetails(_ path: String, method: String, body: Data?, contentType: String, maxBytes: Int) async throws -> NativeResponse { lock.withLock { requested.append(method + " " + (path.split(separator: "?").first.map(String.init) ?? path)) } if method == "GET", path.hasPrefix("/sheets/"), let id = UInt64(path.dropFirst("/sheets/".count)) { await withCheckedContinuation { continuation in let wait = lock.withLock { () -> Bool in if holdingPages { waitingPages.append(continuation) } return holdingPages } if !wait { continuation.resume() } } 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":[]}"# return NativeResponse(data: Data(page.utf8), status: 200) } if method == "GET", path.contains("/cells?") { // A snapshot, as a refetch after a version gap reads it. return lock.withLock { let all = cells.map { #"{"r":\#($0.key.r),"c":\#($0.key.c),"raw":"\#($0.value)","display":"\#(Self.display($0.value))"}"# }.joined(separator: ",") return NativeResponse(data: Data(#"{"version":\#(stamp + 1),"cells":[\#(all)]}"#.utf8), status: 200) } } guard method == "POST", path.hasSuffix("/cells/batch"), let body else { return NativeResponse(data: Data(), status: 404) } struct Batch: Decodable { let cells: [Wire] } struct Wire: Decodable { let r: Int; let c: Int; let raw: String } let batch = try JSONDecoder().decode(Batch.self, from: body).cells.map { Sent(r: $0.r, c: $0.c, raw: $0.raw) } await withCheckedContinuation { continuation in let wait = lock.withLock { () -> Bool in sent.append(batch) if holding { waiting.append(continuation) } return holding } if !wait { continuation.resume() } } let outcome = lock.withLock { () -> NativeResponse? in if unauthorized > 0 { unauthorized -= 1 return NativeResponse(data: Data(), status: 401) } if refusals > 0 { refusals -= 1 return NativeResponse(data: Data(), status: 503) } stamp += UInt64(batch.count) // A cleared cell is deleted, as the real server deletes it. for cell in batch { cells[Coordinate(r: cell.r, c: cell.c)] = cell.raw.isEmpty ? nil : cell.raw } let changed = batch.map { #"{"r":\#($0.r),"c":\#($0.c),"raw":"\#($0.raw)","display":"\#(Self.display($0.raw))"}"# }.joined(separator: ",") if losses > 0 { losses -= 1 return nil } return NativeResponse( data: Data(#"{"version":\#(stamp),"stamps":\#(batch.count),"cells":[\#(changed)]}"#.utf8), status: 200) } guard let outcome else { throw NativeClientError.offline(.networkConnectionLost) } return outcome } func stream(_ path: String, onOpen: @Sendable () async throws -> Void, onLine: @Sendable (String) async throws -> Void) async throws { try await Task.sleep(for: .seconds(3600)) } func download(_ path: String, to destination: URL) async throws {} } @MainActor func fixtureModel(_ server: SheetServerFixture, rows: Int = 6, cols: Int = 4) -> SheetModel { let model = SheetModel(client: server) model.page = SheetPage( Sheet: SheetSummary(ID: 1, Title: "Fixture", TabID: 1, TabName: "Sheet 1"), Rows: rows, Cols: cols, Truncated: false, MayWrite: true, MayComment: true, MayShare: false, FillSwatches: [], InkSwatches: [], NumberFormats: [], Warned: nil) return model } /// Polls the main actor until `condition` holds or `seconds` pass. @MainActor func eventually(_ seconds: Double = 2, _ condition: () -> Bool) async -> Bool { let deadline = ProcessInfo.processInfo.systemUptime + seconds while !condition() { if ProcessInfo.processInfo.systemUptime > deadline { return false } try? await Task.sleep(for: .milliseconds(2)) } return true }