Skip to content

Commit

Permalink
refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
chrismwendt committed Mar 13, 2023
1 parent 6412088 commit ebfa0a6
Showing 1 changed file with 13 additions and 9 deletions.
22 changes: 13 additions & 9 deletions src/Network/WebSockets/Server.hs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ module Network.WebSockets.Server


--------------------------------------------------------------------------------
import Control.Concurrent (MVar, takeMVar, tryPutMVar,
import Control.Concurrent (takeMVar, tryPutMVar,
newEmptyMVar)
import qualified Control.Concurrent.Async as Async
import Control.Exception (Exception, bracket,
Expand Down Expand Up @@ -121,19 +121,23 @@ runServerWithOptions opts app = S.withSocketsDo $
-- whenever a pong is received.
connOpts' = connOpts
{ connectionOnPong = do
tryPutMVar heartbeat ()
_ <- tryPutMVar heartbeat ()
connectionOnPong connOpts
}

-- Kills the thread if a pong was not received within
-- the grace period.
reaper grace appAsync = do
result <- timeout (grace * 1000000) (takeMVar heartbeat)
whileJust io = do
result <- io
case result of
Nothing -> appAsync `Async.cancelWith` PongTimeout
Just _ -> reaper grace appAsync
Nothing -> return ()
Just _ -> whileJust io

runApp conn connOpts' app `Async.withAsync` reaper grace
-- Runs until a pong was not received within the grace
-- period.
heart = whileJust $ timeout (grace * 1000000) (takeMVar heartbeat)

Async.withAsync
(runApp conn connOpts' app)
(\a -> heart `finally` (a `Async.cancelWith` PongTimeout))

mainThread = do
(conn, _) <- S.accept sock
Expand Down

0 comments on commit ebfa0a6

Please sign in to comment.