Cotton code
54 lines · 2.5 KB · SwiftRaw
import CottonKitimport XCTest@testable import CottonUI/// A core whose `records.list` waits until the test lets it answer, counting/// every call that reached it.private actor GatedCore: CottonCalling {    private(set) var calls = 0    private var waiting: [CheckedContinuation<Void, Never>] = []    func callRaw(_ method: String, requestJSON: String) async throws -> String {        calls += 1        await withCheckedContinuation { waiting.append($0) }        return #"{"ok":true,"data":{"records":[{"id":"c1","table":"copy","data":{"role":"this_device"}}]}}"#    }    func release() {        waiting.forEach { $0.resume() }        waiting = []    }    func subscribe(_ handler: @escaping @Sendable (CottonEvent) -> Void) async {}    func close() async {}}@MainActorfinal class CopyRowsFlightTests: XCTestCase {    /// RULE: a periodic read is single-flight — while the copy rows' read for a database is out, the next tick, Me's line, the Mac-away line and a task restarted after a cancel all wait for its answer and never start a second core call, because a cancelled Swift task does not stop the Rust call and restarted reads stacked on a starved read pool (architect's ruling 21:00 IST 16 Oct 2026; realfan's evidence: HomeSync every 20 s).    func testAReadStillOutIsNeverJoinedByASecond() async {        let core = GatedCore()        let first = Task { await CopyRows.read(core, database: "db-a") }        for _ in 0..<200 where await core.calls == 0 { await Task.yield() }        // The first asker gives up, as a page that went away does.        first.cancel()        let second = Task { await CopyRows.read(core, database: "db-a") }        let away = Task { await CopyRows.read(core, database: "db-a") }        for _ in 0..<200 { await Task.yield() }        let whileOut = await core.calls        XCTAssertEqual(whileOut, 1, "one read out, however many ask")        await core.release()        let rows = await second.value        _ = await away.value        XCTAssertEqual(rows?.first?["role"].text, "this_device", "every asker gets the one answer")        // Landed: the next tick reads afresh.        let next = Task { await CopyRows.read(core, database: "db-a") }        for _ in 0..<200 where await core.calls < 2 { await Task.yield() }        let afterLanding = await core.calls        XCTAssertEqual(afterLanding, 2, "a read that has landed is not held: the next ask reads again")        await core.release()        _ = await next.value    }}