Skip to content

Commit ec2e080

Browse files
authored
Only crash in debug mode, if HTTPClient was not shutdown (#478)
### Motivation Generally we want to inform users that they need to shutdown their HTTPClient. Until `1.6.0` we did this with an assert in HTTPClient's deinit. With `1.6.0` this behavior was raised to a precondition. Because of this adopters might suddenly crash in production where they didn't before. ### Changes - This pr reverts the current behavior back to something pre `1.6.0` ### Result - HTTPClient doesn't crash in production anymore.
1 parent ce01ff2 commit ec2e080

File tree

2 files changed

+27
-3
lines changed

2 files changed

+27
-3
lines changed

Sources/AsyncHTTPClient/HTTPClient.swift

+17-3
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ public class HTTPClient {
6868
let eventLoopGroupProvider: EventLoopGroupProvider
6969
let configuration: Configuration
7070
let poolManager: HTTPConnectionPool.Manager
71-
var state: State
71+
private var state: State
7272
private let stateLock = Lock()
7373

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

120120
deinit {
121-
guard case .shutDown = self.state else {
122-
preconditionFailure("Client not shut down before the deinit. Please call client.syncShutdown() when no longer needed.")
121+
debugOnly {
122+
// We want to crash only in debug mode.
123+
switch self.state {
124+
case .shutDown:
125+
break
126+
case .shuttingDown:
127+
preconditionFailure("""
128+
This state should be totally unreachable. While the HTTPClient is shutting down a \
129+
reference cycle should exist, that prevents it from deinit.
130+
""")
131+
case .upAndRunning:
132+
preconditionFailure("""
133+
Client not shut down before the deinit. Please call client.syncShutdown() when no \
134+
longer needed. Otherwise memory will leak.
135+
""")
136+
}
123137
}
124138
}
125139

Sources/AsyncHTTPClient/Utils.swift

+10
Original file line numberDiff line numberDiff line change
@@ -32,3 +32,13 @@ public final class HTTPClientCopyingDelegate: HTTPClientResponseDelegate {
3232
return ()
3333
}
3434
}
35+
36+
/// A utility function that runs the body code only in debug builds, without
37+
/// emitting compiler warnings.
38+
///
39+
/// This is currently the only way to do this in Swift: see
40+
/// https://forums.swift.org/t/support-debug-only-code/11037 for a discussion.
41+
@inlinable
42+
internal func debugOnly(_ body: () -> Void) {
43+
assert({ body(); return true }())
44+
}

0 commit comments

Comments
 (0)