Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add logs to Atlas geocoding #620

Merged
merged 2 commits into from
Sep 14, 2023
Merged
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
18 changes: 18 additions & 0 deletions Sources/Site/Music/Atlas.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@

import CoreLocation
import Foundation
import os

extension Logger {
static let atlas = Logger(category: "atlas")
}

protocol Geocodable: Hashable {
func geocode() async throws -> CLPlacemark
Expand All @@ -26,30 +31,41 @@ actor Atlas<T: Geocodable> {
private var waitUntil: ContinuousClock.Instant = .now + Constants.timeUntilReset

private func reset() {
Logger.atlas.log("reset")
waitUntil = .now + Constants.timeUntilReset
count = 0
}

private func idleAndReset() async throws {
Logger.atlas.log("idleAndReset")
try await ContinuousClock().sleep(until: waitUntil)
reset()
}

public func geocode(_ geocodable: T) async throws -> CLPlacemark {
if let result = self[geocodable] {
Logger.atlas.log("cached result")
return result
}

let result = try await gatedGeocode(geocodable)
self[geocodable] = result
return result
}

private func gatedGeocode(_ geocodable: T) async throws -> CLPlacemark {
Logger.atlas.log("start gatedGeocode")
defer {
Logger.atlas.log("end gatedGeocode")
}

if ContinuousClock.now.duration(to: waitUntil) <= .seconds(0) {
// wait time expired
Logger.atlas.log("wait expired")
reset()
} else if count != 0, count % Constants.maxRequests == 0 {
// hit max requests
Logger.atlas.log("reached max requests")
try await idleAndReset()
}

Expand All @@ -61,10 +77,12 @@ actor Atlas<T: Geocodable> {
return placemark
} catch let error as NSError {
if error.code == CLError.network.rawValue, error.domain == kCLErrorDomain {
Logger.atlas.log("throttle: \(error.localizedDescription, privacy: .public)")
// throttling error
try await idleAndReset()
retry = true
} else {
Logger.atlas.log("error: \(error.localizedDescription, privacy: .public)")
throw error
}
} catch {
Expand Down