fix: comprehensive codebase hardening — crashes, silent failures, performance, and security
Fixes ~95 issues from deep audit across 12 categories in 82 files: - Crash prevention: double-resume in PhotoMetadataExtractor, force unwraps in DateRangePicker, array bounds checks in polls/achievements, ProGate hit-test bypass, Dictionary(uniqueKeysWithValues:) → uniquingKeysWith in 4 files - Silent failure elimination: all 34 try? sites replaced with do/try/catch + logging (SavedTrip, TripDetailView, CanonicalSyncService, BootstrapService, CanonicalModels, CKModels, SportsTimeApp, and more) - Performance: cached DateFormatters (7 files), O(1) team lookups via AppDataProvider, achievement definition dictionary, AnimatedBackground consolidated from 19 Tasks to 1, task cancellation in SharePreviewView - Concurrency: UIKit drawing → MainActor.run, background fetch timeout guard, @MainActor on ThemeManager/AppearanceManager, SyncLogger read/write race fix - Planning engine: game end time in travel feasibility, state-aware city normalization, exact city matching, DrivingConstraints parameter propagation - IAP: unknown subscription states → expired, unverified transaction logging, entitlements updated before paywall dismiss, restore visible to all users - Security: API key to Info.plist lookup, filename sanitization in PDF export, honest User-Agent, removed stale "Feels" analytics super properties - Navigation: consolidated competing navigationDestination, boolean → value-based - Testing: 8 sleep() → waitForExistence, duplicates extracted, Swift 6 compat - Service bugs: infinite retry cap, duplicate achievement prevention, TOCTOU vote fix, PollVote.odg → voterId rename, deterministic placeholder IDs, parallel MKDirections, Sendable-safe POI struct Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -47,6 +47,9 @@ enum GameDAGRouter {
|
||||
|
||||
// MARK: - Configuration
|
||||
|
||||
/// Cached Calendar.current to avoid repeated access in tight loops
|
||||
private static let cachedCalendar = Calendar.current
|
||||
|
||||
/// Default beam width during expansion (for typical datasets)
|
||||
private static let defaultBeamWidth = 100
|
||||
|
||||
@@ -213,12 +216,19 @@ enum GameDAGRouter {
|
||||
for path in beam {
|
||||
guard let lastGame = path.last else { continue }
|
||||
|
||||
// Maintain visited cities set incrementally instead of rebuilding per candidate
|
||||
let pathCities: Set<String>
|
||||
if !allowRepeatCities {
|
||||
pathCities = Set(path.compactMap { stadiums[$0.stadiumId]?.city })
|
||||
} else {
|
||||
pathCities = []
|
||||
}
|
||||
|
||||
// Try adding each of today's games
|
||||
for candidate in todaysGames {
|
||||
// Check for repeat city violation
|
||||
if !allowRepeatCities {
|
||||
let candidateCity = stadiums[candidate.stadiumId]?.city ?? ""
|
||||
let pathCities = Set(path.compactMap { stadiums[$0.stadiumId]?.city })
|
||||
if pathCities.contains(candidateCity) {
|
||||
continue
|
||||
}
|
||||
@@ -504,17 +514,17 @@ enum GameDAGRouter {
|
||||
private static func bucketByDay(games: [Game]) -> [Int: [Game]] {
|
||||
guard let firstGame = games.first else { return [:] }
|
||||
let referenceDate = firstGame.startTime
|
||||
let calendar = Calendar.current
|
||||
|
||||
var buckets: [Int: [Game]] = [:]
|
||||
for game in games {
|
||||
let dayIndex = dayIndexFor(game.startTime, referenceDate: referenceDate)
|
||||
let dayIndex = dayIndexFor(game.startTime, referenceDate: referenceDate, calendar: calendar)
|
||||
buckets[dayIndex, default: []].append(game)
|
||||
}
|
||||
return buckets
|
||||
}
|
||||
|
||||
private static func dayIndexFor(_ date: Date, referenceDate: Date) -> Int {
|
||||
let calendar = Calendar.current
|
||||
private static func dayIndexFor(_ date: Date, referenceDate: Date, calendar: Calendar = .current) -> Int {
|
||||
let refDay = calendar.startOfDay(for: referenceDate)
|
||||
let dateDay = calendar.startOfDay(for: date)
|
||||
return calendar.dateComponents([.day], from: refDay, to: dateDay).day ?? 0
|
||||
@@ -548,8 +558,8 @@ enum GameDAGRouter {
|
||||
|
||||
let drivingHours = distanceMiles / 60.0
|
||||
|
||||
// Check if same calendar day
|
||||
let calendar = Calendar.current
|
||||
// Check if same calendar day (cache Calendar.current for performance in tight loops)
|
||||
let calendar = cachedCalendar
|
||||
let daysBetween = calendar.dateComponents(
|
||||
[.day],
|
||||
from: calendar.startOfDay(for: from.startTime),
|
||||
@@ -574,7 +584,9 @@ enum GameDAGRouter {
|
||||
}
|
||||
|
||||
// Calculate available time
|
||||
let departureTime = from.startTime.addingTimeInterval(postGameBuffer * 3600)
|
||||
// Use end time: startTime + estimated game duration (~3h) + post-game buffer
|
||||
let estimatedGameDurationHours: Double = 3.0
|
||||
let departureTime = from.startTime.addingTimeInterval((estimatedGameDurationHours + postGameBuffer) * 3600)
|
||||
let deadline = to.startTime.addingTimeInterval(-preGameBuffer * 3600)
|
||||
let availableHours = deadline.timeIntervalSince(departureTime) / 3600.0
|
||||
|
||||
|
||||
@@ -58,7 +58,7 @@ enum RouteFilters {
|
||||
var cityDays: [String: Set<Date>] = [:]
|
||||
|
||||
for stop in option.stops {
|
||||
let city = normalizedCityKey(stop.city)
|
||||
let city = normalizedCityKey(stop.city, state: stop.state)
|
||||
guard !city.isEmpty else { continue }
|
||||
let day = calendar.startOfDay(for: stop.arrivalDate)
|
||||
cityDays[city, default: []].insert(day)
|
||||
@@ -86,7 +86,7 @@ enum RouteFilters {
|
||||
var cityDays: [String: Set<Date>] = [:]
|
||||
var displayNames: [String: String] = [:]
|
||||
for stop in option.stops {
|
||||
let normalized = normalizedCityKey(stop.city)
|
||||
let normalized = normalizedCityKey(stop.city, state: stop.state)
|
||||
guard !normalized.isEmpty else { continue }
|
||||
|
||||
if displayNames[normalized] == nil {
|
||||
@@ -103,9 +103,12 @@ enum RouteFilters {
|
||||
return Array(violatingCities).sorted()
|
||||
}
|
||||
|
||||
private static func normalizedCityKey(_ city: String) -> String {
|
||||
let cityPart = city.split(separator: ",", maxSplits: 1).first.map(String.init) ?? city
|
||||
return cityPart
|
||||
/// Normalizes a city name for comparison, including state to distinguish
|
||||
/// cities like Portland, OR from Portland, ME.
|
||||
private static func normalizedCityKey(_ city: String, state: String = "") -> String {
|
||||
// Include state in the normalized key to distinguish same-named cities in different states
|
||||
let base = state.isEmpty ? city : "\(city), \(state)"
|
||||
return base
|
||||
.lowercased()
|
||||
.replacingOccurrences(of: ".", with: "")
|
||||
.split(whereSeparator: \.isWhitespace)
|
||||
|
||||
@@ -457,7 +457,9 @@ final class ScenarioAPlanner: ScenarioPlanner {
|
||||
let targetCity = normalizeCityName(cityName)
|
||||
let stadiumCity = normalizeCityName(stadium.city)
|
||||
guard !targetCity.isEmpty, !stadiumCity.isEmpty else { return false }
|
||||
return stadiumCity == targetCity || stadiumCity.contains(targetCity) || targetCity.contains(stadiumCity)
|
||||
// Use exact match after normalization to avoid false positives
|
||||
// (e.g., "New York" matching "York" via .contains())
|
||||
return stadiumCity == targetCity
|
||||
}
|
||||
|
||||
private func normalizeCityName(_ value: String) -> String {
|
||||
|
||||
@@ -233,18 +233,19 @@ enum TravelEstimator {
|
||||
/// - Parameters:
|
||||
/// - departure: Departure date/time
|
||||
/// - drivingHours: Total driving hours
|
||||
/// - drivingConstraints: Optional driving constraints to determine max daily hours (defaults to 8.0)
|
||||
/// - Returns: Array of calendar days (start of day) that travel spans
|
||||
///
|
||||
/// - Expected Behavior:
|
||||
/// - 0 hours → [departure day]
|
||||
/// - 1-8 hours → [departure day] (1 day)
|
||||
/// - 8.01-16 hours → [departure day, next day] (2 days)
|
||||
/// - 16.01-24 hours → [departure day, +1, +2] (3 days)
|
||||
/// - 1-maxDaily hours → [departure day] (1 day)
|
||||
/// - maxDaily+0.01 to 2*maxDaily hours → [departure day, next day] (2 days)
|
||||
/// - All dates are normalized to start of day (midnight)
|
||||
/// - Assumes 8 driving hours per day max
|
||||
/// - Uses maxDailyDrivingHours from constraints when provided
|
||||
static func calculateTravelDays(
|
||||
departure: Date,
|
||||
drivingHours: Double
|
||||
drivingHours: Double,
|
||||
drivingConstraints: DrivingConstraints? = nil
|
||||
) -> [Date] {
|
||||
var days: [Date] = []
|
||||
let calendar = Calendar.current
|
||||
@@ -252,8 +253,9 @@ enum TravelEstimator {
|
||||
let startDay = calendar.startOfDay(for: departure)
|
||||
days.append(startDay)
|
||||
|
||||
// Add days if driving takes multiple days (8 hrs/day max)
|
||||
let daysOfDriving = max(1, Int(ceil(drivingHours / 8.0)))
|
||||
// Use max daily hours from constraints, defaulting to 8.0
|
||||
let maxDailyHours = drivingConstraints?.maxDailyDrivingHours ?? 8.0
|
||||
let daysOfDriving = max(1, Int(ceil(drivingHours / maxDailyHours)))
|
||||
for dayOffset in 1..<daysOfDriving {
|
||||
if let nextDay = calendar.date(byAdding: .day, value: dayOffset, to: startDay) {
|
||||
days.append(nextDay)
|
||||
|
||||
Reference in New Issue
Block a user