The client reads and writes Store and People
Task 7 of the native slice 2 part 1 plan.
- StoreData, StoreRow (State: notInstalled, installing, installed,
failed), PeopleData and Person (Role: owner, member, invited), decoded
tolerantly as the other reads are: a row or person without an id is
dropped; an unknown state reads as not installed, an unknown role as a
member.
- store(), people(), install(app:), uninstall(app:) and invite(email:).
The writes POST with the transport's Origin (Base's CSRF check), the
invite as JSON {email}.
- BaseAPIError gains .team(TeamRefusal) (busy, owner_only, unknown_app,
unavailable, bad_email, mail_failed) and .notOnThisBase, a plain 404
without a code, so the app opens the web page for an older Base (P3).
A 401 unauthenticated calls rejected, as every call does. AskModel's
switches treat the new cases as a failure to try again; Ask's calls never
produce them.
Gate: swift test -j 4 --filter BaseKitTests.ClientTests: 16 passed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Summary
Task 7: Store and People in the client
6 files changed,
+241
−2
native/apple/Sources/BaseKit/API/Client.swift+61 −0native/apple/Sources/BaseKit/API/Models.swift+78 −0native/apple/Sources/BaseKit/Ask/AskModel.swift+2 −2native/apple/Tests/BaseKitTests/ClientTests.swift+81 −0native/apple/Tests/BaseKitTests/Fixtures/people.json+9 −0native/apple/Tests/BaseKitTests/Fixtures/store.json+10 −0
diff --git a/native/apple/Sources/BaseKit/API/Client.swift b/native/apple/Sources/BaseKit/API/Client.swift| index 58e092c..968ee73 100644 |
| --- a/native/apple/Sources/BaseKit/API/Client.swift |
| +++ b/native/apple/Sources/BaseKit/API/Client.swift |
| @@ -16,6 +16,27 @@ public enum BaseAPIError: Error, Sendable, Equatable { |
| case server(status: Int, code: String?, state: String?) |
| /// A 2xx whose body isn't what the contract says. |
| case badResponse |
| + /// A Store or People route this Base doesn't have (a plain 404): an |
| + /// older Base. The app opens the web page instead (plan P3). |
| + case notOnThisBase |
| + /// Store's and People's refusals, by their code. |
| + case team(TeamRefusal) |
| +} |
| + |
| +/// What Store and People refuse with (docs/api/base-native-v1.md). |
| +public enum TeamRefusal: String, Sendable, Equatable { |
| + /// 409: the app is still installing. |
| + case busy |
| + /// 403: only the owner may. |
| + case ownerOnly = "owner_only" |
| + /// 404: the catalogue has no such app. |
| + case unknownApp = "unknown_app" |
| + /// 503: Base couldn't read or write its own store. |
| + case unavailable |
| + /// 422: not one plain email address. |
| + case badEmail = "bad_email" |
| + /// 502: invited, but the email wasn't delivered. Inviting again sends it. |
| + case mailFailed = "mail_failed" |
| } |
| /// Base's API for the apps, over the kit's transport: `NativeHTTP` sends |
| @@ -48,6 +69,46 @@ public struct BaseClient: Sendable { |
| public func home() async throws(BaseAPIError) -> HomeData { try await get("/api/v1/home") } |
| public func askState() async throws(BaseAPIError) -> AskSnapshot { try await get("/ask/state") } |
| + // MARK: Store and People (slice 2) |
| + |
| + public func store() async throws(BaseAPIError) -> StoreData { try await team("/api/v1/store", method: "GET", body: nil) } |
| + public func people() async throws(BaseAPIError) -> PeopleData { try await team("/api/v1/people", method: "GET", body: nil) } |
| + |
| + /// The owner's Install: `202` installing (or already), `200` installed. |
| + public func install(app id: String) async throws(BaseAPIError) -> StoreData { |
| + let answer: StoreAnswer = try await team("/api/v1/store/\(Self.segment(id))/install", method: "POST", body: nil) |
| + return answer.store |
| + } |
| + |
| + /// The owner's Uninstall (confirmed by the caller): `200`, also when |
| + /// it was uninstalled already. |
| + public func uninstall(app id: String) async throws(BaseAPIError) -> StoreData { |
| + let answer: StoreAnswer = try await team("/api/v1/store/\(Self.segment(id))/uninstall", method: "POST", body: nil) |
| + return answer.store |
| + } |
| + |
| + /// The owner's invitation: the person invited, or already here. |
| + public func invite(email: String) async throws(BaseAPIError) -> Person { |
| + let body = try? JSONSerialization.data(withJSONObject: ["email": email]) |
| + let answer: PersonAnswer = try await team("/api/v1/people", method: "POST", body: body) |
| + return answer.person |
| + } |
| + |
| + struct StoreAnswer: Decodable { let store: StoreData } |
| + struct PersonAnswer: Decodable { let person: Person } |
| + |
| + /// A Store or People call: refusals typed by their code, and a plain |
| + /// 404 (no code) as an older Base. |
| + func team<T: Decodable>(_ path: String, method: String, body: Data?) async throws(BaseAPIError) -> T { |
| + do { |
| + return try await call(path, method: method, body: body, contentType: "application/json") |
| + } catch .server(let status, let code, _) { |
| + if let refusal = code.flatMap(TeamRefusal.init(rawValue:)) { throw .team(refusal) } |
| + if status == 404, code == nil { throw .notOnThisBase } |
| + throw .server(status: status, code: code, state: nil) |
| + } |
| + } |
| + |
| // MARK: Ask's writes (the forms ask.js posts) |
| public func send(_ text: String, key: String) async throws(BaseAPIError) -> AskSent { |
diff --git a/native/apple/Sources/BaseKit/API/Models.swift b/native/apple/Sources/BaseKit/API/Models.swift| index 66c549a..2c81e86 100644 |
| --- a/native/apple/Sources/BaseKit/API/Models.swift |
| +++ b/native/apple/Sources/BaseKit/API/Models.swift |
| @@ -399,3 +399,81 @@ public struct AskSetupAnswer: Decodable, Sendable, Equatable { |
| state = AskPhase(server: c.optional(.state)); renewAfter = c.date(.renewAfter) |
| } |
| } |
| + |
| +// MARK: /api/v1/store and /api/v1/people (slice 2, Task 7) |
| + |
| +/// `GET /api/v1/store`: the whole catalogue, in its order, with each |
| +/// install's state, and whether this member may install. |
| +public struct StoreData: Decodable, Sendable, Equatable { |
| + public var owner: Bool |
| + public var rows: [StoreRow] |
| + public init(owner: Bool, rows: [StoreRow]) { self.owner = owner; self.rows = rows } |
| + /// Whether any row is installing, which is when the Store polls. |
| + public var installing: Bool { rows.contains { $0.state == .installing } } |
| + enum CodingKeys: String, CodingKey { case owner, rows } |
| + public init(from decoder: Decoder) throws { |
| + let c = try decoder.container(keyedBy: CodingKeys.self) |
| + owner = c.value(.owner, false); rows = c.value(.rows, []).filter { !$0.id.isEmpty } |
| + } |
| +} |
| + |
| +public struct StoreRow: Decodable, Sendable, Equatable, Identifiable { |
| + /// `""` is not installed. A state a newer Base adds reads as not |
| + /// installed, so the row offers Install rather than nothing. |
| + public enum State: String, Sendable, Equatable { case notInstalled = "", installing, installed, failed } |
| + public var id: String |
| + public var name: String |
| + public var summary: String |
| + /// A catalogue tint name, as in `/api/v1/home`. |
| + public var tint: String |
| + /// Line art drawn in `currentColor`. |
| + public var iconSVG: String |
| + public var state: State |
| + /// A failed install's reason; may be empty. |
| + public var error: String |
| + public init(id: String, name: String, summary: String = "", tint: String = "", iconSVG: String = "", state: State = .notInstalled, error: String = "") { |
| + self.id = id; self.name = name; self.summary = summary; self.tint = tint; self.iconSVG = iconSVG; self.state = state; self.error = error |
| + } |
| + enum CodingKeys: String, CodingKey { case id, name, summary, tint, state, error, iconSVG = "icon_svg" } |
| + public init(from decoder: Decoder) throws { |
| + let c = try decoder.container(keyedBy: CodingKeys.self) |
| + id = c.value(.id, ""); name = c.value(.name, ""); summary = c.value(.summary, ""); tint = c.value(.tint, "") |
| + iconSVG = c.value(.iconSVG, ""); state = State(rawValue: c.value(.state, "")) ?? .notInstalled; error = c.value(.error, "") |
| + } |
| +} |
| + |
| +/// `GET /api/v1/people`: everyone here, in the order they were invited, |
| +/// and whether this member may invite. |
| +public struct PeopleData: Decodable, Sendable, Equatable { |
| + public var owner: Bool |
| + public var people: [Person] |
| + public init(owner: Bool, people: [Person]) { self.owner = owner; self.people = people } |
| + enum CodingKeys: String, CodingKey { case owner, people } |
| + public init(from decoder: Decoder) throws { |
| + let c = try decoder.container(keyedBy: CodingKeys.self) |
| + owner = c.value(.owner, false); people = c.value(.people, []).filter { !$0.id.isEmpty } |
| + } |
| +} |
| + |
| +public struct Person: Decodable, Sendable, Equatable, Identifiable { |
| + /// `invited` hasn't signed in yet. A role a newer Base adds reads as a |
| + /// member. |
| + public enum Role: String, Sendable, Equatable { case owner, member, invited } |
| + public var id: String |
| + public var initial: String |
| + /// Empty for someone who has given none: `label` is the address then. |
| + public var name: String |
| + public var email: String |
| + public var role: Role |
| + public init(id: String, initial: String, name: String, email: String, role: Role) { |
| + self.id = id; self.initial = initial; self.name = name; self.email = email; self.role = role |
| + } |
| + /// What the page shows first: the name, or else the address. |
| + public var label: String { name.isEmpty ? email : name } |
| + enum CodingKeys: String, CodingKey { case id, initial, name, email, role } |
| + public init(from decoder: Decoder) throws { |
| + let c = try decoder.container(keyedBy: CodingKeys.self) |
| + id = c.value(.id, ""); initial = c.value(.initial, ""); name = c.value(.name, ""); email = c.value(.email, "") |
| + role = Role(rawValue: c.value(.role, "")) ?? .member |
| + } |
| +} |
diff --git a/native/apple/Sources/BaseKit/Ask/AskModel.swift b/native/apple/Sources/BaseKit/Ask/AskModel.swift| index e676daa..8352a1a 100644 |
| --- a/native/apple/Sources/BaseKit/Ask/AskModel.swift |
| +++ b/native/apple/Sources/BaseKit/Ask/AskModel.swift |
| @@ -395,7 +395,7 @@ import SwiftUI |
| static func tryAgain(_ error: BaseAPIError) -> Bool { |
| switch error { |
| case .unauthenticated: false |
| - case .offline, .badResponse: true |
| + case .offline, .badResponse, .notOnThisBase, .team: true |
| case .server(let code, _, let state): |
| code != 409 && !(state.map { [.connect, .pending, .reconnect, .norunner, .oldrunner, .notLinked].contains(AskPhase(server: $0)) } ?? false) |
| } |
| @@ -421,7 +421,7 @@ import SwiftUI |
| } else if code != 409 { |
| status = BaseText.text("ask.not_sent") |
| } |
| - case .badResponse: |
| + case .badResponse, .notOnThisBase, .team: |
| // An unreadable answer (or the request cancelled once it may |
| // have reached Base) leaves the outcome unknown: the key stays, |
| // so sending again is the same write. |
diff --git a/native/apple/Tests/BaseKitTests/ClientTests.swift b/native/apple/Tests/BaseKitTests/ClientTests.swift| index bbefc95..e4041a0 100644 |
| --- a/native/apple/Tests/BaseKitTests/ClientTests.swift |
| +++ b/native/apple/Tests/BaseKitTests/ClientTests.swift |
| @@ -147,3 +147,84 @@ func XCTAssertThrows(_ expected: BaseAPIError, file: StaticString = #filePath, l |
| XCTFail("\(error); expected \(expected)", file: file, line: line) |
| } |
| } |
| + |
| +/// Task 7: Store and People (docs/api/base-native-v1.md "Store and People"). |
| +extension ClientTests { |
| + func testStoreAndPeopleDecode() async throws { |
| + let c = client(ScriptedTransport([.respond(status: 200, body: Fixture.data("store.json")), .respond(status: 200, body: Fixture.data("people.json"))])) |
| + let store = try await c.store() |
| + XCTAssertTrue(store.owner) |
| + XCTAssertEqual(store.rows.map(\.id), ["welcome", "scratchpad", "contra", "future"], "a row without an id is dropped") |
| + XCTAssertEqual(store.rows.map(\.state), [.installed, .installing, .failed, .notInstalled], "an unknown state reads as not installed") |
| + XCTAssertEqual(store.rows[2].error, "The app did not start answering") |
| + XCTAssertEqual(store.rows[0].tint, "amber") |
| + XCTAssertTrue(store.rows[0].iconSVG.hasPrefix("<svg")) |
| + XCTAssertTrue(store.installing) |
| + let people = try await c.people() |
| + XCTAssertFalse(people.owner) |
| + XCTAssertEqual(people.people.map(\.role), [.owner, .member, .invited, .member], "an unknown role reads as a member") |
| + XCTAssertEqual(people.people[1].name, "Ana Ruiz") |
| + XCTAssertEqual(people.people[0].label, "owner@acme.test", "no name: the address") |
| + XCTAssertEqual(people.people[1].label, "Ana Ruiz") |
| + } |
| + |
| + func testInstallAndUninstallPostAndDecodeTheStore() async throws { |
| + let answer = #"{"store":\#(String(decoding: Fixture.data("store.json"), as: UTF8.self))}"# |
| + let t = ScriptedTransport([json(202, answer), json(200, answer)]) |
| + let c = client(t) |
| + let installed = try await c.install(app: "scratch pad") |
| + XCTAssertEqual(installed.rows.count, 4) |
| + _ = try await c.uninstall(app: "welcome") |
| + XCTAssertEqual(t.calls.map(\.method), ["POST", "POST"]) |
| + XCTAssertEqual(t.calls.map(\.path), ["/api/v1/store/scratch%20pad/install", "/api/v1/store/welcome/uninstall"]) |
| + XCTAssertEqual(t.calls.map(\.body), [nil, nil]) |
| + } |
| + |
| + /// Through the kit's NativeHTTP: the writes carry Base's Origin, so its |
| + /// CSRF check passes, and the cookie. |
| + func testTeamWritesCarryTheOrigin() async throws { |
| + let server = try LocalServer { _ in (200, #"{"person":{"id":"m1","initial":"M","name":"","email":"maria@acme.test","role":"invited"}}"#) } |
| + let http = NativeHTTP(origin: server.origin, credential: NativeSession(name: "__Host-rastrillo_session", value: "s3cret")) |
| + let person = try await client(http).invite(email: "maria@acme.test") |
| + XCTAssertEqual(person, Person(id: "m1", initial: "M", name: "", email: "maria@acme.test", role: .invited)) |
| + let request = try XCTUnwrap(server.received.first) |
| + let lines = request.lowercased() |
| + XCTAssertTrue(request.hasPrefix("POST /api/v1/people HTTP/1.1"), request) |
| + XCTAssertTrue(lines.contains("origin: \(server.origin.absoluteString.lowercased())"), request) |
| + XCTAssertTrue(lines.contains("cookie: __host-rastrillo_session=s3cret"), request) |
| + XCTAssertTrue(lines.contains("content-type: application/json"), request) |
| + XCTAssertTrue(request.hasSuffix(#"{"email":"maria@acme.test"}"#), request) |
| + } |
| + |
| + func testTeamRefusalsAreTyped() async { |
| + let c = client(ScriptedTransport([json(409, #"{"code":"busy"}"#), json(403, #"{"code":"owner_only"}"#), |
| + json(404, #"{"code":"unknown_app"}"#), json(503, #"{"code":"unavailable"}"#), |
| + json(422, #"{"code":"bad_email"}"#), json(502, #"{"code":"mail_failed"}"#), |
| + json(403, #"{"code":"owner_only"}"#), json(413, #"{"code":"too_large"}"#)])) |
| + await XCTAssertThrows(.team(.busy)) { _ = try await c.uninstall(app: "scratchpad") } |
| + await XCTAssertThrows(.team(.ownerOnly)) { _ = try await c.install(app: "scratchpad") } |
| + await XCTAssertThrows(.team(.unknownApp)) { _ = try await c.install(app: "nope") } |
| + await XCTAssertThrows(.team(.unavailable)) { _ = try await c.store() } |
| + await XCTAssertThrows(.team(.badEmail)) { _ = try await c.invite(email: "x") } |
| + await XCTAssertThrows(.team(.mailFailed)) { _ = try await c.invite(email: "x@acme.test") } |
| + await XCTAssertThrows(.team(.ownerOnly)) { _ = try await c.invite(email: "x@acme.test") } |
| + await XCTAssertThrows(.server(status: 413, code: "too_large", state: nil)) { _ = try await c.invite(email: "x@acme.test") } |
| + } |
| + |
| + /// P3: an older Base has no such routes; the app opens the web page. |
| + func testAnOlderBaseIsNotOnThisBase() async { |
| + let c = client(ScriptedTransport([.respond(status: 404, body: Data("404 page not found".utf8)), .respond(status: 404), |
| + .respond(status: 404)])) |
| + await XCTAssertThrows(.notOnThisBase) { _ = try await c.store() } |
| + await XCTAssertThrows(.notOnThisBase) { _ = try await c.people() } |
| + await XCTAssertThrows(.notOnThisBase) { _ = try await c.install(app: "welcome") } |
| + } |
| + |
| + func testTeamCallsThatBaseRefusesTellTheKit() async { |
| + let rejections = Rejections() |
| + let c = client(ScriptedTransport([json(401, #"{"code":"unauthenticated"}"#), json(401, #"{"code":"unauthenticated"}"#)]), rejections) |
| + await XCTAssertThrows(.unauthenticated) { _ = try await c.store() } |
| + await XCTAssertThrows(.unauthenticated) { _ = try await c.invite(email: "x@acme.test") } |
| + XCTAssertEqual(rejections.count, 2) |
| + } |
| +} |
diff --git a/native/apple/Tests/BaseKitTests/Fixtures/people.json b/native/apple/Tests/BaseKitTests/Fixtures/people.json| new file mode 100644 |
| index 0000000..1a4b19e |
| --- /dev/null |
| +++ b/native/apple/Tests/BaseKitTests/Fixtures/people.json |
| @@ -0,0 +1,9 @@ |
| +{ |
| + "owner": false, |
| + "people": [ |
| + {"id": "m-owner", "initial": "O", "name": "", "email": "owner@acme.test", "role": "owner"}, |
| + {"id": "m-ana", "initial": "A", "name": "Ana Ruiz", "email": "ana@acme.test", "role": "member"}, |
| + {"id": "m-bob", "initial": "B", "name": "", "email": "bob@acme.test", "role": "invited"}, |
| + {"id": "m-new", "initial": "N", "name": "", "email": "new@acme.test", "role": "guest"} |
| + ] |
| +} |
diff --git a/native/apple/Tests/BaseKitTests/Fixtures/store.json b/native/apple/Tests/BaseKitTests/Fixtures/store.json| new file mode 100644 |
| index 0000000..9a94395 |
| --- /dev/null |
| +++ b/native/apple/Tests/BaseKitTests/Fixtures/store.json |
| @@ -0,0 +1,10 @@ |
| +{ |
| + "owner": true, |
| + "rows": [ |
| + {"id": "welcome", "name": "Welcome", "summary": "A short tour of your team's Base.", "tint": "amber", "icon_svg": "<svg viewBox=\"0 0 24 24\"><path d=\"M12 3v4\"/></svg>", "state": "installed", "error": ""}, |
| + {"id": "scratchpad", "name": "Scratchpad", "summary": "A shared page for quick notes.", "tint": "rose", "icon_svg": "<svg viewBox=\"0 0 24 24\"></svg>", "state": "installing", "error": ""}, |
| + {"id": "contra", "name": "Contra", "summary": "Passwords only your own devices can open.", "tint": "teal", "icon_svg": "<svg viewBox=\"0 0 24 24\"></svg>", "state": "failed", "error": "The app did not start answering"}, |
| + {"id": "future", "name": "Future", "summary": "From a newer Base.", "tint": "violet", "icon_svg": "", "state": "paused", "error": "", "new_field": 1}, |
| + {"name": "No id"} |
| + ] |
| +} |