Skip to content

Commit

Permalink
Only crash in debug mode, if HTTPClient was not shutdown (#478)
Browse files Browse the repository at this point in the history
### 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.
  • Loading branch information
fabianfett authored Nov 17, 2021
1 parent ce01ff2 commit ec2e080
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
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 }())
}

0 comments on commit ec2e080

Please sign in to comment.