-
Notifications
You must be signed in to change notification settings - Fork 536
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Use CacheControlInfo to pay attention to the Cache-Control http respo…
…nse header and drop requests that are made too soon. We need to be nice to servers.
- Loading branch information
1 parent
80c78b6
commit e57e3c9
Showing
2 changed files
with
95 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,63 @@ | ||
// | ||
// CacheControl.swift | ||
// RSWeb | ||
// | ||
// Created by Brent Simmons on 11/30/24. | ||
// | ||
|
||
import Foundation | ||
|
||
/// Basic Cache-Control handling — just the part we need, | ||
/// which is to know when we got the response (dateCreated) | ||
/// and when we can ask again (dateExpired). | ||
public struct CacheControlInfo: Codable, Equatable { | ||
|
||
let dateCreated: Date | ||
let maxAge: TimeInterval | ||
|
||
var dateExpired: Date { | ||
dateCreated + maxAge | ||
} | ||
|
||
public init?(urlResponse: HTTPURLResponse) { | ||
guard let cacheControlValue = urlResponse.valueForHTTPHeaderField(HTTPResponseHeader.cacheControl) else { | ||
return nil | ||
} | ||
self.init(value: cacheControlValue) | ||
} | ||
|
||
/// Returns nil if there’s no max-age or it’s < 1. | ||
public init?(value: String) { | ||
|
||
guard let maxAge = Self.parseMaxAge(value) else { | ||
return nil | ||
} | ||
|
||
let d = Date() | ||
self.dateCreated = d | ||
self.maxAge = maxAge | ||
} | ||
} | ||
|
||
private extension CacheControlInfo { | ||
|
||
static let maxAgePrefix = "max-age=" | ||
static let maxAgePrefixCount = maxAgePrefix.count | ||
|
||
static func parseMaxAge(_ s: String) -> TimeInterval? { | ||
|
||
let components = s.components(separatedBy: ",") | ||
let trimmedComponents = components.map { $0.trimmingCharacters(in: .whitespaces) } | ||
|
||
for component in trimmedComponents { | ||
if component.hasPrefix(Self.maxAgePrefix) { | ||
let maxAgeStringValue = component.dropFirst(maxAgePrefixCount) | ||
if let timeInterval = TimeInterval(maxAgeStringValue), timeInterval > 0 { | ||
return timeInterval | ||
} | ||
} | ||
} | ||
|
||
return nil | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters