| 1 |
module Network.WebSockets.Connection.PingPong |
| 2 |
( withPingPong |
| 3 |
, PingPongOptions(..) |
| 4 |
, PongTimeout(..) |
| 5 |
, defaultPingPongOptions |
| 6 |
) where |
| 7 |
|
| 8 |
import Control.Concurrent.Async as Async |
| 9 |
import Control.Exception |
| 10 |
import Control.Monad (void) |
| 11 |
import Network.WebSockets.Connection (Connection, connectionHeartbeat, pingThread) |
| 12 |
import Control.Concurrent.MVar (takeMVar) |
| 13 |
import System.Timeout (timeout) |
| 14 |
|
| 15 |
|
| 16 |
-- | Exception type used to kill connections if there |
| 17 |
-- is a pong timeout. |
| 18 |
data PongTimeout = PongTimeout deriving Show |
| 19 |
|
| 20 |
instance Exception PongTimeout |
| 21 |
|
| 22 |
|
| 23 |
-- | Options for ping-pong |
| 24 |
-- |
| 25 |
-- Make sure that the ping interval is less than the pong timeout, |
| 26 |
-- for example N/2. |
| 27 |
data PingPongOptions = PingPongOptions { |
| 28 |
pingInterval :: Int, -- ^ Interval in seconds |
| 29 |
pongTimeout :: Int, -- ^ Timeout in seconds |
| 30 |
pingAction :: IO () -- ^ Action to perform after sending a ping |
| 31 |
} |
| 32 |
|
| 33 |
-- | Default options for ping-pong |
| 34 |
-- |
| 35 |
-- Ping every 15 seconds, timeout after 30 seconds |
| 36 |
defaultPingPongOptions :: PingPongOptions |
| 37 |
defaultPingPongOptions = PingPongOptions { |
| 38 |
pingInterval = 15, |
| 39 |
pongTimeout = 30, |
| 40 |
pingAction = return () |
| 41 |
} |
| 42 |
|
| 43 |
-- | Run an application with ping-pong enabled. Raises PongTimeout if a pong is not received. |
| 44 |
-- |
| 45 |
-- Can used with Client and Server connections. |
| 46 |
withPingPong :: PingPongOptions -> Connection -> (Connection -> IO ()) -> IO () |
| 47 |
withPingPong options connection app = void $ |
| 48 |
withAsync (app connection) $ \appAsync -> do |
| 49 |
withAsync (pingThread connection (pingInterval options) (pingAction options)) $ \pingAsync -> do |
| 50 |
withAsync (heartbeat >> throwIO PongTimeout) $ \heartbeatAsync -> do |
| 51 |
waitAnyCancel [appAsync, pingAsync, heartbeatAsync] |
| 52 |
where |
| 53 |
heartbeat = whileJust $ timeout (pongTimeout options * 1000 * 1000) |
| 54 |
$ takeMVar (connectionHeartbeat connection) |
| 55 |
|
| 56 |
-- Loop until action returns Nothing |
| 57 |
whileJust :: IO (Maybe a) -> IO () |
| 58 |
whileJust action = do |
| 59 |
result <- action |
| 60 |
case result of |
| 61 |
Nothing -> return () |
| 62 |
Just _ -> whileJust action |