on master help sign in
Basic EventSource prototype working
commitb86031143db6e0d5873afb3e5b3cd254085ae7d0 authorMathias Biilmann Christensen <info@mathias-biilmann.net> dateThu 6 Oct 2011, 01:25 (15 years ago) parent334c9ed
3 files changed+31−82
src/AMQPListener.hs−80 src/Main.hs+12−2 static/index.html+19
src/AMQPListener.hsdeleted−80
@@ -1,80 +0,0 @@
1−{-# LANGUAGE OverloadedStrings #-}
2−module AMQPListener
3− (
4− AMQPEvent(..)
5− , openEventChannel
6− ) where
7−
8−import Control.Applicative((<$>), (<*>))
9−import Control.Monad(mzero)
10−import Control.Monad.Fix(fix)
11−import Control.Concurrent(forkIO)
12−import Control.Concurrent.Chan(Chan, newChan, readChan, writeChan)
13−
14−import Data.Aeson(FromJSON(..), Value(..), Result(..), fromJSON, json, (.:), (.:?))
15−import Data.Attoparsec(parse, maybeResult)
16−
17−import qualified Data.ByteString as B
18−import qualified Data.ByteString.Lazy as LB
19−
20−import Data.Maybe(fromJust, fromMaybe)
21−import Data.String.Utils(split)
22−
23−import Text.URI(URI(..), parseURI)
24−import System.Posix.Env(getEnvDefault)
25−import Network.AMQP
26−
27−-- |The AMQPEvent represents and incomming message that should be
28−-- mapped to an EventSource event.
29−data AMQPEvent = AMQPEvent
30− { amqpChannel :: B.ByteString
31− , amqpData :: B.ByteString
32− , amqpId :: Maybe B.ByteString
33− , amqpName :: Maybe B.ByteString
34− }
35−
36−instance FromJSON AMQPEvent where
37− parseJSON (Object v) = AMQPEvent <$>
38− v .: "channel" <*>
39− v .: "data" <*>
40− v .:? "id" <*>
41− v .:? "name"
42− parseJSON _ = mzero
43−
44−-- |Connects to an AMQP broker.
45−-- Tries to get credentials, host and vhost from the AMQP_URL
46−-- environment variable
47−-- Take an exchange name and a queue name
48−openEventChannel :: String -> String -> IO (Chan AMQPEvent)
49−openEventChannel exchange queue = do
50− amqpURI <- getEnvDefault "AMQP_URL" "amqp://guest:guest@127.0.0.1/"
51−
52− let uri = fromJust $ parseURI amqpURI
53− let auth = fromMaybe "guest:guest" $ uriUserInfo uri
54− let host = fromMaybe "127.0.0.1" $ uriRegName uri
55− let vhost = uriPath uri
56−
57− let [user,password] = split ":" auth
58−
59− conn <- openConnection host vhost user password
60− chan <- openChannel conn
61−
62− declareQueue chan newQueue {queueName = queue, queueAutoDelete = True, queueDurable = False}
63− declareExchange chan newExchange {exchangeName = exchange, exchangeType = "fanout", exchangeDurable = False}
64− bindQueue chan queue exchange queue
65−
66− listener <- newChan
67− forkIO $ fix $ \loop -> readChan listener >> loop
68− consumeMsgs chan queue NoAck (sendTo listener)
69− return listener
70−
71−-- |Write messages from AMQP to a channel
72−sendTo :: Chan AMQPEvent -> (Message, Envelope) -> IO ()
73−sendTo chan (msg, _) =
74− case maybeResult $ parse json (B.concat $ LB.toChunks (msgBody msg)) of
75− Just value -> case fromJSON value of
76− Success event -> do
77− writeChan chan event
78− Error _ -> do
79− return ()
80− Nothing -> return ()
src/Main.hs+12−2
@@ -1,5 +1,4 @@
11{-# LANGUAGE OverloadedStrings #-}
2−
32module Main where
43
54import Control.Monad
@@ -11,7 +10,9 @@ import Network.Wai
1110import Network.HTTP.Types (statusOK)
1211import Data.Enumerator (Iteratee, Step(Continue), Stream(Chunks,EOF), returnI, run_, (>>==), ($$), generateM)
1312import Data.Time.Clock.POSIX
13+import Data.ByteString (ByteString)
1414import qualified Data.ByteString as B
15+import Blaze.ByteString.Builder (fromByteString)
1516import Blaze.ByteString.Builder.Char.Utf8 (fromString)
1617
1718
@@ -19,23 +20,32 @@ import EventStream
1920
2021
2122app :: Chan ServerEvent -> Application
22−app chan = return $ res chan
23+app chan req =
24+ case pathInfo req of
25+ [] -> return $ ResponseFile statusOK [("Content-Type", "text/html")] "static/index.html" Nothing
26+ ["es"] -> do
27+ chan' <- liftIO $ dupChan chan
28+ return $ res chan'
29+
2330
2431res :: Chan ServerEvent -> Response
2532res chan = ResponseEnumerator (resE chan)
2633
34+
2735source :: Chan ServerEvent -> IO ()
2836source chan = forever $ do
2937 threadDelay 1000000
3038 time <- getPOSIXTime
3139 writeChan chan (ServerEvent Nothing Nothing [fromString . show $ time])
3240
41+
3342resE :: Chan ServerEvent -> ResponseEnumerator a
3443resE chan genIter =
3544 run_ $ generateM (fmap eventToBuilder $ readChan chan) $$ iter
3645 where
3746 iter = genIter statusOK [("Content-Type", "text/event-stream")]
3847
48+
3949main :: IO ()
4050main = do
4151 chan <- newChan
static/index.htmlnew file+19
@@ -0,0 +1,19 @@
1+<!doctype html>
2+<head>
3+ <title>Hello</title>
4+</head>
5+<h1>Testing</h1>
6+
7+<div id="output"></div>
8+
9+<script>
10+ var output = document.getElementById("output");
11+
12+ var src = new EventSource("/es");
13+
14+ src.onmessage = function(msg) {
15+ var p = document.createElement("p");
16+ p.appendChild(document.createTextNode(msg.data));
17+ output.appendChild(p);
18+ }
19+</script>