Skip to content
Merged
Show file tree
Hide file tree
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
21 changes: 9 additions & 12 deletions Sources/Early/BrowserApplication.swift
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,6 @@ final class EarlyAppDelegate: NSObject, NSApplicationDelegate {
@ObservationIgnored private var pendingRestoredWindows: Set<UUID> = []
@ObservationIgnored private var profileCleanupTask: Task<Void, Never>?
@ObservationIgnored private var profileCleanupError: String?
@ObservationIgnored private var profileCleanupIcons: [UUID: [FaviconStore]] = [:]
private var primaryWindowIsOpen = false
/// Whether the window in front shows a page, for ⌘W's title. SwiftUI
/// doesn't observe the key window, and a menu that read it itself kept
Expand Down Expand Up @@ -643,6 +642,7 @@ final class EarlyAppDelegate: NSObject, NSApplicationDelegate {
let since = range.start(now: Date())
return await historyRemoval(for: profile).remove(.since(since), from: history, clearWebsiteData: { [self] in
await websiteDataStore(for: profile).removeData(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes(), modifiedSince: since ?? .distantPast)
await FaviconStore.removeCachedIcons(for: profile, since: since, keeping: sidebarURLs(profileID: profile), ephemeral: testing)
}, didChange: { [weak self] in self?.didChangeHistory(profileID: profile) })
}

Expand Down Expand Up @@ -1122,17 +1122,18 @@ final class EarlyAppDelegate: NSObject, NSApplicationDelegate {
return await persistence.flush()
}

/// Every tab, pin and Favorite address in the profile's open windows.
/// Every tab, pin and Favorite address in the profile's sidebar.
func sidebarURLs(profileID: UUID) -> [URL] {
visibleModels.filter { $0.coordinator.profileID == profileID }.flatMap(\.sidebarURLs)
let models = visibleModels.filter { $0.coordinator.profileID == profileID }
if !models.isEmpty { return models.flatMap(\.sidebarURLs) }
guard let session = workspace?.session(for: profileID) else { return [] }
let tabs = session.tabs + session.additionalWindows.flatMap(\.tabs)
return tabs.flatMap { [$0.currentURL, $0.pinnedURL].compactMap { $0 } }
}

/// One window cleared the profile's shared website data; the others drop
/// icons of sites no longer in the sidebar and reload History.
/// Other windows refresh History after the shared website data is cleared.
func didClearWebsiteData(profileID: UUID, from source: BrowserWindowModel) {
let kept = sidebarURLs(profileID: profileID)
for target in visibleModels where target !== source && target.coordinator.profileID == profileID {
target.webViews.forgetClearedArtwork(keepingIconsFor: kept)
target.historyRevision += 1
target.refreshRecentPages()
}
Expand Down Expand Up @@ -1291,8 +1292,6 @@ final class EarlyAppDelegate: NSObject, NSApplicationDelegate {
// its windows, credentials, extension data and permissions be removed.
workspace = draft
profileError = nil
let icons = visibleModels.filter { $0.coordinator.profileID == id }.map { $0.webViews.favicons }
profileCleanupIcons[id] = icons
let closing = windows.filter { $0.model.coordinator.profileID == id }.map(\.id)
for windowID in closing {
nativeWindow(id: windowID)?.close()
Expand Down Expand Up @@ -1456,9 +1455,7 @@ final class EarlyAppDelegate: NSObject, NSApplicationDelegate {
await attempt("Website data") { try await WKWebsiteDataStore.remove(forIdentifier: id) }
}
await attempt("Website icons") {
for store in profileCleanupIcons[id] ?? [] { await store.shutdown() }
if !testing { try await FaviconStore.removeCache(for: id) }
profileCleanupIcons[id] = nil
try await FaviconStore.removeCache(for: id, ephemeral: testing)
}
if !failures.isEmpty { throw ProfileCleanupFailure(failures: failures) }
}
Expand Down
87 changes: 59 additions & 28 deletions Sources/EarlyWeb/BoundedResponse.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,62 +9,81 @@ import Foundation
final class BoundedResponse: NSObject, URLSessionDataDelegate, @unchecked Sendable {
/// Whether to follow a redirect to the new request.
typealias Redirects = @Sendable (HTTPURLResponse, URLRequest) -> Bool
typealias Output = (Data, URLResponse)

private enum Completion {
case unregistered
case waiting(CheckedContinuation<Output, any Error>)
case finished(Result<Output, any Error>)
}

private let limit: Int
private let redirects: Redirects
/// Guards what the session's queue and the caller share.
private let lock = NSLock()
private var body = Data()
private var response: URLResponse?
private var continuation: CheckedContinuation<(Data, URLResponse), any Error>?
private var completion = Completion.unregistered
private var exceededLimit = false

private init(limit: Int, redirects: @escaping Redirects) {
init(limit: Int, redirects: @escaping Redirects = { _, _ in true }) {
self.limit = limit
self.redirects = redirects
}

static func load(_ request: URLRequest, in session: URLSession, limit: Int,
redirects: @escaping Redirects = { _, _ in true }) async throws -> (Data, URLResponse) {
redirects: @escaping Redirects = { _, _ in true }) async throws -> Output {
let reader = BoundedResponse(limit: limit, redirects: redirects)
let task = session.dataTask(with: request)
task.delegate = reader
return try await withTaskCancellationHandler {
try await withCheckedThrowingContinuation { continuation in
reader.lock.withLock { reader.continuation = continuation }
task.resume()
}
try await reader.waitForCompletion(starting: task.resume)
} onCancel: {
task.cancel()
}
}

private func finish(_ result: Result<(Data, URLResponse), any Error>) {
let waiting = lock.withLock { () -> CheckedContinuation<(Data, URLResponse), any Error>? in
defer { continuation = nil }
return continuation
func waitForCompletion(starting start: @Sendable () -> Void) async throws -> Output {
try await withCheckedThrowingContinuation { continuation in
let result = lock.withLock { () -> Result<Output, any Error>? in
switch completion {
case .finished(let result): return result
case .waiting: preconditionFailure("A response can have only one waiter")
case .unregistered:
completion = .waiting(continuation)
return nil
}
}
if let result { continuation.resume(with: result) }
else { start() }
}
waiting?.resume(with: result)
}

func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse,
completionHandler: @escaping @Sendable (URLSession.ResponseDisposition) -> Void) {
guard response.expectedContentLength <= limit else {
finish(.failure(URLError(.dataLengthExceedsMaximum)))
completionHandler(.cancel)
return
let allow = lock.withLock {
if case .finished = completion { return false }
guard !exceededLimit else { return false }
exceededLimit = response.expectedContentLength > limit
if exceededLimit { return false }
self.response = response
return true
}
lock.withLock { self.response = response }
completionHandler(.allow)
completionHandler(allow ? .allow : .cancel)
}

func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
let tooLong = lock.withLock { () -> Bool in
if case .finished = completion { return false }
guard !exceededLimit else { return false }
if data.count > limit - body.count {
exceededLimit = true
return true
}
body.append(data)
return body.count > limit
return false
}
guard tooLong else { return }
finish(.failure(URLError(.dataLengthExceedsMaximum)))
dataTask.cancel()
if tooLong { dataTask.cancel() }
}

func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse,
Expand All @@ -73,12 +92,24 @@ final class BoundedResponse: NSObject, URLSessionDataDelegate, @unchecked Sendab
}

func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: (any Error)?) {
if let error {
finish(.failure(error))
return
let delivery = lock.withLock { () -> (CheckedContinuation<Output, any Error>, Result<Output, any Error>)? in
if case .finished = completion { return nil }
let result: Result<Output, any Error>
if exceededLimit { result = .failure(URLError(.dataLengthExceedsMaximum)) }
else if let error { result = .failure(error) }
else if let response { result = .success((body, response)) }
else { result = .failure(URLError(.badServerResponse)) }

// Cancellation can complete before the caller installs its waiter.
// Keep the result and wait for this callback even on size rejection,
// so callers don't free a network slot while the task is cancelling.
let previous = completion
completion = .finished(result)
body = Data()
response = nil
if case .waiting(let waiter) = previous { return (waiter, result) }
return nil
}
let (body, response) = lock.withLock { (self.body, self.response) }
guard let response else { finish(.failure(URLError(.badServerResponse))); return }
finish(.success((body, response)))
if let (waiter, result) = delivery { waiter.resume(with: result) }
}
}
Loading
Loading