Cotton code
214 lines · 11.0 KB · SwiftRaw
// 4g's half of the boundary contract — the twenty-seven reads behind people's// traffic and money.//// A separate file from `BoundaryContractTests` and `BoundaryContract4dTests`// for the reason those two give about each other: several lanes are landing at// once, and a lane that appends to the middle of somebody else's file makes a// merge conflict out of what is really independent additions.//// The rule is the same one stated there — **where this app and// `crates/cotton-ffi/src/phone/reads.rs` disagree, the crate// wins** — and so is the by-path discipline AGENTS.md sets for a guard that// reads another lane's file: the read fails LOUDLY if it finds nothing, the// owning lane is named here, and the path is grepped repo-wide before it moves.//// **What this file checks that a name-only check cannot.** `READS` declares a// name AND the screens it answers, and the two are asserted together: a read// that answered the right name for the wrong screen would pass a `contains`// over the whole file and then draw the wrong page. So the table is split into// its `ScreenRead` blocks and each method is matched against the block that// bears its name, never against the file.import CottonKitimport CottonUIimport XCTestfinal class BoundaryContract4gTests: XCTestCase {    private static let lane = "Rust FFI (the phone's reads table)"    private static let readsPath = "crates/cotton-ffi/src/phone/reads.rs"    private static let methodsPath = "crates/cotton-ffi/src/methods.rs"    /// Every read this lane calls, and a screen it must answer.    ///    /// One row per METHOD, and one method per route.    private static let reads: [(method: String, screen: String)] = [        // ── email ────────────────────────────────────────────────────────        (CottonMethod.readEmail, "/email"),        // ── pictures and film ────────────────────────────────────────────        (CottonMethod.readPhotos, "/photos"),        // ── chat ─────────────────────────────────────────────────────────        (CottonMethod.readThreads, "/messages"),        // ── disk ─────────────────────────────────────────────────────────        (CottonMethod.readStorage, "/storage"),    ]    /// The routes this lane draws that are answered by a WRITTEN LINE rather    /// than by a read, and the words the crate uses for each.    ///    /// Both are permanent in the sense that matters here: neither will get a    /// read in this sub-step, and a screen that quietly drew nothing would be    /// indistinguishable from one whose read failed. Each draws a page that    /// NAMES what it waits on.    private static let writtenLines: [(route: String, owes: String)] = [        // EMPTY, and the test below is now the one that matters: the list is        // supposed to shrink to nothing and it has.        //        // `/call/[id]` WAS the last line, owed nothing because live calling was        // paused — and at schema 5 it stopped being paused and started being        // deleted, so the route went and the debt closed by subtraction.        // `/messages/import` was the one before it, until lane N landed        // `import.whatsappExport`: the screen runs that job and shows its        // answer, so it is on `READ_LESS`.    ]    private func readsTable() throws -> String {        let text = try SourceSweep.mustRead(            BoundaryContract4gTests.readsPath, ownedBy: BoundaryContract4gTests.lane        )        // Anti-vacuity before any comparison: a `contains` over an empty read        // is how a moved file turns a guard green.        XCTAssertTrue(text.contains("pub static READS"), "reads.rs did not read as itself")        XCTAssertTrue(text.contains("static DEFERRED"), "reads.rs no longer declares DEFERRED")        return text    }    /// The table's `ScreenRead` blocks, as `name -> the screens it declares`.    ///    /// Parsed rather than grepped, so a method can be checked against ITS OWN    /// block. A `contains` over the whole file would pass for a read that named    /// the right screen under somebody else's name, which is precisely the    /// mistake worth catching: the two halves of a `ScreenRead` are what say    /// which page a method draws.    ///    /// The screens live under `audience: Audience::Screens(&[…])` since 4i,    /// which also added `Audience::Extension("…")` for a read an app EXTENSION    /// draws rather than a route. An extension block has no screens and is    /// skipped ON PURPOSE — and a block that is NEITHER shape fails the sweep    /// rather than being skipped, because the version of this parser that    /// `continue`d past an unrecognised block is how the merge that renamed    /// `screens:` left the guard reading almost nothing.    private func blocks(in table: String) throws -> [String: [String]] {        // From the TABLE, not from the file: `pub struct ScreenRead {` matches        // the same separator as an entry does, and a parser that failed loudly        // on a malformed block failed on the struct declaration instead. Every        // block after this point is a table entry, so an unrecognised one is a        // real defect rather than the type it is made of.        guard let tableAt = table.range(of: "pub static READS") else {            throw SweepFailure("reads.rs no longer declares READS")        }        let entries = String(table[tableAt.upperBound ..< table.endIndex])        var found: [String: [String]] = [:]        for chunk in entries.components(separatedBy: "ScreenRead {").dropFirst() {            guard let head = chunk.range(of: "source:") else {                throw SweepFailure("a ScreenRead block with no `source:` — the table changed shape")            }            let declaration = String(chunk[chunk.startIndex ..< head.lowerBound])            guard                let nameRange = declaration.range(of: "name: \""),                let nameEnd = declaration.range(                    of: "\"", range: nameRange.upperBound ..< declaration.endIndex                )            else {                throw SweepFailure("a ScreenRead block with no `name:` — the table changed shape")            }            let name = String(declaration[nameRange.upperBound ..< nameEnd.lowerBound])            if declaration.contains("Audience::Extension(") { continue }            guard let screensAt = declaration.range(of: "Audience::Screens(") else {                throw SweepFailure(                    "read.\(name) declares neither Audience::Screens nor Audience::Extension — "                        + "either the crate renamed the field again, in which case this parser "                        + "follows, or the block is malformed"                )            }            let screens = String(declaration[screensAt.upperBound ..< declaration.endIndex])                .components(separatedBy: "\"")                .enumerated()                // Odd indices are what sat BETWEEN a pair of quotes.                .filter { $0.offset % 2 == 1 }                .map(\.element)            found[name] = screens        }        return found    }    /// A by-path sweep that could not read what it came for.    private struct SweepFailure: Error, CustomStringConvertible {        let description: String        init(_ description: String) { self.description = description }    }    func testEveryReadThisLaneCallsIsOneTheCrateDeclaresForThatScreen() throws {        let table = try readsTable()        let declared = try blocks(in: table)        XCTAssertFalse(declared.isEmpty, "the table parsed as nothing")        for (method, screen) in BoundaryContract4gTests.reads {            let name = String(method.dropFirst("read.".count))            guard let screens = declared[name] else {                return XCTFail(                    """                    \(method) is declared in this lane's Boundary and `READS` does \                    not name it. Either the crate renamed it — in which case this \                    app follows, because the crate wins — or a screen is asking \                    for something nobody answers, which is an unknown_method at \                    runtime.                    """                )            }            XCTAssertTrue(                screens.contains(screen),                """                \(method) should answer \(screen); the crate says it answers \                \(screens). A read that draws the wrong page is worse than one \                that does not answer at all, because nothing says so.                """            )        }    }    func testTheTwoMediaMethodsAreOnesThePhoneActuallyHas() throws {        // `read.mediaPath` is a READ and rides the table; `media.ensure` is a        // method of its own and rides `CLIENT_METHODS`. Every picture, poster        // and film in this lane goes through the pair, so a rename below the        // boundary must not reach the screens as a silent absence.        let table = try readsTable()        XCTAssertTrue(            table.contains("name: \"mediaPath\""),            "\(CottonMethod.readMediaPath) is called by every media screen and READS does not name it"        )        let methods = try SourceSweep.mustRead(            BoundaryContract4gTests.methodsPath, ownedBy: BoundaryContract4gTests.lane        )        XCTAssertTrue(methods.contains("CLIENT_METHODS"), "methods.rs did not read as itself")        XCTAssertTrue(            methods.contains("\"\(CottonMethod.mediaEnsure)\""),            "\(CottonMethod.mediaEnsure) is not a method this phone build has"        )    }    /// One Rust function's body, from its signature to its matching brace.    ///    /// A window bounded by the BRACES rather than by a character count, so a    /// guard over it cannot be satisfied by something written after the    /// function ends. Braces inside string literals would break the count and    /// there are none in the three bodies this reads; a `{` that never closes    /// fails rather than returning the rest of the file.    private func functionBody(        of source: String, startingAt: String.Index    ) throws -> String {        guard let open = source[startingAt...].firstIndex(of: "{") else {            throw SweepFailure("no body opens after that signature")        }        var depth = 0        var at = open        while at < source.endIndex {            if source[at] == "{" { depth += 1 }            if source[at] == "}" {                depth -= 1                if depth == 0 { return String(source[open ... at]) }            }            at = source.index(after: at)        }        throw SweepFailure("a body that never closes — traffic.rs did not read as Rust")    }}