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
22 changes: 22 additions & 0 deletions Normal/Services/Keys/LocationFixPolicy.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import CoreLocation
import Foundation

struct LocationFixPolicy {
static let maxAge: TimeInterval = 30
static let clockTolerance: TimeInterval = 5

var maxAccuracy: CLLocationAccuracy?

static let inApp = LocationFixPolicy()

func accepts(_ fix: CLLocation, now: Date = .now) -> Bool {
let age = now.timeIntervalSince(fix.timestamp)
guard age >= -Self.clockTolerance,
age <= Self.maxAge,
fix.horizontalAccuracy >= 0,
fix.sourceInformation?.isSimulatedBySoftware != true
else { return false }
guard let maxAccuracy else { return true }
return fix.horizontalAccuracy <= maxAccuracy
}
}
10 changes: 5 additions & 5 deletions Normal/Services/Keys/LocationUnlockModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,6 @@ final class LocationUnlockModel {
private let provider: any LocationProviding
private let pollInterval: Duration

private static let maxCacheAge: TimeInterval = 30

init(keys: [Key], provider: any LocationProviding, pollInterval: Duration = .seconds(2)) {
let locationKeys = Key.locationKeys(in: keys)
self.locationKeys = locationKeys
Expand All @@ -51,9 +49,7 @@ final class LocationUnlockModel {
}

func verifyFromCache() -> Bool {
guard let cached = provider.cachedLocation,
cached.timestamp.timeIntervalSinceNow > -Self.maxCacheAge
else { return false }
guard let cached = provider.recentLocation, LocationFixPolicy.inApp.accepts(cached) else { return false }
location = cached
hasValidLocation = true
guard Key.locationKeyVerifies(keys: locationKeys, location: cached) else { return false }
Expand All @@ -64,6 +60,10 @@ final class LocationUnlockModel {
func checkOnce() async {
do {
let fix = try await provider.currentLocation()
guard LocationFixPolicy.inApp.accepts(fix) else {
phase = .unavailable
return
}
location = fix
hasValidLocation = true
phase = Key.locationKeyVerifies(keys: locationKeys, location: fix) ? .verified : .outOfRange
Expand Down
15 changes: 15 additions & 0 deletions Normal/Services/LocationService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ enum LocationKeyError: Error, Equatable {
protocol LocationProviding: AnyObject {
var authorizationStatus: CLAuthorizationStatus { get }
var cachedLocation: CLLocation? { get }
var recentLocation: CLLocation? { get }
func currentLocation() async throws -> CLLocation
}

Expand All @@ -52,7 +53,18 @@ final class LocationService: NSObject, LocationProviding {
return manager.location
}

var recentLocation: CLLocation? {
if UITestSupport.isActive {
return CLLocation(latitude: 37.33182, longitude: -122.03118)
}
guard let lastFix, lastFix.receivedAt.duration(to: .now) <= .seconds(LocationFixPolicy.maxAge) else {
return nil
}
return lastFix.location
}

private let manager = CLLocationManager()
private var lastFix: (location: CLLocation, receivedAt: ContinuousClock.Instant)?
private var locationContinuations: [CheckedContinuation<CLLocation, Error>] = []
private var authContinuations: [CheckedContinuation<CLAuthorizationStatus, Never>] = []

Expand Down Expand Up @@ -91,6 +103,9 @@ final class LocationService: NSObject, LocationProviding {
}

private func flushLocation(_ result: Result<CLLocation, Error>) {
if case let .success(location) = result {
lastFix = (location, .now)
}
let pending = locationContinuations
locationContinuations.removeAll()
for c in pending {
Expand Down
57 changes: 57 additions & 0 deletions NormalTests/Services/LocationFixPolicyTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import CoreLocation
import Foundation
@testable import Normal
import Testing

struct LocationFixPolicyTests {
private let now = Date()

private func fix(accuracy: CLLocationAccuracy = 10, age: TimeInterval = 0, simulated: Bool = false) -> CLLocation {
CLLocation(
coordinate: CLLocationCoordinate2D(latitude: 37.3349, longitude: -122.0090),
altitude: 0,
horizontalAccuracy: accuracy,
verticalAccuracy: 10,
course: 0,
courseAccuracy: 0,
speed: 0,
speedAccuracy: 0,
timestamp: now.addingTimeInterval(-age),
sourceInfo: CLLocationSourceInformation(
softwareSimulationState: simulated,
andExternalAccessoryState: false
)
)
}

@Test func acceptsAFreshFix() {
#expect(LocationFixPolicy.inApp.accepts(fix(), now: now))
}

@Test func rejectsAnOldFix() {
#expect(!LocationFixPolicy.inApp.accepts(fix(age: 31), now: now))
}

@Test func rejectsAFixFromTheFuture() {
#expect(!LocationFixPolicy.inApp.accepts(fix(age: -60), now: now))
}

@Test func toleratesSmallClockDrift() {
#expect(LocationFixPolicy.inApp.accepts(fix(age: -2), now: now))
}

@Test func rejectsASimulatedFix() {
#expect(!LocationFixPolicy.inApp.accepts(fix(simulated: true), now: now))
}

@Test func rejectsAnInvalidFix() {
#expect(!LocationFixPolicy.inApp.accepts(fix(accuracy: -1), now: now))
}

@Test func appliesAnAccuracyLimit() {
let policy = LocationFixPolicy(maxAccuracy: 100)
#expect(policy.accepts(fix(accuracy: 100), now: now))
#expect(!policy.accepts(fix(accuracy: 150), now: now))
#expect(LocationFixPolicy.inApp.accepts(fix(accuracy: 1500), now: now))
}
}
66 changes: 56 additions & 10 deletions NormalTests/Services/LocationUnlockModelTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -84,18 +84,30 @@ struct LocationUnlockModelTests {
#expect(model.phase == .permissionDenied)
}

private func cachedLocation(at coordinate: CLLocationCoordinate2D, secondsAgo: TimeInterval = 0) -> CLLocation {
private func fix(
at coordinate: CLLocationCoordinate2D,
secondsAgo: TimeInterval = 0,
simulated: Bool = false
) -> CLLocation {
CLLocation(
coordinate: coordinate,
altitude: 0,
horizontalAccuracy: 10,
verticalAccuracy: 10,
timestamp: Date(timeIntervalSinceNow: -secondsAgo)
course: 0,
courseAccuracy: 0,
speed: 0,
speedAccuracy: 0,
timestamp: Date(timeIntervalSinceNow: -secondsAgo),
sourceInfo: CLLocationSourceInformation(
softwareSimulationState: simulated,
andExternalAccessoryState: false
)
)
}

@Test func verifiesInstantlyFromFreshInZoneCache() {
let provider = FakeLocationProvider(outcome: .throwGeneric, cachedLocation: cachedLocation(at: Self.cupertino))
let provider = FakeLocationProvider(outcome: .throwGeneric, recentLocation: fix(at: Self.cupertino))
let model = LocationUnlockModel(keys: [locationKey(kind: .unblock)], provider: provider)
#expect(model.verifyFromCache())
#expect(model.phase == .verified)
Expand All @@ -104,27 +116,27 @@ struct LocationUnlockModelTests {
@Test func ignoresStaleCache() {
let provider = FakeLocationProvider(
outcome: .throwGeneric,
cachedLocation: cachedLocation(at: Self.cupertino, secondsAgo: 120)
recentLocation: fix(at: Self.cupertino, secondsAgo: 120)
)
let model = LocationUnlockModel(keys: [locationKey(kind: .unblock)], provider: provider)
#expect(!model.verifyFromCache())
#expect(model.phase == .checking)
}

@Test func ignoresCacheOutOfZone() {
let provider = FakeLocationProvider(outcome: .throwGeneric, cachedLocation: cachedLocation(at: Self.london))
let provider = FakeLocationProvider(outcome: .throwGeneric, recentLocation: fix(at: Self.london))
let model = LocationUnlockModel(keys: [locationKey(kind: .unblock)], provider: provider)
#expect(!model.verifyFromCache())
}

@Test func ignoresMissingCache() {
let provider = FakeLocationProvider(outcome: .throwGeneric, cachedLocation: nil)
let provider = FakeLocationProvider(outcome: .throwGeneric)
let model = LocationUnlockModel(keys: [locationKey(kind: .unblock)], provider: provider)
#expect(!model.verifyFromCache())
}

@Test func runVerifiesFromFreshCacheWithoutGPSWait() async {
let provider = FakeLocationProvider(outcome: .throwGeneric, cachedLocation: cachedLocation(at: Self.cupertino))
let provider = FakeLocationProvider(outcome: .throwGeneric, recentLocation: fix(at: Self.cupertino))
let model = LocationUnlockModel(keys: [locationKey(kind: .unblock)], provider: provider)
await model.run()
#expect(model.phase == .verified)
Expand All @@ -136,7 +148,7 @@ struct LocationUnlockModelTests {
}

@Test func freshCacheMarksLocationValidEvenWhenOutOfZone() {
let provider = FakeLocationProvider(outcome: .throwGeneric, cachedLocation: cachedLocation(at: Self.london))
let provider = FakeLocationProvider(outcome: .throwGeneric, recentLocation: fix(at: Self.london))
let model = LocationUnlockModel(keys: [locationKey(kind: .unblock)], provider: provider)
#expect(!model.verifyFromCache())
#expect(model.hasValidLocation)
Expand All @@ -145,7 +157,7 @@ struct LocationUnlockModelTests {
@Test func staleCacheDoesNotMarkLocationValid() {
let provider = FakeLocationProvider(
outcome: .throwGeneric,
cachedLocation: cachedLocation(at: Self.cupertino, secondsAgo: 120)
recentLocation: fix(at: Self.cupertino, secondsAgo: 120)
)
let model = LocationUnlockModel(keys: [locationKey()], provider: provider)
_ = model.verifyFromCache()
Expand Down Expand Up @@ -174,11 +186,45 @@ struct LocationUnlockModelTests {
@Test func runSeedsStaleCacheAsGreyDotLocation() async {
let provider = FakeLocationProvider(
outcome: .throwKeyError(.denied),
cachedLocation: cachedLocation(at: Self.cupertino, secondsAgo: 600)
cachedLocation: fix(at: Self.cupertino, secondsAgo: 600)
)
let model = LocationUnlockModel(keys: [locationKey()], provider: provider)
await model.run()
#expect(model.location?.coordinate.latitude == Self.cupertino.latitude)
#expect(!model.hasValidLocation)
}

@Test func ignoresFutureDatedRecentFix() {
let provider = FakeLocationProvider(
outcome: .throwGeneric,
recentLocation: fix(at: Self.cupertino, secondsAgo: -120)
)
let model = LocationUnlockModel(keys: [locationKey(kind: .unblock)], provider: provider)
#expect(!model.verifyFromCache())
#expect(!model.hasValidLocation)
}

@Test func ignoresSimulatedRecentFix() {
let provider = FakeLocationProvider(
outcome: .throwGeneric,
recentLocation: fix(at: Self.cupertino, simulated: true)
)
let model = LocationUnlockModel(keys: [locationKey(kind: .unblock)], provider: provider)
#expect(!model.verifyFromCache())
}

@Test func rejectsSimulatedFix() async {
let provider = FakeLocationProvider(outcome: .location(fix(at: Self.cupertino, simulated: true)))
let model = LocationUnlockModel(keys: [locationKey(kind: .unblock)], provider: provider)
await model.checkOnce()
#expect(model.phase == .unavailable)
#expect(!model.hasValidLocation)
}

@Test func rejectsStaleFix() async {
let provider = FakeLocationProvider(outcome: .location(fix(at: Self.cupertino, secondsAgo: 120)))
let model = LocationUnlockModel(keys: [locationKey(kind: .unblock)], provider: provider)
await model.checkOnce()
#expect(model.phase == .unavailable)
}
}
5 changes: 4 additions & 1 deletion NormalTests/TestSupport/FakeLocationProvider.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,18 @@ final class FakeLocationProvider: LocationProviding {
var outcome: Outcome
var authorizationStatus: CLAuthorizationStatus
var cachedLocation: CLLocation?
var recentLocation: CLLocation?

init(
outcome: Outcome,
authorizationStatus: CLAuthorizationStatus = .authorizedWhenInUse,
cachedLocation: CLLocation? = nil
cachedLocation: CLLocation? = nil,
recentLocation: CLLocation? = nil
) {
self.outcome = outcome
self.authorizationStatus = authorizationStatus
self.cachedLocation = cachedLocation
self.recentLocation = recentLocation
}

convenience init(at coordinate: CLLocationCoordinate2D) {
Expand Down
Loading