@@ -19,9 +19,13 @@ module Language.Javascript.JSaddle.WebSockets (
1919 jsaddleOr
2020 , jsaddleApp
2121 , jsaddleWithAppOr
22+ , jsaddleAppWithJs
23+ , jsaddleAppWithJsOr
2224 , jsaddleAppPartial
2325 , jsaddleJs
26+ , jsaddleJs'
2427 , debug
28+ , debugOr
2529 , debugWrapper
2630) where
2731
@@ -56,44 +60,57 @@ import qualified Data.Map as M (empty, insert, lookup)
5660import Data.IORef
5761 (readIORef, newIORef, atomicModifyIORef')
5862import Data.ByteString.Lazy (ByteString)
63+import qualified Data.ByteString.Lazy as LBS
64+ (toStrict, stripPrefix)
5965import Control.Concurrent.MVar
6066 (tryTakeMVar, MVar, tryPutMVar, modifyMVar_, putMVar, takeMVar,
6167 readMVar, newMVar, newEmptyMVar, modifyMVar)
6268import Network.Wai.Handler.Warp
6369 (defaultSettings, setTimeout, setPort, runSettings)
64−import Foreign.Store (newStore, readStore, lookupStore)
70+import Foreign.Store (readStore, lookupStore, writeStore, Store(..))
6571import Language.Javascript.JSaddle (askJSM)
6672import Control.Monad.IO.Class (MonadIO(..))
6773
6874import Language.Javascript.JSaddle.WebSockets.Compat (getTextMessageByteString)
75+import qualified Data.Text.Encoding as T (decodeUtf8)
6976
7077jsaddleOr :: ConnectionOptions -> JSM () -> Application -> IO Application
7178jsaddleOr opts entryPoint otherApp = do
7279 syncHandlers <- newIORef M.empty
80+ asyncHandlers <- newIORef M.empty
7381 let wsApp :: ServerApp
7482 wsApp pending_conn = do
7583 conn <- acceptRequest pending_conn
76− rec (processResult, processSyncResult, start) <- runJavaScript (sendTextData conn . encode) $ do
77− syncKey <- T.pack . show . contextId <$> askJSM
78− liftIO $ atomicModifyIORef' syncHandlers (\m -> (M.insert syncKey processSyncResult m, ()))
79− liftIO $ sendTextData conn (encode syncKey)
80− entryPoint
81− _ <- forkIO . forever $
82− receiveDataMessage conn >>= \msg -> case getTextMessageByteString msg of
83− Just t ->
84− case decode t of
85− Nothing -> error $ "jsaddle Results decode failed : " <> show t
86− Just r -> processResult r
87− _ -> error "jsaddle WebSocket unexpected binary data"
88− start
89− 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"
90107
91108 -- Based on Network.WebSocket.forkPingThread
92109 waitTillClosed conn = ignore `handle` go 1
93110 where
94111 go :: Int -> IO ()
95112 go i = do
96− threadDelay (1 * 1000 * 1000)
113+ threadDelay (10 * 1000 * 1000)
97114 sendPing conn (T.pack $ show i)
98115 go (i + 1)
99116
@@ -126,9 +143,14 @@ jsaddleApp = jsaddleAppWithJs $ jsaddleJs False
126143
127144jsaddleAppWithJs :: ByteString -> Application
128145jsaddleAppWithJs js req sendResponse =
129− fromMaybe
130− (sendResponse $ W.responseLBS H.status403 [("Content-Type", "text/plain")] "Forbidden")
131− (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)
132154
133155jsaddleWithAppOr :: ConnectionOptions -> JSM () -> Application -> IO Application
134156jsaddleWithAppOr opts entryPoint otherApp = jsaddleOr opts entryPoint $ \req sendResponse ->
@@ -147,32 +169,49 @@ jsaddleAppPartialWithJs js req sendResponse = case (W.requestMethod req, W.pathI
147169 ("GET", ["jsaddle.js"]) -> Just $ sendResponse $ W.responseLBS H.status200 [("Content-Type", "application/javascript")] js
148170 _ -> Nothing
149171
172+jsaddleJs :: Bool -> ByteString
173+jsaddleJs = jsaddleJs' Nothing
174+
150175-- Use this to generate this string for embedding
151176-- sed -e 's|\\|\\\\|g' -e 's|^| \\|' -e 's|$|\\n\\|' -e 's|"|\\"|g' data/jsaddle.js | pbcopy
152−jsaddleJs :: Bool -> ByteString
153−jsaddleJs refreshOnLoad = "\
154− \if(typeof global !== \"undefined\") {\n\
177+jsaddleJs' :: Maybe ByteString -> Bool -> ByteString
178+jsaddleJs' jsaddleUri refreshOnLoad = "\
179+ \if(typeof global !== \"undefined\" && typeof require === \"function\") {\n\
155180 \ global.window = global;\n\
156181 \ global.WebSocket = require('ws');\n\
157182 \}\n\
158183 \\n\
159184 \var connect = function() {\n\
160− \ var wsaddress = window.location.protocol.replace('http', 'ws')+\"//\"+window.location.hostname+(window.location.port?(\":\"+window.location.port):\"\");\n\
185+ \ var wsaddress = "
186+ <> maybe "window.location.protocol.replace('http', 'ws')+\"//\"+window.location.hostname+(window.location.port?(\":\"+window.location.port):\"\")"
187+ (\ s -> "\"ws" <> s <> "\"")
188+ (jsaddleUri >>= LBS.stripPrefix "http")
189+ <> ";\n\
161190 \\n\
162− \ var ws = new WebSocket(wsaddress);\n\
191+ \ var ws0 = new WebSocket(wsaddress);\n\
163192 \ var syncKey = \"\";\n\
164193 \\n\
165− \ 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\
166198 \ " <> initState <> "\n\
167199 \\n\
168− \ ws.onmessage = function(e) {\n\
200+ \ ws0.onmessage = function(e) {\n\
169201 \ var batch = JSON.parse(e.data);\n\
170202 \ if(inCallback > 0) {\n\
171203 \ asyncBatch = batch;\n\
172204 \ return;\n\
173205 \ }\n\
174206 \ if(typeof batch === \"string\") {\n\
175− \ 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" <>
176215 (if refreshOnLoad
177216 then " var xhr = new XMLHttpRequest();\n\
178217 \ xhr.open('POST', '/reload/'+syncKey, true);\n\
@@ -188,13 +227,13 @@ jsaddleJs refreshOnLoad = "\
188227 \ " <> runBatch (\a -> "ws.send(JSON.stringify(" <> a <> "));")
189228 (Just (\a -> "(function(){\n\
190229 \ var xhr = new XMLHttpRequest();\n\
191− \ xhr.open('POST', '/sync/'+syncKey, false);\n\
230+ \ xhr.open('POST', '" <> fromMaybe "" jsaddleUri <> "/sync/'+syncKey, false);\n\
192231 \ xhr.setRequestHeader(\"Content-type\", \"application/json\");\n\
193232 \ xhr.send(JSON.stringify(" <> a <> "));\n\
194233 \ return JSON.parse(xhr.response);})()")) <> "\
195234 \ };\n\
196235 \ };\n\
197− \ ws.onerror = function() {\n\
236+ \ ws0.onerror = function() {\n\
198237 \ setTimeout(connect, 1000);\n\
199238 \ };\n\
200239 \}\n\
@@ -213,6 +252,13 @@ debug port f = do
213252 jsaddleOr defaultConnectionOptions (registerContext >> f >> syncPoint) (withRefresh $ jsaddleAppWithJs $ jsaddleJs True)
214253 putStrLn $ "<a href=\"http://localhost:" <> show port <> "\">run</a>"
215254
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+
216262refreshMiddleware :: ((Response -> IO ResponseReceived) -> IO ResponseReceived) -> Middleware
217263refreshMiddleware refresh otherApp req sendResponse = case (W.requestMethod req, W.pathInfo req) of
218264 ("POST", ["reload", _syncKey]) -> refresh sendResponse
@@ -261,13 +307,13 @@ debugWrapper run = do
261307 start' <- takeMVar mvar
262308 n <- stop
263309 start' n >>= restarter mvar
264− lookupStore shutdown_0 >>= \case
310+ lookupStore storeId >>= \case
265311 Nothing -> do
266312 restartMVar <- newMVar start
267313 void . forkIO $ restarter restartMVar (return 0)
268− void $ newStore restartMVar
314+ void $ writeStore (Store storeId) restartMVar
269315 Just shutdownStore -> do
270316 restartMVar :: MVar (Int -> IO (IO Int)) <- readStore shutdownStore
271317 void $ tryTakeMVar restartMVar
272318 putMVar restartMVar start
273− where shutdown_0 = 0
319+ where storeId = 354