@@ -20,9 +20,12 @@ module Language.Javascript.JSaddle.WebSockets (
20 , jsaddleApp
20 , jsaddleApp
21 , jsaddleWithAppOr
21 , jsaddleWithAppOr
22 , jsaddleAppWithJs
22 , jsaddleAppWithJs
23 , jsaddleAppPartial
24 , jsaddleAppPartial
24 , jsaddleJs
25 , jsaddleJs
26 , debugWrapper
29 , debugWrapper
@@ -57,45 +60,57 @@ import qualified Data.Map as M (empty, insert, lookup)
57import Data.IORef
60import Data.IORef
58 (readIORef, newIORef, atomicModifyIORef')
61 (readIORef, newIORef, atomicModifyIORef')
59import Data.ByteString.Lazy (ByteString)
62import Data.ByteString.Lazy (ByteString)
60−import qualified Data.ByteString.Lazy as LBS (stripPrefix)
63+import qualified Data.ByteString.Lazy as LBS
64+ (toStrict, stripPrefix)
61import Control.Concurrent.MVar
65import Control.Concurrent.MVar
62 (tryTakeMVar, MVar, tryPutMVar, modifyMVar_, putMVar, takeMVar,
66 (tryTakeMVar, MVar, tryPutMVar, modifyMVar_, putMVar, takeMVar,
63 readMVar, newMVar, newEmptyMVar, modifyMVar)
67 readMVar, newMVar, newEmptyMVar, modifyMVar)
64import Network.Wai.Handler.Warp
68import Network.Wai.Handler.Warp
65 (defaultSettings, setTimeout, setPort, runSettings)
69 (defaultSettings, setTimeout, setPort, runSettings)
66−import Foreign.Store (newStore, readStore, lookupStore)
70+import Foreign.Store (readStore, lookupStore, writeStore, Store(..))
67import Language.Javascript.JSaddle (askJSM)
71import Language.Javascript.JSaddle (askJSM)
68import Control.Monad.IO.Class (MonadIO(..))
72import Control.Monad.IO.Class (MonadIO(..))
70import Language.Javascript.JSaddle.WebSockets.Compat (getTextMessageByteString)
74import Language.Javascript.JSaddle.WebSockets.Compat (getTextMessageByteString)
75+import qualified Data.Text.Encoding as T (decodeUtf8)
72jsaddleOr :: ConnectionOptions -> JSM () -> Application -> IO Application
77jsaddleOr :: ConnectionOptions -> JSM () -> Application -> IO Application
73jsaddleOr opts entryPoint otherApp = do
78jsaddleOr opts entryPoint otherApp = do
74 syncHandlers <- newIORef M.empty
79 syncHandlers <- newIORef M.empty
80+ asyncHandlers <- newIORef M.empty
75 let wsApp :: ServerApp
81 let wsApp :: ServerApp
76 wsApp pending_conn = do
82 wsApp pending_conn = do
77 conn <- acceptRequest pending_conn
83 conn <- acceptRequest pending_conn
84+ initMsg <- receiveDataMessage conn
85+ case getTextMessageByteString initMsg of
78− rec (processResult, processSyncResult, start) <- runJavaScript (sendTextData conn . encode) $ do
87+ rec (processResult, processSyncResult, start) <- runJavaScript (sendTextData conn . encode) $ do
79− syncKey <- T.pack . show . contextId <$> askJSM
88+ syncKey <- T.pack . show . contextId <$> askJSM
80− liftIO $ atomicModifyIORef' syncHandlers (\m -> (M.insert syncKey processSyncResult m, ()))
89+ liftIO $ atomicModifyIORef' syncHandlers (\m -> (M.insert syncKey processSyncResult m, ()))
90+ liftIO $ atomicModifyIORef' asyncHandlers (\m -> (M.insert syncKey processResult m, ()))
81− liftIO $ sendTextData conn (encode syncKey)
91+ liftIO $ sendTextData conn (encode syncKey)
82− entryPoint
92+ entryPoint
83− _ <- forkIO . forever $
93+ start
84− receiveDataMessage conn >>= \msg -> case getTextMessageByteString msg of
94+ waitTillClosed conn
85− Just t ->
95+ Just syncKey ->
96+ M.lookup (T.decodeUtf8 $ LBS.toStrict syncKey) <$> readIORef syncHandlers >>= \case
97+ Nothing -> error "jsaddle missing sync message handler"
98+ Just processResult ->
100+ receiveDataMessage conn >>= \msg -> case getTextMessageByteString msg of
86− case decode t of
102+ case decode t of
87− Nothing -> error $ "jsaddle Results decode failed : " <> show t
103+ Nothing -> error $ "jsaddle Results decode failed : " <> show t
88− Just r -> processResult r
104+ Just r -> processResult r
89− _ -> error "jsaddle WebSocket unexpected binary data"
105+ _ -> error "jsaddle WebSocket unexpected binary data"
90− start
106+ _ -> error "jsaddle WebSocket unexpected binary data"
93 -- Based on Network.WebSocket.forkPingThread
108 -- Based on Network.WebSocket.forkPingThread
94 waitTillClosed conn = ignore `handle` go 1
109 waitTillClosed conn = ignore `handle` go 1
96 go :: Int -> IO ()
111 go :: Int -> IO ()
97 go i = do
112 go i = do
98− threadDelay (1 * 1000 * 1000)
113+ threadDelay (10 * 1000 * 1000)
99 sendPing conn (T.pack $ show i)
114 sendPing conn (T.pack $ show i)
100 go (i + 1)
115 go (i + 1)
@@ -124,13 +139,18 @@ jsaddleOr opts entryPoint otherApp = do
126jsaddleApp :: Application
141jsaddleApp :: Application
127−jsaddleApp = jsaddleAppWithJs $ jsaddleJs Nothing False
142+jsaddleApp = jsaddleAppWithJs $ jsaddleJs False
129jsaddleAppWithJs :: ByteString -> Application
144jsaddleAppWithJs :: ByteString -> Application
130jsaddleAppWithJs js req sendResponse =
145jsaddleAppWithJs js req sendResponse =
131− fromMaybe
146+ jsaddleAppWithJsOr js
132− (sendResponse $ W.responseLBS H.status403 [("Content-Type", "text/plain")] "Forbidden")
147+ (\_ _ -> sendResponse $ W.responseLBS H.status403 [("Content-Type", "text/plain")] "Forbidden")
150+jsaddleAppWithJsOr :: ByteString -> Application -> Application
151+jsaddleAppWithJsOr js otherApp req sendResponse =
152+ fromMaybe (otherApp req sendResponse)
133− (jsaddleAppPartialWithJs js req sendResponse)
153+ (jsaddleAppPartialWithJs js req sendResponse)
135jsaddleWithAppOr :: ConnectionOptions -> JSM () -> Application -> IO Application
155jsaddleWithAppOr :: ConnectionOptions -> JSM () -> Application -> IO Application
136jsaddleWithAppOr opts entryPoint otherApp = jsaddleOr opts entryPoint $ \req sendResponse ->
156jsaddleWithAppOr opts entryPoint otherApp = jsaddleOr opts entryPoint $ \req sendResponse ->
@@ -138,7 +158,7 @@ jsaddleWithAppOr opts entryPoint otherApp = jsaddleOr opts entryPoint $ \req sen
138 (jsaddleAppPartial req sendResponse))
158 (jsaddleAppPartial req sendResponse))
140jsaddleAppPartial :: Request -> (Response -> IO ResponseReceived) -> Maybe (IO ResponseReceived)
160jsaddleAppPartial :: Request -> (Response -> IO ResponseReceived) -> Maybe (IO ResponseReceived)
141−jsaddleAppPartial = jsaddleAppPartialWithJs $ jsaddleJs Nothing False
161+jsaddleAppPartial = jsaddleAppPartialWithJs $ jsaddleJs False
143indexResponse :: Response
163indexResponse :: Response
144indexResponse = W.responseLBS H.status200 [("Content-Type", "text/html")] indexHtml
164indexResponse = W.responseLBS H.status200 [("Content-Type", "text/html")] indexHtml
@@ -149,11 +169,14 @@ jsaddleAppPartialWithJs js req sendResponse = case (W.requestMethod req, W.pathI
149 ("GET", ["jsaddle.js"]) -> Just $ sendResponse $ W.responseLBS H.status200 [("Content-Type", "application/javascript")] js
169 ("GET", ["jsaddle.js"]) -> Just $ sendResponse $ W.responseLBS H.status200 [("Content-Type", "application/javascript")] js
150 _ -> Nothing
170 _ -> Nothing
172+jsaddleJs :: Bool -> ByteString
173+jsaddleJs = jsaddleJs' Nothing
152-- Use this to generate this string for embedding
175-- Use this to generate this string for embedding
153-- sed -e 's|\\|\\\\|g' -e 's|^| \\|' -e 's|$|\\n\\|' -e 's|"|\\"|g' data/jsaddle.js | pbcopy
176-- sed -e 's|\\|\\\\|g' -e 's|^| \\|' -e 's|$|\\n\\|' -e 's|"|\\"|g' data/jsaddle.js | pbcopy
154−jsaddleJs :: Maybe ByteString -> Bool -> ByteString
177+jsaddleJs' :: Maybe ByteString -> Bool -> ByteString
155−jsaddleJs jsaddleUri refreshOnLoad = "\
178+jsaddleJs' jsaddleUri refreshOnLoad = "\
156− \if(typeof global !== \"undefined\") {\n\
179+ \if(typeof global !== \"undefined\" && typeof require === \"function\") {\n\
157 \ global.window = global;\n\
180 \ global.window = global;\n\
158 \ global.WebSocket = require('ws');\n\
181 \ global.WebSocket = require('ws');\n\
@@ -165,20 +188,30 @@ jsaddleJs jsaddleUri refreshOnLoad = "\
165 (jsaddleUri >>= LBS.stripPrefix "http")
188 (jsaddleUri >>= LBS.stripPrefix "http")
168− \ var ws = new WebSocket(wsaddress);\n\
191+ \ var ws0 = new WebSocket(wsaddress);\n\
169 \ var syncKey = \"\";\n\
192 \ var syncKey = \"\";\n\
171− \ ws.onopen = function(e) {\n\
194+ \ ws0.onopen = function(e) {\n\
195+ \ ws0.send(\"\");\n\
196+ \ var initialResults = [];\n\
197+ \ var ws = {send: function(m) {initialResults.push(m);}};\n\
172 \ " <> initState <> "\n\
198 \ " <> initState <> "\n\
174− \ ws.onmessage = function(e) {\n\
200+ \ ws0.onmessage = function(e) {\n\
175 \ var batch = JSON.parse(e.data);\n\
201 \ var batch = JSON.parse(e.data);\n\
176 \ if(inCallback > 0) {\n\
202 \ if(inCallback > 0) {\n\
177 \ asyncBatch = batch;\n\
203 \ asyncBatch = batch;\n\
178 \ return;\n\
204 \ return;\n\
180 \ if(typeof batch === \"string\") {\n\
206 \ if(typeof batch === \"string\") {\n\
181− \ syncKey = batch;\n" <>
207+ \ syncKey = batch;\n\
208+ \ var ws1 = new WebSocket(wsaddress);\n\
209+ \ ws1.onopen = function(e) {\n\
210+ \ ws1.send(syncKey);\n\
211+ \ initialResults.forEach(function(m){ ws1.send(m); });\n\
212+ \ initialResults = null;\n\
182 (if refreshOnLoad
215 (if refreshOnLoad
183 then " var xhr = new XMLHttpRequest();\n\
216 then " var xhr = new XMLHttpRequest();\n\
184 \ xhr.open('POST', '/reload/'+syncKey, true);\n\
217 \ xhr.open('POST', '/reload/'+syncKey, true);\n\
@@ -200,7 +233,7 @@ jsaddleJs jsaddleUri refreshOnLoad = "\
200 \ return JSON.parse(xhr.response);})()")) <> "\
233 \ return JSON.parse(xhr.response);})()")) <> "\
203− \ ws.onerror = function() {\n\
236+ \ ws0.onerror = function() {\n\
204 \ setTimeout(connect, 1000);\n\
237 \ setTimeout(connect, 1000);\n\
@@ -216,7 +249,14 @@ debug :: Int -> JSM () -> IO ()
216debug port f = do
249debug port f = do
217 debugWrapper $ \withRefresh registerContext ->
250 debugWrapper $ \withRefresh registerContext ->
218 runSettings (setPort port (setTimeout 3600 defaultSettings)) =<<
251 runSettings (setPort port (setTimeout 3600 defaultSettings)) =<<
219− jsaddleOr defaultConnectionOptions (registerContext >> f >> syncPoint) (withRefresh $ jsaddleAppWithJs $ jsaddleJs Nothing True)
252+ jsaddleOr defaultConnectionOptions (registerContext >> f >> syncPoint) (withRefresh $ jsaddleAppWithJs $ jsaddleJs True)
253+ putStrLn $ "<a href=\"http://localhost:" <> show port <> "\">run</a>"
255+debugOr :: Int -> JSM () -> Application -> IO ()
256+debugOr port f b = do
257+ debugWrapper $ \withRefresh registerContext ->
258+ runSettings (setPort port (setTimeout 3600 defaultSettings)) =<<
259+ jsaddleOr defaultConnectionOptions (registerContext >> f >> syncPoint) (withRefresh $ jsaddleAppWithJsOr (jsaddleJs True) b)
220 putStrLn $ "<a href=\"http://localhost:" <> show port <> "\">run</a>"
260 putStrLn $ "<a href=\"http://localhost:" <> show port <> "\">run</a>"
222refreshMiddleware :: ((Response -> IO ResponseReceived) -> IO ResponseReceived) -> Middleware
262refreshMiddleware :: ((Response -> IO ResponseReceived) -> IO ResponseReceived) -> Middleware
@@ -267,13 +307,13 @@ debugWrapper run = do
267 start' <- takeMVar mvar
307 start' <- takeMVar mvar
268 n <- stop
308 n <- stop
269 start' n >>= restarter mvar
309 start' n >>= restarter mvar
270− lookupStore shutdown_0 >>= \case
310+ lookupStore storeId >>= \case
271 Nothing -> do
311 Nothing -> do
272 restartMVar <- newMVar start
312 restartMVar <- newMVar start
273 void . forkIO $ restarter restartMVar (return 0)
313 void . forkIO $ restarter restartMVar (return 0)
274− void $ newStore restartMVar
314+ void $ writeStore (Store storeId) restartMVar
275 Just shutdownStore -> do
315 Just shutdownStore -> do
276 restartMVar :: MVar (Int -> IO (IO Int)) <- readStore shutdownStore
316 restartMVar :: MVar (Int -> IO (IO Int)) <- readStore shutdownStore
277 void $ tryTakeMVar restartMVar
317 void $ tryTakeMVar restartMVar
278 putMVar restartMVar start
318 putMVar restartMVar start
279− where shutdown_0 = 0
319+ where storeId = 354