Everything works well and good structure.
This commit is contained in:
37
Sources/MusicBrainz/MusicBrainzCoordinator.swift
Normal file
37
Sources/MusicBrainz/MusicBrainzCoordinator.swift
Normal file
@@ -0,0 +1,37 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user