@@ -19,8 +19,13 @@ module Language.Javascript.JSaddle.WebSockets (
1919 jsaddleOr
2020 , jsaddleApp
2121 , jsaddleWithAppOr
22+ , jsaddleAppWithJs
23+ , jsaddleAppWithJsOr
2224 , jsaddleAppPartial
25+ , jsaddleJs
26+ , jsaddleJs'
2327 , debug
28+ , debugOr
2429 , debugWrapper
2530) where
2631
@@ -37,12 +42,12 @@ import Network.Wai
3742import Network.WebSockets
3843 (defaultConnectionOptions, ConnectionOptions(..), sendTextData,
3944 receiveDataMessage, acceptRequest, ServerApp, sendPing)
40−import qualified Network.WebSockets as WS (DataMessage(..))
4145import Network.Wai.Handler.WebSockets (websocketsOr)
46+import Network.HTTP.Types (Status(..))
4247
4348import Language.Javascript.JSaddle.Types (JSM(..), JSContextRef(..))
4449import qualified Network.Wai as W
45− (responseLBS, requestMethod, pathInfo)
50+ (responseLBS, requestMethod, pathInfo, modifyResponse, responseStatus)
4651import qualified Data.Text as T (pack)
4752import qualified Network.HTTP.Types as H
4853 (status403, status200)
@@ -55,42 +60,57 @@ import qualified Data.Map as M (empty, insert, lookup)
5560import Data.IORef
5661 (readIORef, newIORef, atomicModifyIORef')
5762import Data.ByteString.Lazy (ByteString)
63+import qualified Data.ByteString.Lazy as LBS
64+ (toStrict, stripPrefix)
5865import Control.Concurrent.MVar
5966 (tryTakeMVar, MVar, tryPutMVar, modifyMVar_, putMVar, takeMVar,
6067 readMVar, newMVar, newEmptyMVar, modifyMVar)
6168import Network.Wai.Handler.Warp
6269 (defaultSettings, setTimeout, setPort, runSettings)
63−import Foreign.Store (newStore, readStore, lookupStore)
70+import Foreign.Store (readStore, lookupStore, writeStore, Store(..))
6471import Language.Javascript.JSaddle (askJSM)
6572import Control.Monad.IO.Class (MonadIO(..))
6673
74+import Language.Javascript.JSaddle.WebSockets.Compat (getTextMessageByteString)
75+import qualified Data.Text.Encoding as T (decodeUtf8)
76+
6777jsaddleOr :: ConnectionOptions -> JSM () -> Application -> IO Application
6878jsaddleOr opts entryPoint otherApp = do
6979 syncHandlers <- newIORef M.empty
80+ asyncHandlers <- newIORef M.empty
7081 let wsApp :: ServerApp
7182 wsApp pending_conn = do
7283 conn <- acceptRequest pending_conn
73− rec (processResult, processSyncResult, start) <- runJavaScript (sendTextData conn . encode) $ do
74− syncKey <- T.pack . show . contextId <$> askJSM
75− liftIO $ atomicModifyIORef' syncHandlers (\m -> (M.insert syncKey processSyncResult m, ()))
76− liftIO $ sendTextData conn (encode syncKey)
77− entryPoint
78− _ <- forkIO . forever $
79− receiveDataMessage conn >>= \case
80− (WS.Text t) ->
81− case decode t of
82− Nothing -> error $ "jsaddle Results decode failed : " <> show t
83− Just r -> processResult r
84− _ -> error "jsaddle WebSocket unexpected binary data"
85− start
86− 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"
87107
88108 -- Based on Network.WebSocket.forkPingThread
89109 waitTillClosed conn = ignore `handle` go 1
90110 where
91111 go :: Int -> IO ()
92112 go i = do
93− threadDelay (1 * 1000 * 1000)
113+ threadDelay (10 * 1000 * 1000)
94114 sendPing conn (T.pack $ show i)
95115 go (i + 1)
96116
@@ -110,7 +130,11 @@ jsaddleOr opts entryPoint otherApp = do
110130 Just handler -> do
111131 next <- encode <$> handler result
112132 sendResponse $ W.responseLBS H.status200 [("Content-Type", "application/json")] next
113− _ -> otherApp req sendResponse
133+ (method, _) -> (catch404 otherApp) req sendResponse
134+ where catch404 = W.modifyResponse $ \resp ->
135+ case (method, W.responseStatus resp) of
136+ ("GET", Status 404 _) -> indexResponse
137+ _ -> resp
114138 return $ websocketsOr opts wsApp syncHandler
115139
116140
@@ -119,9 +143,14 @@ jsaddleApp = jsaddleAppWithJs $ jsaddleJs False
119143
120144jsaddleAppWithJs :: ByteString -> Application
121145jsaddleAppWithJs js req sendResponse =
122− fromMaybe
123− (sendResponse $ W.responseLBS H.status403 [("Content-Type", "text/plain")] "Forbidden")
124− (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)
125154
126155jsaddleWithAppOr :: ConnectionOptions -> JSM () -> Application -> IO Application
127156jsaddleWithAppOr opts entryPoint otherApp = jsaddleOr opts entryPoint $ \req sendResponse ->
@@ -131,38 +160,58 @@ jsaddleWithAppOr opts entryPoint otherApp = jsaddleOr opts entryPoint $ \req sen
131160jsaddleAppPartial :: Request -> (Response -> IO ResponseReceived) -> Maybe (IO ResponseReceived)
132161jsaddleAppPartial = jsaddleAppPartialWithJs $ jsaddleJs False
133162
163+indexResponse :: Response
164+indexResponse = W.responseLBS H.status200 [("Content-Type", "text/html")] indexHtml
165+
134166jsaddleAppPartialWithJs :: ByteString -> Request -> (Response -> IO ResponseReceived) -> Maybe (IO ResponseReceived)
135167jsaddleAppPartialWithJs js req sendResponse = case (W.requestMethod req, W.pathInfo req) of
136− ("GET", []) -> Just $ sendResponse $ W.responseLBS H.status200 [("Content-Type", "text/html")] indexHtml
168+ ("GET", []) -> Just $ sendResponse indexResponse
137169 ("GET", ["jsaddle.js"]) -> Just $ sendResponse $ W.responseLBS H.status200 [("Content-Type", "application/javascript")] js
138170 _ -> Nothing
139171
172+jsaddleJs :: Bool -> ByteString
173+jsaddleJs = jsaddleJs' Nothing
174+
140175-- Use this to generate this string for embedding
141176-- sed -e 's|\\|\\\\|g' -e 's|^| \\|' -e 's|$|\\n\\|' -e 's|"|\\"|g' data/jsaddle.js | pbcopy
142−jsaddleJs :: Bool -> ByteString
143−jsaddleJs refreshOnLoad = "\
144− \if(typeof global !== \"undefined\") {\n\
177+jsaddleJs' :: Maybe ByteString -> Bool -> ByteString
178+jsaddleJs' jsaddleUri refreshOnLoad = "\
179+ \if(typeof global !== \"undefined\" && typeof require === \"function\") {\n\
145180 \ global.window = global;\n\
146181 \ global.WebSocket = require('ws');\n\
147182 \}\n\
148183 \\n\
149184 \var connect = function() {\n\
150− \ 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\
151190 \\n\
152− \ var ws = new WebSocket(wsaddress);\n\
191+ \ var ws0 = new WebSocket(wsaddress);\n\
153192 \ var syncKey = \"\";\n\
154193 \\n\
155− \ 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\
156198 \ " <> initState <> "\n\
157199 \\n\
158− \ ws.onmessage = function(e) {\n\
200+ \ ws0.onmessage = function(e) {\n\
159201 \ var batch = JSON.parse(e.data);\n\
160202 \ if(inCallback > 0) {\n\
161203 \ asyncBatch = batch;\n\
162204 \ return;\n\
163205 \ }\n\
164206 \ if(typeof batch === \"string\") {\n\
165− \ 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" <>
166215 (if refreshOnLoad
167216 then " var xhr = new XMLHttpRequest();\n\
168217 \ xhr.open('POST', '/reload/'+syncKey, true);\n\
@@ -178,13 +227,13 @@ jsaddleJs refreshOnLoad = "\
178227 \ " <> runBatch (\a -> "ws.send(JSON.stringify(" <> a <> "));")
179228 (Just (\a -> "(function(){\n\
180229 \ var xhr = new XMLHttpRequest();\n\
181− \ xhr.open('POST', '/sync/'+syncKey, false);\n\
230+ \ xhr.open('POST', '" <> fromMaybe "" jsaddleUri <> "/sync/'+syncKey, false);\n\
182231 \ xhr.setRequestHeader(\"Content-type\", \"application/json\");\n\
183232 \ xhr.send(JSON.stringify(" <> a <> "));\n\
184233 \ return JSON.parse(xhr.response);})()")) <> "\
185234 \ };\n\
186235 \ };\n\
187− \ ws.onerror = function() {\n\
236+ \ ws0.onerror = function() {\n\
188237 \ setTimeout(connect, 1000);\n\
189238 \ };\n\
190239 \}\n\
@@ -203,6 +252,13 @@ debug port f = do
203252 jsaddleOr defaultConnectionOptions (registerContext >> f >> syncPoint) (withRefresh $ jsaddleAppWithJs $ jsaddleJs True)
204253 putStrLn $ "<a href=\"http://localhost:" <> show port <> "\">run</a>"
205254
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+
206262refreshMiddleware :: ((Response -> IO ResponseReceived) -> IO ResponseReceived) -> Middleware
207263refreshMiddleware refresh otherApp req sendResponse = case (W.requestMethod req, W.pathInfo req) of
208264 ("POST", ["reload", _syncKey]) -> refresh sendResponse
@@ -251,13 +307,13 @@ debugWrapper run = do
251307 start' <- takeMVar mvar
252308 n <- stop
253309 start' n >>= restarter mvar
254− lookupStore shutdown_0 >>= \case
310+ lookupStore storeId >>= \case
255311 Nothing -> do
256312 restartMVar <- newMVar start
257313 void . forkIO $ restarter restartMVar (return 0)
258− void $ newStore restartMVar
314+ void $ writeStore (Store storeId) restartMVar
259315 Just shutdownStore -> do
260316 restartMVar :: MVar (Int -> IO (IO Int)) <- readStore shutdownStore
261317 void $ tryTakeMVar restartMVar
262318 putMVar restartMVar start
263− where shutdown_0 = 0
319+ where storeId = 354