Cotton code
95 lines · 5.2 KB · SwiftRaw
import Foundationimport XCTestimport zlib@testable import CottonKit// `CottonCore` exists only where the Rust framework links (`CottonCore.swift`);// a build without it compiles this suite out rather than failing the target.#if canImport(CottonFFI)final class CoreHandleStackTests: XCTestCase {    /// RULE: A core dropped without `close` closes from `deinit` and nothing    /// outlives it: the close's barrier block never holds the handle, so the    /// handle is never freed while something still retains it (CottonTestHost    /// aborted in `CoreHandle.__deallocating_deinit`, verify-main #10190).    func testACoreDroppedWithoutCloseClosesFromDeinit() throws {        guard CottonRuntime.linksFFI else {            throw XCTSkip("The real Rust framework is required to open and drop a core.")        }        for round in 0..<20 {            let container = FileManager.default.temporaryDirectory.appendingPathComponent("cotton-drop-\(UUID().uuidString)")            try FileManager.default.createDirectory(at: container, withIntermediateDirectories: true)            defer { try? FileManager.default.removeItem(at: container) }            weak var dropped: CottonCore?            do {                let core = try CottonCore.open(CottonConfig(containerPath: container.path, timeZone: "UTC"))                dropped = core            }            // The last reference may be let go a moment after the scope ends            // (the actor's executor); what this proves is that it IS let go and            // that its deinit closes without aborting the process.            let deadline = Date().addingTimeInterval(10)            while dropped != nil, Date() < deadline {                RunLoop.current.run(until: Date().addingTimeInterval(0.01))            }            XCTAssertNil(dropped, "round \(round): the core outlived its last reference by 10 s")        }    }    /// RULE: A native call must survive the debug serde stack required by a    /// deep synthetic definition. The fixture is a fresh-schema synthetic file (`pnpm gen:stack-probe`)    /// with a future (tolerated) definition field nested 110 levels deep.    /// This exercises TableDefinition decoding in Rust through CoreHandle,    /// not a Swift decoder or a fake native response.    func testADeepDefinitionReadsThroughTheRealHandle() async throws {        guard CottonRuntime.linksFFI else {            throw XCTSkip("The real Rust framework is required for the native stack guard.")        }        let container = FileManager.default.temporaryDirectory.appendingPathComponent("cotton-stack-\(UUID().uuidString)")        let client = container.appendingPathComponent("client")        let held = client.appendingPathComponent("11111111-1111-4111-8111-111111111111")        try FileManager.default.createDirectory(at: held, withIntermediateDirectories: true)        try fixture().write(to: held.appendingPathComponent("replica.db"))        try Data(#"{"mode":"remote","baseUrl":"https://server.invalid","workspaceId":"11111111-1111-4111-8111-111111111111","ownerId":"owner-synthetic","connectedAt":"2026-10-01T09:00:00.000Z"}"#.utf8)            .write(to: client.appendingPathComponent("connection.json"))        let core = try CottonCore.open(CottonConfig(containerPath: container.path, timeZone: "UTC"))        addTeardownBlock {            await core.close()            try FileManager.default.removeItem(at: container)        }        let answer = try await core.callRaw("definitions.tables", requestJSON: #"{"database":"11111111-1111-4111-8111-111111111111"}"#)        let envelope = try XCTUnwrap(JSONSerialization.jsonObject(with: Data(answer.utf8)) as? [String: Any])        XCTAssertEqual(envelope["ok"] as? Bool, true, answer)        let data = try XCTUnwrap(envelope["data"] as? [String: Any])        let tables = try XCTUnwrap(data["definitions"] as? [[String: Any]])        let probe = try XCTUnwrap(tables.first { $0["id"] as? String == "stack_probe" }, "\(data["refused"] ?? [])")        var payload: Any? = probe["future_stack_payload"]        for level in 0..<110 {            payload = try XCTUnwrap(payload as? [String: Any], "lost nested level \(level)")["next"]        }        XCTAssertEqual(payload as? String, "synthetic bottom", "the real handle retains every level")    }    private func fixture() throws -> Data {        #if SWIFT_PACKAGE        let bundle = Bundle.module        #else        let bundle = Bundle(for: Self.self)        #endif        let url = try XCTUnwrap(bundle.url(forResource: "StackProbe.sqlite", withExtension: "zlib", subdirectory: "Fixtures")            ?? bundle.url(forResource: "StackProbe.sqlite", withExtension: "zlib"))        let packed = try Data(contentsOf: url)        var bytes = Data(count: 16 * 1024 * 1024)        var count = uLongf(bytes.count)        let status = bytes.withUnsafeMutableBytes { destination in            packed.withUnsafeBytes { source in                uncompress(destination.bindMemory(to: Bytef.self).baseAddress, &count,                           source.bindMemory(to: Bytef.self).baseAddress, uLong(packed.count))            }        }        XCTAssertEqual(status, Z_OK, "the synthetic replica fixture did not decompress")        bytes.count = Int(count)        return bytes    }}#endif