You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

100 lines
4.1 KiB

{-# OPTIONS_HADDOCK hide #-}
{-# LANGUAGE OverloadedStrings #-}
module Network.Xmpp.Concurrent.Monad where
14 years ago
import Network.Xmpp.Types
14 years ago
import Control.Concurrent.STM
import qualified Control.Exception.Lifted as Ex
import Control.Monad.Reader
14 years ago
import Network.Xmpp.Concurrent.Types
import Network.Xmpp.Stream
14 years ago
14 years ago
-- TODO: Wait for presence error?
-- -- | Run an XmppConMonad action in isolation. Reader and writer workers will be
-- -- temporarily stopped and resumed with the new session details once the action
-- -- returns. The action will run in the calling thread. Any uncaught exceptions
-- -- will be interpreted as connection failure.
-- withConnection :: XmppConMonad a -> Context -> IO (Either StreamError a)
-- withConnection a session = do
-- wait <- newEmptyTMVarIO
-- Ex.mask_ $ do
-- -- Suspends the reader until the lock (wait) is released (set to `()').
-- throwTo (readerThread session) $ Interrupt wait
-- -- We acquire the write and stateRef locks, to make sure that this is
-- -- the only thread that can write to the stream and to perform a
-- -- withConnection calculation. Afterwards, we release the lock and
-- -- fetches an updated state.
-- s <- Ex.catch
-- (atomically $ do
-- _ <- takeTMVar (writeRef session)
-- s <- takeTMVar (conStateRef session)
-- putTMVar wait ()
-- return s
-- )
-- -- If we catch an exception, we have failed to take the MVars above.
-- (\e -> atomically (putTMVar wait ()) >>
-- Ex.throwIO (e :: Ex.SomeException)
-- )
-- -- Run the XmppMonad action, save the (possibly updated) states, release
-- -- the locks, and return the result.
-- Ex.catches
-- (do
-- (res, s') <- runStateT a s
-- atomically $ do
-- putTMVar (writeRef session) (cSend . sCon $ s')
-- putTMVar (conStateRef session) s'
-- return $ Right res
-- )
-- -- We treat all Exceptions as fatal. If we catch a StreamError, we
-- -- return it. Otherwise, we throw an exception.
-- [ Ex.Handler $ \e -> return $ Left (e :: StreamError)
-- , Ex.Handler $ \e -> runStateT xmppKillConnection s
-- >> Ex.throwIO (e :: Ex.SomeException)
-- ]
-- | Executes a function to update the event handlers.
modifyHandlers :: (EventHandlers -> EventHandlers) -> Session -> IO ()
modifyHandlers f session = atomically $ modifyTVar_ (eventHandlers session) f
where
-- Borrowing modifyTVar from
-- http://hackage.haskell.org/packages/archive/stm/2.4/doc/html/src/Control-Concurrent-STM-TVar.html
-- as it's not available in GHC 7.0.
modifyTVar_ :: TVar a -> (a -> a) -> STM ()
modifyTVar_ var g = do
x <- readTVar var
writeTVar var (g x)
-- | Sets the handler to be executed when the server connection is closed.
Tweak failure approach I'm assuming and defining the following: 1. XMPP failures (which can occur at the TCP, TLS, and XML/XMPP layers (as a stream error or forbidden input)) are fatal; they will distrupt the XMPP session. 2. All fatal failures should be thrown (or similar) by `session', or any other function that might produce them. 3. Authentication failures that are not "XMPP failures" are not fatal. They do not necessarily terminate the stream. For example, the developer should be able to make another authentication attempt. The `Session' object returned by `session' might be useful even if the authentication fails. 4. We can (and should) use one single data type for fatal failures. (Previously, both StreamFailure and TlsFailure was used.) 5. We can catch and rethrow/wrap IO exceptions in the context of the Pontarius XMPP error system that we decide to use, making the error system more intuitive, Haskell-like, and more straight-forward to implement. Calling `error' may only be done in the case of a program error (a bug). 6. A logging system will remove the need for many of the error types. Only exceptions that seem likely to affect the flow of client applications should be defined. 7. The authentication functions are prone to fatal XMPP failures in addition to non-fatal authentication conditions. (Previously, `AuthStreamFailure' was used to wrap these errors.) I'm hereby suggesting (and implementing) the following: `StreamFailure' and `TlsFailure' should be joined into `XmppFailure'. `pullStanza' and the other Connection functions used to throw `IOException', `StreamFailure' and `TlsFailure' exceptions. With this patch, they have been converted to `StateT Connection IO (Either XmppFailure a)' computations. They also catch (some) IOException errors and wrap them in the new `XmppIOException' constructor. `newSession' is now `IO (Either XmppFailure Session)' as well (being capable of throwing IO exceptions). Whether or not to continue to a) wrap `XmppFailure' failures in an `AuthStreamFailure' equivalent, or, b) treat the authentication functions just like the other functions that may result in failure (Either XmppFailure a), depends on how Network.Xmpp.Connection.auth will be used. Since the latter will make `auth' more consistent, as well as remove the need for a wrapped (and special-case) "AuthFailure" type, I have decided to give the "b" approach a try. (The drawback being, of course, that authentication errors can not be accessed through the use of ErrorT. Whether or not this might be a problem, I don't really know at this point.) As the SASL code (and SaslM) depended on `AuthStreamFailure', it remains for internal use, at least for the time-being. `session' is now an ErrorT computation as well. Some functions have been updated as hacks, but this will be changed if we decide to move forward with this approach.
13 years ago
setConnectionClosedHandler_ :: (XmppFailure -> Session -> IO ()) -> Session -> IO ()
setConnectionClosedHandler_ eh session = do
modifyHandlers (\s -> s{connectionClosedHandler =
\e -> eh e session}) session
-- | Run an event handler.
runHandler :: (EventHandlers -> IO a) -> Session -> IO a
runHandler h session = h =<< atomically (readTVar $ eventHandlers session)
-- | End the current Xmpp session.
endContext :: Session -> IO ()
endContext session = do -- TODO: This has to be idempotent (is it?)
closeConnection session
stopThreads session
-- | Close the connection to the server. Closes the stream (by enforcing a
-- write lock and sending a </stream:stream> element), waits (blocks) for three
-- seconds, and then closes the connection.
closeConnection :: Session -> IO ()
closeConnection session = Ex.mask_ $ do
(_send, connection) <- atomically $ liftM2 (,)
(takeTMVar $ writeRef session)
(takeTMVar $ streamRef session)
_ <- closeStreams connection
return ()