38 lines
834 B
Swift
38 lines
834 B
Swift
import Foundation
|
|
|
|
#if canImport(FoundationNetworking)
|
|
import FoundationNetworking
|
|
#endif
|
|
|
|
public actor MusicBrainzCoordinator {
|
|
private var nextAvailableTime: ContinuousClock.Instant = .now
|
|
private let clock = ContinuousClock()
|
|
private let session: URLSession
|
|
|
|
public init(session: URLSession = .shared) {
|
|
self.session = session
|
|
}
|
|
|
|
public func perform(_ request: URLRequest) async throws(MusicBrainzError) -> (Data, URLResponse)
|
|
{
|
|
let now = clock.now
|
|
let executionTime = max(now, nextAvailableTime)
|
|
nextAvailableTime = executionTime + .seconds(1)
|
|
let delay = now.duration(to: executionTime)
|
|
|
|
if delay > .zero {
|
|
do {
|
|
try await Task.sleep(for: delay)
|
|
} catch {
|
|
throw .coordinator(error)
|
|
}
|
|
}
|
|
|
|
do {
|
|
return try await session.data(for: request)
|
|
} catch {
|
|
throw .coordinator(error)
|
|
}
|
|
}
|
|
}
|