mirror of
https://github.com/apple/swift-nio
synced 2026-11-29 05:24:21 +00:00
retain Channel from ChannelPipeline until destroyed (#415)
Motivation: A long time ago, `ChannelPipeline.channel` was public and needed to be thread-safe. That meant we could never mutate `ChannelPipeline.channel`. Instead we stored it as an unowned reference that we only read when the `Channel` was still alive. It was the right call making `ChannelPipeline.channel` internal but we forgot to then remove the `unowned` reference from `ChannelPipeline` to `Channel`. This patch makes this reference strong but nils it out whenever the `ChannelPipeline` is destroyed. That makes everything easier because there is no danger anymore that the `Channel` gets deallocated when the `ChannelPipeline` is still alive. After destroying the `ChannelPipeline` we will still hand out a `DeadChannel` if you call `ctx.channel` (as it's a non-optional requirement). This comes with an unfortunate drawback: Now if you just leak an open Channel (which you shouldn't be able to when using the Bootstraps) we can no longer detect that as the Channel and the ChannelPipeline will have a retain cycle. Unfortunately I don't think there's a good way to safely assert that. Modifications: - made `ChannelPipeline` hold a strong reference to `Channel` until the `ChannelPipeline` is destroyed Result: - don't crash if the user only retains the ChannelPipeline but not the Channel
This commit is contained in:
1 parent
6e73790951
commit
f2343bfd95
1 file changed
+6
-4
@@ -145,13 +145,14 @@ public final class ChannelPipeline: ChannelInvoker {
|
||||
|
||||
/// The `Channel` that this `ChannelPipeline` belongs to.
|
||||
///
|
||||
/// - warning: This is unsafe as it's only valid if the `Channel` is still open
|
||||
private unowned let _channel: Channel
|
||||
/// - note: This will be nil after the channel has closed
|
||||
private var _channel: Channel?
|
||||
|
||||
/// The `Channel` that this `ChannelPipeline` belongs to.
|
||||
internal var channel: Channel {
|
||||
assert(self.eventLoop.inEventLoop)
|
||||
return !self.destroyed ? self._channel : DeadChannel(pipeline: self)
|
||||
assert(self._channel != nil || self.destroyed)
|
||||
return self._channel ?? DeadChannel(pipeline: self)
|
||||
}
|
||||
|
||||
/// Add a `ChannelHandler` to the `ChannelPipeline`.
|
||||
@@ -515,7 +516,8 @@ public final class ChannelPipeline: ChannelInvoker {
|
||||
self.head = nil
|
||||
self.tail = nil
|
||||
|
||||
destroyed = true
|
||||
self.destroyed = true
|
||||
self._channel = nil
|
||||
}
|
||||
|
||||
// Just delegate to the head and tail context
|
||||
|
||||
Reference in new issue
Block a user