@@ -29,10 +29,12 @@ import Control.Concurrent (forkIOWithUnmask, killThread, ThreadId, threadDelay
2929 , mkWeakThreadId )
3030import Control.Concurrent.STM.TQueue (TQueue , writeTQueue , newTQueueIO )
3131import Control.Concurrent.STM (atomically )
32- import Control.Exception (SomeException , bracketOnError , catch , mask_ )
32+ import Control.Exception (SomeException , bracketOnError , catch , mask_ ,
33+ catch , throwIO )
3334import GHC.Conc (labelThread )
3435import Crypto.Hash (hash , Digest , MD5 )
3536import System.Mem.Weak (Weak , deRefWeak )
37+ import System.Socket (eBadFileDescriptor )
3638import qualified Data.HashMap.Strict as HM
3739import qualified Data.ByteString as B
3840import qualified Data.ByteString.Char8 as BS (pack , unpack )
@@ -131,7 +133,6 @@ sendMessage rawConn msg = void $
131133sendEncode :: AbsConnection c -> Encode -> IO ()
132134sendEncode conn = void . rSend (connRawConnection conn) . runEncode
133135
134-
135136connectWith
136137 :: ConnectionSettings
137138 -> (RawConnection -> ConnectionParameters -> IO (AbsConnection c ))
@@ -251,18 +252,19 @@ parseParameters action str = Right <$> do
251252handshakeTls :: RawConnection -> IO ()
252253handshakeTls _ = pure ()
253254
254- -- | Public
255- -- TODO add termination
255+ -- | Closes connection. Does not throw exceptions when socket is closed.
256256close :: AbsConnection c -> IO ()
257257close conn = do
258258 maybe (pure () ) killThread =<< deRefWeak (connReceiverThread conn)
259+ sendMessage (connRawConnection conn) Terminate `catch` handlerEx
259260 rClose $ connRawConnection conn
261+ where
262+ handlerEx e | e == eBadFileDescriptor = pure ()
263+ | otherwise = throwIO e
260264
261265-- | Any exception prevents thread from future work.
262266receiverThread :: RawConnection -> InDataChan -> IO ()
263267receiverThread rawConn dataChan = loopExtractDataRows
264- -- TODO
265- -- dont append strings. Allocate buffer manually and use unsafeReceive
266268 (\ bs -> rReceive rawConn bs 4096 )
267269 (writeChan dataChan . Right )
268270
@@ -279,8 +281,6 @@ receiverThreadCommon rawConn chan msgFilter ntfHandler = go ""
279281 (rest, msg) <- decodeNextServerMessage bs readMoreAction
280282 handler msg >> go rest
281283
282- -- TODO
283- -- dont append strings. Allocate buffer manually and use unsafeReceive
284284 readMoreAction = (\ bs -> rReceive rawConn bs 4096 )
285285 handler msg = do
286286 dispatchIfNotification msg ntfHandler
0 commit comments