Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 13 additions & 7 deletions FitCheck/Services/OpenMeteoProvider.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@ import CoreLocation
/// metric units outright so nothing here has to convert.
///
/// The trade is that a coordinate leaves the device. It arrives here already
/// rounded to two decimals by the seam in `WeatherService`, which is where the
/// rule lives: a little over a kilometre is far coarser than the fix itself and
/// makes no practical difference to a temperature reading. The `%.2f` below is
/// belt-and-braces — it keeps the request coarse even if that guarantee ever
/// regresses upstream.
/// rounded by the gate in `WeatherService`, which is where the rule lives: a
/// little over a kilometre is far coarser than the fix itself and makes no
/// practical difference to a temperature reading. This request formats with the
/// same `CoordinatePrecision.decimalPlaces` anyway — belt-and-braces, so it
/// stays coarse even if the guarantee upstream ever regresses.
struct OpenMeteoProvider: WeatherProvider {

/// The session is injected so the request can be pointed at a stub and
Expand All @@ -27,8 +27,8 @@ struct OpenMeteoProvider: WeatherProvider {
components.queryItems = [
// Two decimals is a little over a kilometre. The reading is
// identical at that resolution and the request carries less.
.init(name: "latitude", value: String(format: "%.2f", coordinate.latitude)),
.init(name: "longitude", value: String(format: "%.2f", coordinate.longitude)),
.init(name: "latitude", value: text(coordinate.latitude)),
.init(name: "longitude", value: text(coordinate.longitude)),
.init(name: "current", value: "temperature_2m,apparent_temperature,weather_code,wind_speed_10m,is_day"),
.init(name: "daily", value: "temperature_2m_max,temperature_2m_min,precipitation_probability_max"),
.init(name: "wind_speed_unit", value: "kmh"),
Expand Down Expand Up @@ -66,6 +66,12 @@ struct OpenMeteoProvider: WeatherProvider {
)
}

/// One axis as the request writes it: the seam's precision, never a literal
/// that could drift from the rule the gate applies.
private func text(_ value: Double) -> String {
String(format: "%.\(CoordinatePrecision.decimalPlaces)f", value)
}

// MARK: Wire format

private struct Payload: Decodable {
Expand Down
58 changes: 36 additions & 22 deletions FitCheck/Services/WeatherService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,30 @@ struct MapKitPlaceNamer: PlaceNaming {
}
}

/// How much of a position may leave the device.
///
/// Two decimals is a little over a kilometre, and a reading is identical at that
/// resolution, so nothing finer has any reason to travel — not to the forecast
/// and not to the map that names the place. The rule sits here, above the
/// service's single gate, rather than in a provider or the namer: whoever is
/// asked must not get to decide how much of a position it sees, and a second
/// implementation added to either seam inherits it for free.
enum CoordinatePrecision {
/// The decimals a coordinate keeps. Two is a little over a kilometre.
static let decimalPlaces = 2

/// The factor a coordinate is multiplied by to round at that place.
private static let scale = pow(10, Double(decimalPlaces))

/// The pair rounded to `decimalPlaces`, on both axes.
static func rounded(_ coordinate: CLLocationCoordinate2D) -> CLLocationCoordinate2D {
CLLocationCoordinate2D(
latitude: (coordinate.latitude * scale).rounded() / scale,
longitude: (coordinate.longitude * scale).rounded() / scale
)
}
}

/// Reads current conditions for the device's location, through whichever
/// `WeatherProvider` the build was handed.
///
Expand Down Expand Up @@ -351,7 +375,7 @@ final class WeatherService: NSObject {

do {
let place = try await readingPlace()
let reading = try await provider.current(at: Self.roundedForForecast(place.coordinate))
let reading = try await provider.current(at: place.coordinate)

snapshot = WeatherSnapshot(
temperature: reading.temperature,
Expand All @@ -377,36 +401,26 @@ final class WeatherService: NSObject {
}
}

/// The coordinate to describe and the name to show for it.
/// The coordinate to describe and the name to show for it, both already
/// reduced to what may leave the device.
///
/// A named place wins over a fix and is never renamed: the wearer's own
/// wording is better than anything the map would answer, and it costs no
/// request. With no name stored this is the device path, which asks the
/// place namer — and gets an empty name when the map has nothing to say.
///
/// Rounding happens here, before either seam is handed the pair, so the map
/// and the forecast see the same coarse coordinate instead of each deciding
/// how much of a position to take.
private func readingPlace() async throws -> (coordinate: CLLocationCoordinate2D, name: String) {
if let namedCoordinate, let namedPlace {
return (namedCoordinate, namedPlace)
return (CoordinatePrecision.rounded(namedCoordinate), namedPlace)
}

let location = try await currentLocation()
return (location.coordinate, await naming.name(for: location))
}

/// The scale that leaves two decimals — a little over a kilometre.
private static let forecastCoordinateScale: Double = 100

/// The precision a coordinate is reduced to before it leaves the device.
///
/// Two decimals is a little over a kilometre, and the reading is identical
/// at that resolution, so nothing finer has any reason to travel. The rule
/// lives here, at the one call into the provider, rather than in a provider:
/// whoever answers must not get to decide how much of a position it sees,
/// and a second implementation added to the seam inherits it for free.
private static func roundedForForecast(_ coordinate: CLLocationCoordinate2D) -> CLLocationCoordinate2D {
CLLocationCoordinate2D(
latitude: (coordinate.latitude * forecastCoordinateScale).rounded() / forecastCoordinateScale,
longitude: (coordinate.longitude * forecastCoordinateScale).rounded() / forecastCoordinateScale
)
let fix = try await currentLocation()
let coordinate = CoordinatePrecision.rounded(fix.coordinate)
let location = CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude)
return (coordinate, await naming.name(for: location))
}

private func currentLocation() async throws -> CLLocation {
Expand Down
74 changes: 65 additions & 9 deletions FitCheckTests/WeatherProviderSeamTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -55,26 +55,37 @@ private final class CoordinateLog: @unchecked Sendable {
}

/// Counts how often the placeholder namer was asked, so a test can tell a name
/// that came through the seam from one that was never resolved at all. A lock
/// for the same reason as `CoordinateLog`: the namer is `Sendable`.
/// that came through the seam from one that was never resolved at all, and
/// keeps the position it was asked about — the map is the second thing a fix
/// reaches, so what it sees is part of the same promise. A lock for the same
/// reason as `CoordinateLog`: the namer is `Sendable`.
private final class NamingLog: @unchecked Sendable {
private let lock = NSLock()
private var recordedCalls = 0
private var recordedCoordinate: CLLocationCoordinate2D?

var calls: Int { lock.withLock { recordedCalls } }

/// The pair the namer was handed, read back once the fetch is over.
var coordinate: CLLocationCoordinate2D? { lock.withLock { recordedCoordinate } }

func recordCall() { lock.withLock { recordedCalls += 1 } }

func record(_ coordinate: CLLocationCoordinate2D) {
lock.withLock { recordedCoordinate = coordinate }
}
}

/// What stands in for MapKit: one fixed label for any coordinate. The real
/// namer asks Apple's map stack, which cannot answer in the unit target — so
/// every service built here is handed this one instead, and the suite makes no
/// reverse-geocoding call at all.
/// What stands in for MapKit: one fixed label for any coordinate, and a note of
/// the position it was handed. The real namer asks Apple's map stack, which
/// cannot answer in the unit target — so every service built here is handed
/// this one instead, and the suite makes no reverse-geocoding call at all.
private struct FixedPlaceNamer: PlaceNaming {
let asked: NamingLog

func name(for location: CLLocation) async -> String {
asked.recordCall()
asked.record(location.coordinate)
return SeamFixture.placeLabel
}
}
Expand Down Expand Up @@ -222,9 +233,10 @@ private func isLocationTimedOut(_ error: WeatherFetchError?) -> Bool {

// MARK: - Suite

/// What the app promises at the seam: whoever answers the forecast gets a
/// position rounded to two decimals, a reading comes back as a snapshot, and a
/// failure comes back as an error the sheet can read — never a trap.
/// What the app promises at the seam: whoever answers the forecast, and whoever
/// names the place, gets one position rounded to two decimals; a reading comes
/// back as a snapshot, and a failure comes back as an error the sheet can read —
/// never a trap.
@MainActor
@Suite("Weather provider seam")
struct WeatherProviderSeamTests {
Expand Down Expand Up @@ -300,6 +312,50 @@ struct WeatherProviderSeamTests {
)
}

/// The other thing a fix leaves the device for: the map, to name the place.
/// It used to be handed the raw fix while the provider got the rounded one,
/// so one reading sent two positions out — the coarse pair and the exact
/// doorway. The gate rounds before either seam, so a raw fix reaching
/// MapKit goes red here, on the same promise as the test above.
@Test("The place namer is handed the same rounded coordinate as the provider")
func namerSeesTheRoundedCoordinate() async throws {
let handed = CoordinateLog()
let asked = NamingLog()
let testSubject = makeService(
provider: ScriptedWeatherProvider(answer: .reading(SeamFixture.reading), handed: handed),
naming: FixedPlaceNamer(asked: asked)
)

await testSubject.refresh()

let named = try #require(asked.coordinate)
let regression = "The CLLocation handed to the place namer is not rounded to two decimals: a raw fix reaches MapKit, so a position finer than a kilometre leaves the device on the map lookup."

#expect(
named.latitude == SeamFixture.roundedLatitude,
"\(regression) Expected \(SeamFixture.roundedLatitude), got \(named.latitude)."
)
#expect(
named.longitude == SeamFixture.roundedLongitude,
"\(regression) Expected \(SeamFixture.roundedLongitude), got \(named.longitude)."
)

// One pair, not two. The provider and the namer must not each be given a
// position the other never saw, because then neither call can say how
// much of a fix it was allowed to take.
let forecast = try #require(handed.coordinate)
#expect(
forecast.latitude == named.latitude && forecast.longitude == named.longitude,
"The provider was handed (\(forecast.latitude), \(forecast.longitude)) and the namer (\(named.latitude), \(named.longitude)): one reading sent two coordinates out, so the rounding rule is decided in more than one place."
)

// The name still crosses the seam, so the assertions above are about a
// real naming call rather than one that never landed.
let snapshot = try #require(testSubject.snapshot)
#expect(snapshot.locationName == SeamFixture.placeLabel)
#expect(asked.calls == 1)
}

@Test("A typed provider failure reaches lastError unchanged")
func typedFailureSurvivesTheSeam() async {
let testSubject = makeService(
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ Demo content in `Mocks/` stays English: it is data, not copy. The folder is not
* **Data Storage:** SwiftData (Local)
* **Weather Data:** [`WeatherProvider`](FitCheck/Services/WeatherProvider.swift) — Open-Meteo today (rounded coordinates, no account), WeatherKit as the release path

The forecast is the only thing that leaves the device, and it has two phases. Today's build sends Open-Meteo a coordinate rounded to two decimals — a little over a kilometre — and nothing else: no key, no account, nothing cached off-device. The release build switches to WeatherKit, where the coordinate stays inside Apple's stack; that provider is compiled but not wired, because WeatherKit needs the paid Apple Developer Program and a free profile cannot carry its entitlement. The switch is three things — WeatherKit enabled on the App ID, the entitlement block in `project.yml`, and one value in `WeatherProviderKind` — and it is mandatory before release: Open-Meteo's free tier is non-commercial only. The ordered cutover — App ID capability, entitlement, the value, the rebuild, and what to re-verify on the phone — is [`docs/weatherkit-cutover.md`](docs/weatherkit-cutover.md).
The forecast is the only thing that leaves the device, and it has two phases. Today's build sends Open-Meteo a coordinate rounded to two decimals — a little over a kilometre — and nothing else: no key, no account, nothing cached off-device. The place name on the sheet comes from MapKit's reverse geocoder, and that lookup leaves with the same two-decimal coordinate: one gate in `WeatherService` rounds the pair before either the namer or the provider is asked. The release build switches to WeatherKit, where the coordinate stays inside Apple's stack; that provider is compiled but not wired, because WeatherKit needs the paid Apple Developer Program and a free profile cannot carry its entitlement. The switch is three things — WeatherKit enabled on the App ID, the entitlement block in `project.yml`, and one value in `WeatherProviderKind` — and it is mandatory before release: Open-Meteo's free tier is non-commercial only. The ordered cutover — App ID capability, entitlement, the value, the rebuild, and what to re-verify on the phone — is [`docs/weatherkit-cutover.md`](docs/weatherkit-cutover.md).

---

Expand Down Expand Up @@ -215,7 +215,7 @@ A free Apple ID installs Fit Check on your own iPhone: no paid Apple Developer P

6. **Demo closet (optional).** The 39-garment wardrobe in `Mocks/` (not committed — [`docs/demo-assets.md`](docs/demo-assets.md)) is read only under `-seedDemo`. In Xcode, **Product › Scheme › Edit Scheme › Run › Arguments** and add `-seedDemo`, then run. It seeds only into an empty store, so a second launch adds nothing; delete the app to seed again. A scheme edited by hand is lost on the next `xcodegen generate`, because the project it lives in is regenerated. `-seedCloset` is a different flag: the five-garment fixture with one saved look that the UI tests assert against.

7. **Seven days, then reinstall.** A free profile expires seven days after it is signed. The app then stops opening — not a crash, and nothing is lost. Reconnect the phone and press ⌘R again: the profile is renewed and the app opens with its closet, looks and settings intact, because reinstalling over the same bundle identifier keeps the local store. Changing the bundle identifier is a different app and starts empty. One free Apple ID can keep three side-loaded apps on a device at a time; a fourth means deleting one first. Photos, garments, looks and every decision stay on the phone: the only traffic out is the forecast — a coordinate rounded to two decimals to Open-Meteo — and the MapKit lookup that names the place.
7. **Seven days, then reinstall.** A free profile expires seven days after it is signed. The app then stops opening — not a crash, and nothing is lost. Reconnect the phone and press ⌘R again: the profile is renewed and the app opens with its closet, looks and settings intact, because reinstalling over the same bundle identifier keeps the local store. Changing the bundle identifier is a different app and starts empty. One free Apple ID can keep three side-loaded apps on a device at a time; a fourth means deleting one first. Photos, garments, looks and every decision stay on the phone: the only traffic out is the forecast — a coordinate rounded to two decimals to Open-Meteo — and the MapKit lookup that names the place, which leaves with that same rounded coordinate.

8. **If it does not work.**
* *"Signing for 'FitCheck' requires a development team"* — the project was generated without the team, or a `xcodegen generate` since then erased the one Xcode had set. `export FITCHECK_TEAM_ID=XXXXXXXXXX && xcodegen generate` (step 2). The value is read at generate time, so exporting it now without regenerating changes nothing.
Expand Down
Loading
Loading