Cotton code
713 lines · 33.0 KB · SwiftRaw
// The Swift face of the Rust core — the Mac's `CottonClient/CottonCore.swift`,// moved over and cut down to what a phone sends.//// An `actor` because the handle is not thread-safe by contract and every call// blocks the calling thread inside Rust — so it must never be the main one// (design P5, the Mac's M2). Anything long is a command that returns at once// and reports on the event stream: `join.start`, `bootstrap.start`, the sync// pass. The boot read and the Keychain read run off the main thread for the// same reason.//// **The seam is a protocol, not the actor.** Every model in this app takes// `any CottonCalling`, so a screen is testable without an XCFramework, without// a container and without a simulator's filesystem — which is the whole reason// `CottonUI` is a library target (P17). `FakeCore` below is the double every// test uses; `CottonCore` is the one implementation that touches C.#if canImport(CottonFFI)    import CottonFFI#endifimport Foundation/// What the app hands the core at open — ONE shape for both destinations.////// The Rust side (`OpenConfig`, H1) reads the MODE off which keys are present:/// `containerPath` is a phone (the app group's container, Rust builds its whole/// layout under it); `home` is a host (a Mac that holds a database — the data/// directory's refusals and its one-time adoption run under `prepareDataDir`)./// Both at once, neither, or a host's field beside a container are refused by/// name, and a host config handed to the client build is refused at open —/// `no_server_in_this_build` — never at compile time. The JSON is/// `deny_unknown_fields` on the far side, and nothing here is/// optional-by-accident: a synthesised `Encodable` omits a nil optional, so an/// unset field is an absent field.////// Two constructors, so a call site reads as what it is: `CottonConfig(/// containerPath:)` is the phone's and `CottonConfig.host(...)` the Mac's, with/// the Mac's defaults (`NSHomeDirectory()`, `COTTON_MAC_DATA_DIR`, the bundle's/// version, the host name, "packaged" meaning a signed bundle).public struct CottonConfig: Encodable, Sendable {    /// WHICH APP this is — `real` or `dev`, the wire field `flavor`, on BOTH    /// the phone's config and the Mac's. Read off this bundle's `CottonFlavor`    /// stamp (`AppFlavor.current`, unstamped is dev) and handed down so the    /// core decides the data folder, the port, the relay-name rule and the    /// server it will talk to by the same word (`cotton-core/src/flavor.rs`).    /// Never optional: a config that does not say which app it is would be    /// read as Cotton Dev on the far side anyway, and saying so is honest.    public var flavor: String = AppFlavor.current.rawValue    /// WHICH BUSINESS APP this is, when it is one — the bundle's `flavour.json`    /// (`FlavourManifest`), handed down unchanged so the core reads the same    /// tools and database rule the screens do. Absent is Cotton.    public var manifest: FlavourManifest? = FlavourManifest.current    /// The phone: its data folder, in the app's own container    /// (`PhoneDataDirectory`) — never the app group's.    public var containerPath: String?    /// The phone: the app group's container, where the data folder lived    /// before 6 Oct 2026, so the core can rewrite the media rows' paths.    public var previousContainerPath: String?    /// The Mac: the home folder the data directory hangs off. Passed rather    /// than read inside Rust so the data directory's rules stay pure and a    /// test can point them at a synthetic folder.    public var home: String?    /// The Mac: `COTTON_MAC_DATA_DIR`, when set.    public var dataDirOverride: String?    public var appVersion: String?    /// The Mac app identity for booked moves, independent of its device-row version.    public var appBuildLabel: String?    /// The Mac: whether to run the data directory's refusals and its one-time    /// adoption. True in the app, always.    public var prepareDataDir: Bool?    /// The Mac: what this machine calls itself. Read here and passed down, so    /// the rule that strips `.local` stays pure on the other side.    public var hostname: String?    /// This device's zone, read here and passed down, so the recurrence rules    /// below the boundary stay pure. On the Mac it is read BEFORE anything    /// pins the process to UTC.    public var timeZone: String?    /// The Mac: true inside a signed app bundle. It decides ONE thing — where    /// the device seed lives — and it is false for `swift run` and for every    /// test.    public var packaged: Bool?    /// The device seed, base64url, out of the Keychain (§3). Rust derives the    /// id from it and signs every request with it; Swift never signs anything.    /// `nil` on an unpackaged Mac build, which keeps a rehearsal seed beside    /// the synthetic database instead (design M8).    public var deviceSecret: String?    /// THE MAC'S VAULT KEY, base64url, out of the Keychain (spec §7.1).    ///    /// A HOST field, and the phone must never set it. The two devices hold the    /// same kind of key and hold it completely differently: the Mac's is read    /// once at open and kept for the process's life, because the server and the    /// placement applier run unattended; the phone's is guarded by presence and    /// crosses per call as `vault.unlock`'s parameter, so nothing holds it    /// between two reveals. The core refuses a phone config that names one.    public var vaultSecret: String?    /// The phone's config.    public init(        containerPath: String,        previousContainerPath: String? = nil,        appVersion: String? = nil,        timeZone: String? = TimeZone.current.identifier,        deviceSecret: String? = nil    ) {        self.containerPath = containerPath        self.previousContainerPath = previousContainerPath        self.appVersion = appVersion        self.timeZone = timeZone        self.deviceSecret = deviceSecret    }    private init() {}    /// **The phone's version label** — "1.0.0 (248)": the marketing version    /// and, in brackets, the build. The label rides every request onto the    /// phone's synced device row (`app_version`), and the build in it is what    /// the cutover tool's Mac-last gate reads (architect, 12 Oct 2026): the    /// marketing version alone does not say which build a phone runs.    public static func versionLabel(short: String?, build: String?) -> String? {        guard let short, !short.isEmpty else { return nil }        guard let build, !build.isEmpty else { return short }        return "\(short) (\(build))"    }    /// This bundle's [`versionLabel`].    public static var bundleVersionLabel: String? {        let info = Bundle.main.infoDictionary        return versionLabel(            short: info?["CFBundleShortVersionString"] as? String,            build: info?["CFBundleVersion"] as? String        )    }    /// **The name a person reads on this machine's device row** — the Computer    /// Name they gave it in System Settings ("Asha's iMac"), not    /// `hostName`'s network spelling ("mac-a.local").    ///    /// The pairing list is read by a PERSON, and a row that names a machine has    /// to name it the way they do (the Mac walk's walk-23, 2026-09-15).    /// `hostName` stands in only where there is no localized name to read, and    /// off macOS it is all there is.    public static var machineName: String {        #if os(macOS)        return Host.current().localizedName ?? ProcessInfo.processInfo.hostName        #else        return ProcessInfo.processInfo.hostName        #endif    }    /// The Mac's config — a machine that holds a database.    public static func host(        home: String = NSHomeDirectory(),        dataDirOverride: String? = ProcessInfo.processInfo.environment["COTTON_MAC_DATA_DIR"],        appVersion: String? = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String,        appBuildLabel: String? = CottonConfig.bundleVersionLabel,        prepareDataDir: Bool = true,        hostname: String? = CottonConfig.machineName,        timeZone: String? = TimeZone.current.identifier,        packaged: Bool = Bundle.main.bundleIdentifier != nil,        deviceSecret: String? = nil,        vaultSecret: String? = nil    ) -> CottonConfig {        var config = CottonConfig()        config.home = home        config.dataDirOverride = dataDirOverride        config.appVersion = appVersion        config.appBuildLabel = appBuildLabel        config.prepareDataDir = prepareDataDir        config.hostname = hostname        config.timeZone = timeZone        config.packaged = packaged        config.deviceSecret = deviceSecret        config.vaultSecret = vaultSecret        return config    }}/// Why the core would not open — a title and a message a screen can show/// unchanged.public struct CottonRefusal: Error, Decodable, Equatable, Sendable {    public let code: String    public let title: String    public let message: String    public init(code: String, title: String, message: String) {        self.code = code        self.title = title        self.message = message    }}/// Why a call did not answer. Its `message` is the core's sentence, and it is/// what `localizedDescription` draws: a screen that shows a caught error must/// never draw "(CottonKit.CottonCallError error 1.)" (walk6, Documents).public struct CottonCallError: Error, Decodable, Equatable, Sendable, LocalizedError {    public let code: String    public let message: String    public let details: JSONValue?    public init(code: String, message: String, details: JSONValue? = nil) {        self.code = code        self.message = message        self.details = details    }    public var errorDescription: String? {        FlavourManifest.said(message.isEmpty ? "Cotton couldn't do that just now. Please try again." : message)    }    /// What a source that has no such method says: plain words, never the    /// method's name (291 words row 6).    public static let notOnThisDevice = "This device cannot do that."}/// An error on this side of the boundary: the core said something the app could/// not read.////// **It carries the raw answer and NEVER shows it.** The payload is for the/// log, for a report and for a test that wants to say what came back; the/// `errorDescription` is a sentence. Every screen's last-resort formatter is/// `String(describing:)` over whatever it caught, so an error that is not a/// `LocalizedError` is an error whose contents get drawn — and the walk of/// 15 Sep 2026 found the FFI's write envelope, JSON braces and all, written on/// the record sheet in red handwriting where the reason a recording had not/// been filed belonged.public enum CottonClientError: Error, Equatable, LocalizedError {    case malformedAnswer(String)    public var errorDescription: String? {        FlavourManifest.said("Cotton couldn't read what the core answered. Please try again.")    }    /// What actually came back, for the log and for a report. Never drawn.    public var rawAnswer: String {        switch self {        case .malformedAnswer(let answer): return answer        }    }}/// One event off the stream. Ten kinds — `status data log client devices/// sharing analyze ingest tunnel backup` — buffered and replayed before/// subscribe, delivered with the lock released, from any thread.public struct CottonEvent: Decodable, Equatable, Sendable {    public let kind: String    public let payload: JSONValue    public init(kind: String, payload: JSONValue) {        self.kind = kind        self.payload = payload    }}/// A request with no arguments. A struct with no stored properties encodes as/// `{}`, which is what the core reads an absent body as anyway.public struct EmptyRequest: Encodable, Sendable {    public init() {}}/// The core, as every model sees it.////// Four members and no fifth: ask, ask-and-decode, listen, close. Everything a/// screen wants is a method NAME inside `call`, which is the ABI's own rule/// carried one layer up — a fifth member here would be a second door into the/// same six C functions.public protocol CottonCalling: Sendable {    /// The raw envelope, for a caller that wants the JSON itself.    func callRaw(_ method: String, requestJSON: String) async throws -> String    /// Listen to the event stream. Everything buffered before now is replayed    /// first, in order. ONE subscriber: a second call replaces the first.    func subscribe(_ handler: @escaping @Sendable (CottonEvent) -> Void) async    func close() async}extension CottonCalling {    /// Ask the core something, and decode its answer.    public func call<Response: Decodable>(        _ method: String,        _ request: some Encodable = EmptyRequest(),        as _: Response.Type = Response.self    ) async throws -> Response {        let body = String(decoding: try JSONEncoder().encode(request), as: UTF8.self)        let answer = try await callRaw(method, requestJSON: body)        let decoded: Answer<Response>        do {            decoded = try JSONDecoder().decode(Answer<Response>.self, from: Data(answer.utf8))        } catch {            throw CottonClientError.malformedAnswer(answer)        }        if let error = decoded.error { throw error }        guard let data = decoded.data else {            throw CottonClientError.malformedAnswer(answer)        }        return data    }    /// The answer as an untyped tree, for a reader that is looking at one field    /// of a shape the boundary owns.    public func callJSON(        _ method: String,        _ request: some Encodable = EmptyRequest()    ) async throws -> JSONValue {        try await call(method, request, as: JSONValue.self)    }}/// The envelope: `{"ok":true,"data":…}` / `{"ok":false,"error":{…}}`.private struct Answer<T: Decodable>: Decodable {    let ok: Bool    let data: T?    let error: CottonCallError?}#if canImport(CottonFFI)    /// The handle, and everything that must outlive the actor.    ///    /// **Why the pointer lives in a class rather than in the actor.** Closing is    /// the one thing that has to happen from `deinit`, and under Swift 6's    /// strict concurrency a nonisolated `deinit` may not touch actor-isolated    /// state — `OpaquePointer` is not `Sendable`, so reading it there is a    /// compile error rather than a race nobody notices. Putting the pointer,    /// the subscription and the closed flag in one lock-guarded box makes the    /// ownership explicit: the box is what holds the C resource, its `deinit`    /// is what releases it, and the actor merely uses it.    final class CoreHandle: @unchecked Sendable {        let pointer: OpaquePointer        private let lock = NSLock()        /// Calls run on this queue, CONCURRENTLY: the core below is its own        /// locks (the replica's mutex, the client state's), and two calls in        /// flight at once are what it was built for. `close` is the one        /// barrier, so a call never enters a handle that is being closed.        private let calls = DispatchQueue(            label: "com.cottondb.core.calls",            qos: .userInitiated,            attributes: .concurrent        )        /// The quit's own lane: one SERIAL queue beside `calls`, for the calls a        /// quit makes (`quitCall`). A serial queue gets a thread of its own even        /// when the concurrent pool is spent — and on 12 Oct 2026 it was: a        /// standby had 64 reads parked on `calls`, GCD's whole width, and a        /// stop sent there would have waited for a thread that never came        /// (standbyhang).        private let quitLane = DispatchQueue(            label: "com.cottondb.core.quit",            qos: .userInitiated        )        /// Every box ever handed to C, kept alive — see `hold`.        private var boxes: [Unmanaged<EventBox>] = []        private var closed = false        init(_ pointer: OpaquePointer) {            self.pointer = pointer        }        /// Remember the subscription. ONE subscriber is the ABI's own rule, so        /// a second `subscribe` replaces the first below the boundary and this        /// only has to keep the object alive.        ///        /// **Nothing is ever released here, and that is deliberate.** The core        /// delivers events with its lock RELEASED, from any thread — so at the        /// moment `cotton_subscribe` swaps the context pointer, a callback may        /// already be inside the trampoline holding the OLD box. Releasing it        /// there is a use-after-free with no way to observe it from Swift. The        /// cost of not releasing is one small object per `subscribe` call, and        /// `subscribe` is called once per core; the cost of releasing is a        /// crash nobody can reproduce.        func hold(_ box: Unmanaged<EventBox>) {            lock.lock()            defer { lock.unlock() }            boxes.append(box)        }        /// The queue class a task's priority maps to, so a hop off the        /// cooperative pool keeps the priority the task was given.        static func qos(for priority: TaskPriority) -> DispatchQoS {            let raw = priority.rawValue            let qosClass: DispatchQoS.QoSClass =                raw >= TaskPriority.userInteractive.rawValue ? .userInteractive                : raw >= TaskPriority.userInitiated.rawValue ? .userInitiated                : raw >= TaskPriority.medium.rawValue ? .default                : raw >= TaskPriority.utility.rawValue ? .utility                : .background            return DispatchQoS(qosClass: qosClass, relativePriority: 0)        }        /// One call, off the calling thread, beside any other in flight.        ///        /// `cotton_call` is synchronous and takes as long as the method takes:        /// a local read is milliseconds, and the owner-HTTP families — a share        /// invitation, a push registration — are a round trip to the Mac with        /// a 60 s ceiling. When every call queued on the actor above, a screen        /// opened during one of those waited the whole round trip for a read        /// the file could have answered at once. So the actor holds nothing        /// while C runs: the work goes to the concurrent queue and the caller        /// awaits its answer alone.        func call(_ method: String, requestJSON: String) async throws -> String {            #if COTTON_DEV            let started = ContinuousClock.now            defer { DevReads.note(method, started: started) }            #endif            // AT THE CALLER'S PRIORITY, not the queue's. An actor runs its            // work at the priority of the task awaiting it; a plain queue hop            // does not, and a screen's read dispatched at the queue's default            // sat behind every other process on a busy Mac — measured at 2.5×            // the actor's time under a load of ten (lane I5).            let priority = Self.qos(for: Task.currentPriority)            return try await run(method, requestJSON: requestJSON, on: calls, qos: priority)        }        /// One call a QUIT makes, on the quit's own lane rather than `calls` —        /// see `quitLane`. Nothing else uses it: a read sent here would queue        /// behind the server's drain.        func quitCall(_ method: String, requestJSON: String) async throws -> String {            try await run(method, requestJSON: requestJSON, on: quitLane, qos: .userInitiated)        }        private func run(            _ method: String,            requestJSON: String,            on queue: DispatchQueue,            qos priority: DispatchQoS        ) async throws -> String {            try await withCheckedThrowingContinuation { continuation in                queue.async(qos: priority) { [self] in                    CoreNativeThread.run(qos: priority) { [self] in                        // Read the flag on the queue that `close` barriers, so a                        // closed handle is never entered.                        lock.lock()                        let isClosed = closed                        lock.unlock()                        guard !isClosed else {                            continuation.resume(throwing: CottonClientError.malformedAnswer(""))                            return                        }                        let answer = method.withCString { methodPointer in                            requestJSON.withCString { requestPointer in                                cotton_call(pointer, methodPointer, requestPointer)                            }                        }                        guard let answer else {                            continuation.resume(throwing: CottonClientError.malformedAnswer(""))                            return                        }                        defer { cotton_string_free(answer) }                        continuation.resume(returning: String(cString: answer))                    }                }            }        }        /// Close, once. Idempotent, and safe from `deinit`.        ///        /// `cotton_subscribe(pointer, nil, nil)` stops new callbacks; one        /// already running is why every held handler outlives this. `cotton_close` is the        /// last thing, so nothing can be dispatched into a closed handle — and        /// it runs as a BARRIER on the calls queue, so every call already in        /// flight has returned before the pointer is freed, and none starts        /// after.        ///        /// **And it is BOUNDED.** `cotton_close` is a synchronous C call, so        /// this blocks whichever thread asked — and the thread that asks is        /// usually one Swift concurrency lent out, a cooperative pool whose        /// width is the machine's core count and which is built on the promise        /// that nothing on it blocks. Park enough of them and no `await`        /// anywhere in the process has a thread to resume on: `swift test` sat        /// at 0 % CPU for 35 minutes on a shared CI runner, holding the        /// machine-wide build lock, over exactly this        /// (Cotton note "Repo landmines — why the build's rules exist"). Past the bound the handle is        /// deliberately LEAKED and the caller gets its thread back, because a        /// leaked core is a megabyte and a parked pool is the whole process.        /// The close below it is bounded too (`CottonHandle::close`), so the        /// bound here is the second line and not the only one.        func close() {            lock.lock()            guard !closed else {                lock.unlock()                return            }            closed = true            lock.unlock()            let finished = DispatchSemaphore(value: 0)            // THE BLOCK NEVER HOLDS THE BOX — only what it needs: the pointer            // and the quit lane. `deinit` calls this, and a block that captured            // `self` held the box past its own `deinit` whenever it had not yet            // been released when `deinit` returned — always after a timeout, and            // in a race even after `finished.signal()`. Swift aborts on a freed            // object something still holds ("deallocated with non-zero retain            // count"): RouteTableTests crashed CottonTestHost so on one Mac on            // 6, 8, 10, 12 and 14 Nov (verify-main #10190). The leak stays safe            // without the box: the box never frees the pointer, `cotton_close`            // in this block does, so a close that ran out of time returns and            // the block closes the pointer later.            let closing = ClosingPointer(raw: pointer)            let quitLane = quitLane            calls.async(flags: .barrier) {                // A quit call still running holds the pointer too.                quitLane.sync {}                CoreNativeThread.run(qos: .userInitiated) {                    cotton_subscribe(closing.raw, nil, nil)                    cotton_close(closing.raw)                }                finished.signal()            }            if finished.wait(timeout: .now() + CottonRuntime.closeTimeout) == .timedOut {                CottonRuntime.report(                    """                    the core did not close within \(Int(CottonRuntime.closeTimeout)) s — \                    leaving it to the operating system rather than waiting. The server log \                    names the step that would not stop.                    """                )            }        }        deinit { close() }    }    /// The handle's pointer on its way to `cotton_close`, carried by a block    /// that must not hold the handle (`CoreHandle.close`). Only that block    /// reads it, after every call has returned.    private struct ClosingPointer: @unchecked Sendable {        let raw: OpaquePointer    }    /// The open core.    public actor CottonCore: CottonCalling {        private let handle: CoreHandle        /// Open the core over an app-group container.        ///        /// Throws `CottonRefusal` when the container cannot be used — a        /// sentence meant to be shown as written, not a code to map.        public static func open(_ config: CottonConfig) throws -> CottonCore {            try CoreNativeThread.run(qos: .userInitiated) {                Result { try openOnNativeThread(config) }            }.get()        }        private static func openOnNativeThread(_ config: CottonConfig) throws -> CottonCore {            let json = String(decoding: try JSONEncoder().encode(config), as: UTF8.self)            var errorText: UnsafeMutablePointer<CChar>?            let handle = json.withCString { cotton_open($0, &errorText) }            guard let handle else {                let refusal = errorText.map { pointer -> CottonRefusal in                    defer { cotton_string_free(pointer) }                    let text = String(cString: pointer)                    return (try? JSONDecoder().decode(CottonRefusal.self, from: Data(text.utf8)))                        ?? CottonRefusal(                            code: "unreadable",                            title: CottonCore.startFailureTitle,                            message: text                        )                }                throw refusal                    ?? CottonRefusal(                        code: "unreadable",                        title: CottonCore.startFailureTitle,                        message: CottonCore.startFailureSilent                    )            }            return CottonCore(handle: CoreHandle(handle))        }        private init(handle: CoreHandle) {            self.handle = handle        }        /// The core's own version.        public nonisolated static var version: String {            guard let text = cotton_version() else { return "" }            defer { cotton_string_free(text) }            return String(cString: text)        }        /// Ask the core. NOT isolated to the actor: the call runs on the        /// handle's concurrent queue beside any other, so a read is never        /// queued behind a slow method — `CoreHandle.call` says why.        public nonisolated func callRaw(_ method: String, requestJSON: String) async throws -> String {            try await CallsInFlight.shared.during { try await handle.call(method, requestJSON: requestJSON) }        }        /// Listen. ONE subscriber: a second call replaces the first BELOW the        /// boundary, and the order here is the whole safety of it — the new        /// context is installed FIRST, and only then is the old one recorded as        /// superseded. Handing C a pointer whose object had already been let go        /// is the window this closes.        public func subscribe(_ handler: @escaping @Sendable (CottonEvent) -> Void) {            CoreNativeThread.run(qos: .userInitiated) { [handle] in                let retained = Unmanaged.passRetained(EventBox(handler))                cotton_subscribe(handle.pointer, retained.toOpaque()) { context, line in                    guard let context, let line else { return }                    let box = Unmanaged<EventBox>.fromOpaque(context).takeUnretainedValue()                    // The line is borrowed for the length of this call:                    // `String(cString:)` copies, and nothing here frees it.                    let text = String(cString: line)                    guard                        let event = try? JSONDecoder().decode(CottonEvent.self, from: Data(text.utf8))                    else { return }                    box.handler(event)                }                handle.hold(retained)            }        }        /// Close the core. Idempotent.        /// The quit: stop the server (it drains), then close — the call on the        /// quit's own lane, so a calls queue full of parked reads cannot hold        /// it. The caller bounds the whole of it        /// (`QuitBudget`). `quit: true` begins the PROCESS's drain first, so        /// no pass of this dying process starts (`cotton_server::drain`).        public func quit() async {            _ = try? await handle.quitCall("server.stop", requestJSON: #"{"quit":true}"#)            handle.close()        }        public func close() {            handle.close()        }        // The two sentences an open refusal falls back on. They are here rather        // than in `CottonStrings` because `CottonKit` carries no string        // catalogue — it is below the design system, not inside it — and these        // two are the only prose in the module. `LanguageSweepTests` reads them        // where they are.        static let startFailureTitle = String(localized: "Cotton could not start")        static let startFailureSilent = String(            localized: "The core would not open and did not say why."        )    }    /// The class the C callback's context pointer points at.    final class EventBox: @unchecked Sendable {        let handler: @Sendable (CottonEvent) -> Void        init(_ handler: @escaping @Sendable (CottonEvent) -> Void) {            self.handler = handler        }    }#endif/// The one door into the core, whether or not the archive is present.////// It exists so no caller above `CottonKit` writes `#if canImport(CottonFFI)`./// The XCFramework is a gitignored BUILD PRODUCT — absent on a fresh clone and/// on any lane that has not run `scripts/build-xcframework.sh`, where/// `scripts/ffi-stub.sh`'s module-less placeholder holds the path instead so/// SwiftPM can still resolve the package. A placeholder carries no module, so/// `canImport(CottonFFI)` is false and this answers false. The app target does/// not link the binary directly, so a conditional written up there would be/// answering a question about a module it cannot see; asked here, it is/// answering about its own.public enum CottonRuntime {    /// How long a close waits before it goes on without the core.    ///    /// Outside the sum of the Rust side's own bounds — 25 s to stop the server    /// and the replica, then 10 s for whatever is left on the blocking pool    /// (`CottonHandle::close`) — on purpose. The inner deadline is the one that    /// should fire and the one that can name the step that would not stop; this    /// is the rung outside it, for the case where it did not fire at all: a    /// blocking closure the operating system is holding, or a build whose core    /// is older than this app.    public static let closeTimeout: TimeInterval = 45    /// Where a close that ran out of time says so. `stderr`, always: a wait    /// that was abandoned must never be silent, and `CottonKit` is below the    /// app's own logging.    static func report(_ text: String) {        FileHandle.standardError.write(Data("cotton: \(text)\n".utf8))    }    /// Whether this build has the core in it. `FFISmokeTests` FAILS rather than    /// skipping when this is false, so "no XCFramework" is never a silent    /// absence.    public static var linksFFI: Bool {        #if canImport(CottonFFI)            return true        #else            return false        #endif    }    /// The core's own version, or the empty string when it is not linked.    public static var version: String {        #if canImport(CottonFFI)            return CottonCore.version        #else            return ""        #endif    }    /// The commit the linked core was built from, as its version carries it    /// (`0.1.0+1a2b3c4d5`, `.dirty` when crates/ held edits): nine characters    /// of the sha, or nil for an unstamped core. `scripts/core-fresh.sh`    /// reads the same stamp out of the archive.    public static var buildCommit: String? {        guard let plus = version.firstIndex(of: "+") else { return nil }        return String(version[version.index(after: plus)...])    }    /// Open the core over an app-group container.    public static func open(_ config: CottonConfig) throws -> any CottonCalling {        #if canImport(CottonFFI)            return try CottonCore.open(config)        #else            throw CottonRefusal(                code: "no_ffi",                title: "Cotton could not start",                message:                    "The Rust core is not in this build. Run `bash scripts/build-xcframework.sh`."            )        #endif    }}