@@ -20,10 +20,12 @@ module Language.Javascript.JSaddle.WebSockets (
2020 , jsaddleApp
2121 , jsaddleWithAppOr
2222 , jsaddleAppWithJs
23+ , jsaddleAppWithJsOr
2324 , jsaddleAppPartial
2425 , jsaddleJs
2526 , jsaddleJs'
2627 , debug
28+ , debugOr
2729 , debugWrapper
2830) where
2931
@@ -58,45 +60,57 @@ import qualified Data.Map as M (empty, insert, lookup)
5860import Data.IORef
5961 (readIORef, newIORef, atomicModifyIORef')
6062import Data.ByteString.Lazy (ByteString)
61−import qualified Data.ByteString.Lazy as LBS (stripPrefix)
63+import qualified Data.ByteString.Lazy as LBS
64+ (toStrict, stripPrefix)
6265import Control.Concurrent.MVar
6366 (tryTakeMVar, MVar, tryPutMVar, modifyMVar_, putMVar, takeMVar,
6467 readMVar, newMVar, newEmptyMVar, modifyMVar)
6568import Network.Wai.Handler.Warp
6669 (defaultSettings, setTimeout, setPort, runSettings)
67−import Foreign.Store (newStore, readStore, lookupStore, writeStore, Store(..))
70+import Foreign.Store (readStore, lookupStore, writeStore, Store(..))
6871import Language.Javascript.JSaddle (askJSM)
6972import Control.Monad.IO.Class (MonadIO(..))
7073
7174import Language.Javascript.JSaddle.WebSockets.Compat (getTextMessageByteString)
75+import qualified Data.Text.Encoding as T (decodeUtf8)
7276
7377jsaddleOr :: ConnectionOptions -> JSM () -> Application -> IO Application
7478jsaddleOr opts entryPoint otherApp = do
7579 syncHandlers <- newIORef M.empty
80+ asyncHandlers <- newIORef M.empty
7681 let wsApp :: ServerApp
7782 wsApp pending_conn = do
7883 conn <- acceptRequest pending_conn
79− rec (processResult, processSyncResult, start) <- runJavaScript (sendTextData conn . encode) $ do
80− syncKey <- T.pack . show . contextId <$> askJSM
81− liftIO $ atomicModifyIORef' syncHandlers (\m -> (M.insert syncKey processSyncResult m, ()))
82− liftIO $ sendTextData conn (encode syncKey)
83− entryPoint
84− _ <- forkIO . forever $
85− receiveDataMessage conn >>= \msg -> case getTextMessageByteString msg of
86− Just t ->
87− case decode t of
88− Nothing -> error $ "jsaddle Results decode failed : " <> show t
89− Just r -> processResult r
90− _ -> error "jsaddle WebSocket unexpected binary data"
91− start
92− waitTillClosed conn
84+ initMsg <- receiveDataMessage conn
85+ case getTextMessageByteString initMsg of
86+ Just "" -> do
87+ rec (processResult, processSyncResult, start) <- runJavaScript (sendTextData conn . encode) $ do
88+ syncKey <- T.pack . show . contextId <$> askJSM
89+ liftIO $ atomicModifyIORef' syncHandlers (\m -> (M.insert syncKey processSyncResult m, ()))
90+ liftIO $ atomicModifyIORef' asyncHandlers (\m -> (M.insert syncKey processResult m, ()))
91+ liftIO $ sendTextData conn (encode syncKey)
92+ entryPoint
93+ start
94+ waitTillClosed conn
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 ->
99+ forever $
100+ receiveDataMessage conn >>= \msg -> case getTextMessageByteString msg of
101+ Just t ->
102+ case decode t of
103+ Nothing -> error $ "jsaddle Results decode failed : " <> show t
104+ Just r -> processResult r
105+ _ -> error "jsaddle WebSocket unexpected binary data"
106+ _ -> error "jsaddle WebSocket unexpected binary data"
93107
94108 -- Based on Network.WebSocket.forkPingThread
95109 waitTillClosed conn = ignore `handle` go 1
96110 where
97111 go :: Int -> IO ()
98112 go i = do
99− threadDelay (1 * 1000 * 1000)
113+ threadDelay (10 * 1000 * 1000)
100114 sendPing conn (T.pack $ show i)
101115 go (i + 1)
102116
@@ -129,9 +143,14 @@ jsaddleApp = jsaddleAppWithJs $ jsaddleJs False
129143
130144jsaddleAppWithJs :: ByteString -> Application
131145jsaddleAppWithJs js req sendResponse =
132− fromMaybe
133− (sendResponse $ W.responseLBS H.status403 [("Content-Type", "text/plain")] "Forbidden")
134− (jsaddleAppPartialWithJs js req sendResponse)
146+ jsaddleAppWithJsOr js
147+ (\_ _ -> sendResponse $ W.responseLBS H.status403 [("Content-Type", "text/plain")] "Forbidden")
148+ req sendResponse
149+
150+jsaddleAppWithJsOr :: ByteString -> Application -> Application
151+jsaddleAppWithJsOr js otherApp req sendResponse =
152+ fromMaybe (otherApp req sendResponse)
153+ (jsaddleAppPartialWithJs js req sendResponse)
135154
136155jsaddleWithAppOr :: ConnectionOptions -> JSM () -> Application -> IO Application
137156jsaddleWithAppOr opts entryPoint otherApp = jsaddleOr opts entryPoint $ \req sendResponse ->
@@ -157,7 +176,7 @@ jsaddleJs = jsaddleJs' Nothing
157176-- sed -e 's|\\|\\\\|g' -e 's|^| \\|' -e 's|$|\\n\\|' -e 's|"|\\"|g' data/jsaddle.js | pbcopy
158177jsaddleJs' :: Maybe ByteString -> Bool -> ByteString
159178jsaddleJs' jsaddleUri refreshOnLoad = "\
160− \if(typeof global !== \"undefined\") {\n\
179+ \if(typeof global !== \"undefined\" && typeof require === \"function\") {\n\
161180 \ global.window = global;\n\
162181 \ global.WebSocket = require('ws');\n\
163182 \}\n\
@@ -169,20 +188,30 @@ jsaddleJs' jsaddleUri refreshOnLoad = "\
169188 (jsaddleUri >>= LBS.stripPrefix "http")
170189 <> ";\n\
171190 \\n\
172− \ var ws = new WebSocket(wsaddress);\n\
191+ \ var ws0 = new WebSocket(wsaddress);\n\
173192 \ var syncKey = \"\";\n\
174193 \\n\
175− \ 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\
176198 \ " <> initState <> "\n\
177199 \\n\
178− \ ws.onmessage = function(e) {\n\
200+ \ ws0.onmessage = function(e) {\n\
179201 \ var batch = JSON.parse(e.data);\n\
180202 \ if(inCallback > 0) {\n\
181203 \ asyncBatch = batch;\n\
182204 \ return;\n\
183205 \ }\n\
184206 \ if(typeof batch === \"string\") {\n\
185− \ 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\
213+ \ ws = ws1;\n\
214+ \ }\n" <>
186215 (if refreshOnLoad
187216 then " var xhr = new XMLHttpRequest();\n\
188217 \ xhr.open('POST', '/reload/'+syncKey, true);\n\
@@ -204,7 +233,7 @@ jsaddleJs' jsaddleUri refreshOnLoad = "\
204233 \ return JSON.parse(xhr.response);})()")) <> "\
205234 \ };\n\
206235 \ };\n\
207− \ ws.onerror = function() {\n\
236+ \ ws0.onerror = function() {\n\
208237 \ setTimeout(connect, 1000);\n\
209238 \ };\n\
210239 \}\n\
@@ -223,6 +252,13 @@ debug port f = do
223252 jsaddleOr defaultConnectionOptions (registerContext >> f >> syncPoint) (withRefresh $ jsaddleAppWithJs $ jsaddleJs True)
224253 putStrLn $ "<a href=\"http://localhost:" <> show port <> "\">run</a>"
225254
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)
260+ putStrLn $ "<a href=\"http://localhost:" <> show port <> "\">run</a>"
261+
226262refreshMiddleware :: ((Response -> IO ResponseReceived) -> IO ResponseReceived) -> Middleware
227263refreshMiddleware refresh otherApp req sendResponse = case (W.requestMethod req, W.pathInfo req) of
228264 ("POST", ["reload", _syncKey]) -> refresh sendResponse