@@ -271,7 +271,26 @@ fork set mkConn addr app counter ii0 = settingsFork set $ \ unmask ->
271271 -- Allocate a new IORef indicating whether the connection has been
272272 -- closed, to avoid double-freeing a connection
273273 withClosedRef $ \ref ->
274−
274+ let cleanUp (conn, _) = closeConn ref conn `finally` connFree conn
275+ serve (conn, transport) =
276+ -- We need to register a timeout handler for this thread, and
277+ -- cancel that handler as soon as we exit. We additionally close
278+ -- the connection immediately in case the child thread catches the
279+ -- async exception or performs some long-running cleanup action.
280+ bracket (T.registerKillThread (timeoutManager0 ii0) (closeConn ref conn))
281+ T.cancel $ \th ->
282+ let ii1 = toInternalInfo1 ii0 th
283+ -- We now have fully registered a connection close handler
284+ -- in the case of all exceptions, so it is safe to one
285+ -- again allow async exceptions.
286+ in unmask .
287+
288+ -- Call the user-supplied code for connection open and close events
289+ bracket (onOpen addr) (onClose addr) $ \goingon ->
290+
291+ -- Actually serve this connection.
292+ -- bracket with closeConn above ensures the connection is closed.
293+ when goingon $ serveConnection conn ii1 addr transport set app
275294 -- Run the connection maker to get a new connection, and ensure
276295 -- that the connection is closed. If the mkConn call throws an
277296 -- exception, we will leak the connection. If the mkConn call is
@@ -282,26 +301,7 @@ fork set mkConn addr app counter ii0 = settingsFork set $ \ unmask ->
282301 -- We grab the connection before registering timeouts since the
283302 -- timeouts will be useless during connection creation, due to the
284303 -- fact that async exceptions are still masked.
285− bracket mkConn (\(conn, _) -> closeConn ref conn `finally` connFree conn)
286− $ \(conn, transport) ->
287−
288− -- We need to register a timeout handler for this thread, and
289− -- cancel that handler as soon as we exit. We additionally close
290− -- the connection immediately in case the child thread catches the
291− -- async exception or performs some long-running cleanup action.
292− bracket (T.registerKillThread (timeoutManager0 ii0) (closeConn ref conn)) T.cancel $ \th ->
293−
294− let ii1 = toInternalInfo1 ii0 th
295− -- We now have fully registered a connection close handler
296− -- in the case of all exceptions, so it is safe to one
297− -- again allow async exceptions.
298− in unmask .
299− -- Call the user-supplied code for connection open and close events
300− bracket (onOpen addr) (onClose addr) $ \goingon ->
301−
302− -- Actually serve this connection.
303− -- bracket with closeConn above ensures the connection is closed.
304− when goingon $ serveConnection conn ii1 addr transport set app
304+ in bracket mkConn cleanUp serve
305305 where
306306 withClosedRef inner = newIORef False >>= inner
307307