From f2343bfd9596a5ca89b2fbe98b74a3c2a3e335f5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Johannes=20Wei=C3=9F?= Date: Tue, 22 May 2018 10:01:00 +0100 Subject: [PATCH] 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 --- Sources/NIO/ChannelPipeline.swift | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/Sources/NIO/ChannelPipeline.swift b/Sources/NIO/ChannelPipeline.swift index 20bac1e88..b22bfd5ae 100644 --- a/Sources/NIO/ChannelPipeline.swift +++ b/Sources/NIO/ChannelPipeline.swift @@ -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