Skip to content

Only crash in debug mode, if HTTPClient was not shutdown #478

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 17, 2021
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
20 changes: 17 additions & 3 deletions Sources/AsyncHTTPClient/HTTPClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ public class HTTPClient {
let eventLoopGroupProvider: EventLoopGroupProvider
let configuration: Configuration
let poolManager: HTTPConnectionPool.Manager
var state: State
private var state: State
private let stateLock = Lock()

internal static let loggingDisabled = Logger(label: "AHC-do-not-log", factory: { _ in SwiftLogNoOpLogHandler() })
Expand Down Expand Up @@ -118,8 +118,22 @@ public class HTTPClient {
}

deinit {
guard case .shutDown = self.state else {
preconditionFailure("Client not shut down before the deinit. Please call client.syncShutdown() when no longer needed.")
debugOnly {
// We want to crash only in debug mode.
switch self.state {
case .shutDown:
break
case .shuttingDown:
preconditionFailure("""
This state should be totally unreachable. While the HTTPClient is shutting down a \
reference cycle should exist, that prevents it from deinit.
""")
case .upAndRunning:
preconditionFailure("""
Client not shut down before the deinit. Please call client.syncShutdown() when no \
longer needed. Otherwise memory will leak.
""")
}
}
}

Expand Down
10 changes: 10 additions & 0 deletions Sources/AsyncHTTPClient/Utils.swift
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,13 @@ public final class HTTPClientCopyingDelegate: HTTPClientResponseDelegate {
return ()
}
}

/// A utility function that runs the body code only in debug builds, without
/// emitting compiler warnings.
///
/// This is currently the only way to do this in Swift: see
/// https://forums.swift.org/t/support-debug-only-code/11037 for a discussion.
@inlinable
internal func debugOnly(_ body: () -> Void) {
assert({ body(); return true }())
}