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
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,20 @@ import Foundation

nonisolated struct WorktreesAPIClient: WorktreeRemote, Sendable {
private let connectionProvider: @Sendable () -> ServerConnection?
private let urlSession: URLSession
private let resolveURLSession: @Sendable () -> URLSession
private let decoder = JSONDecoder()
private let encoder = JSONEncoder()

init(
connectionProvider: @escaping @Sendable () -> ServerConnection?,
urlSession: URLSession = OpenCodeURLSessions.rest
urlSession: URLSession? = nil
) {
self.connectionProvider = connectionProvider
self.urlSession = urlSession
self.resolveURLSession = OpenCodeURLSessions.restResolver(injected: urlSession)
}

func resolvedURLSession() -> URLSession {
resolveURLSession()
}

func listV2(projectID: String) async throws -> [String] {
Expand Down Expand Up @@ -40,7 +44,7 @@ nonisolated struct WorktreesAPIClient: WorktreeRemote, Sendable {
guard let connection = connectionProvider() else { return .failed(-1) }
let request = connection.authorizedRequest(path: "experimental/workspace", directory: directory)
do {
let (data, response) = try await urlSession.data(for: request)
let (data, response) = try await resolveURLSession().data(for: request)
guard let http = response as? HTTPURLResponse else { return .failed(-1) }
if http.statusCode == 404 { return .notFound }
guard (200 ..< 300).contains(http.statusCode) else { return .failed(http.statusCode) }
Expand All @@ -51,7 +55,7 @@ nonisolated struct WorktreesAPIClient: WorktreeRemote, Sendable {
}

private func data(for request: URLRequest) async throws -> Data {
let (data, response) = try await urlSession.data(for: request)
let (data, response) = try await resolveURLSession().data(for: request)
guard let http = response as? HTTPURLResponse else { throw WorktreesAPIError.invalidResponse }
guard (200 ..< 300).contains(http.statusCode) else {
throw WorktreesAPIError.httpStatus(http.statusCode)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,17 @@ enum OpenCodeURLSessions {
let previous = restSession
restSession = replacement
lock.unlock()
previous.invalidateAndCancel()
// A caller may have read `previous` but not yet created its task, and creating a task on an
// invalidated session raises an uncatchable NSGenericException (#777). Cancel in-flight work
// now; invalidate once such stragglers have had time to start.
previous.getAllTasks { tasks in tasks.forEach { $0.cancel() } }
DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + invalidationGracePeriod) {
previous.invalidateAndCancel()
}
}

private static let invalidationGracePeriod: TimeInterval = 5

/// Nil means the live pool. An injected session stays fixed for tests and the connection probe.
static func restResolver(injected: URLSession?) -> @Sendable () -> URLSession {
if let injected {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,40 @@ struct OpenCodeURLSessionsTests {
assertRestTimeouts(OpenCodeURLSessions.rest)
}

@Test func replaceRestMovesTheLiveWorktreesClientToTheNewPool() {
let original = OpenCodeURLSessions.rest
let explicit = URLSession(configuration: .ephemeral)
let live = WorktreesAPIClient(connectionProvider: { nil })
let fixed = WorktreesAPIClient(connectionProvider: { nil }, urlSession: explicit)
#expect(live.resolvedURLSession() === original)
#expect(fixed.resolvedURLSession() === explicit)

OpenCodeURLSessions.replaceRest()
let replaced = OpenCodeURLSessions.rest
defer {
if OpenCodeURLSessions.rest !== original {
OpenCodeURLSessions.replaceRest()
}
}

#expect(replaced !== original)
#expect(live.resolvedURLSession() === replaced)
#expect(fixed.resolvedURLSession() === explicit)
}

@Test func replaceRestLeavesThePreviousPoolUsableForAStragglerTask() throws {
let original = OpenCodeURLSessions.rest
OpenCodeURLSessions.replaceRest()
defer { OpenCodeURLSessions.replaceRest() }

// A caller that read `original` just before the swap still creates its task. An immediate
// invalidation would raise NSGenericException here and crash the test process (#777).
let url = try #require(URL(string: "http://127.0.0.1:9/"))
let task = original.dataTask(with: url)
task.cancel()
#expect(OpenCodeURLSessions.rest !== original)
}

private func assertRestTimeouts(_ session: URLSession) {
let configuration = session.configuration
#expect(configuration.timeoutIntervalForRequest == 15)
Expand Down