@@ -19,9 +19,13 @@ module Language.Javascript.JSaddle.WebSockets (
20 , jsaddleApp
20 , jsaddleApp
21 , jsaddleWithAppOr
21 , jsaddleWithAppOr
22 , jsaddleAppPartial
24 , jsaddleAppPartial
23 , jsaddleJs
25 , jsaddleJs
25 , debugWrapper
29 , debugWrapper
@@ -38,12 +42,12 @@ import Network.Wai
38import Network.WebSockets
42import Network.WebSockets
39 (defaultConnectionOptions, ConnectionOptions(..), sendTextData,
43 (defaultConnectionOptions, ConnectionOptions(..), sendTextData,
40 receiveDataMessage, acceptRequest, ServerApp, sendPing)
44 receiveDataMessage, acceptRequest, ServerApp, sendPing)
41−import qualified Network.WebSockets as WS (DataMessage(..))
42import Network.Wai.Handler.WebSockets (websocketsOr)
45import Network.Wai.Handler.WebSockets (websocketsOr)
46+import Network.HTTP.Types (Status(..))
44import Language.Javascript.JSaddle.Types (JSM(..), JSContextRef(..))
48import Language.Javascript.JSaddle.Types (JSM(..), JSContextRef(..))
45import qualified Network.Wai as W
49import qualified Network.Wai as W
46− (responseLBS, requestMethod, pathInfo)
50+ (responseLBS, requestMethod, pathInfo, modifyResponse, responseStatus)
47import qualified Data.Text as T (pack)
51import qualified Data.Text as T (pack)
48import qualified Network.HTTP.Types as H
52import qualified Network.HTTP.Types as H
49 (status403, status200)
53 (status403, status200)
@@ -56,42 +60,57 @@ import qualified Data.Map as M (empty, insert, lookup)
56import Data.IORef
60import Data.IORef
57 (readIORef, newIORef, atomicModifyIORef')
61 (readIORef, newIORef, atomicModifyIORef')
58import Data.ByteString.Lazy (ByteString)
62import Data.ByteString.Lazy (ByteString)
63+import qualified Data.ByteString.Lazy as LBS
64+ (toStrict, stripPrefix)
59import Control.Concurrent.MVar
65import Control.Concurrent.MVar
60 (tryTakeMVar, MVar, tryPutMVar, modifyMVar_, putMVar, takeMVar,
66 (tryTakeMVar, MVar, tryPutMVar, modifyMVar_, putMVar, takeMVar,
61 readMVar, newMVar, newEmptyMVar, modifyMVar)
67 readMVar, newMVar, newEmptyMVar, modifyMVar)
62import Network.Wai.Handler.Warp
68import Network.Wai.Handler.Warp
63 (defaultSettings, setTimeout, setPort, runSettings)
69 (defaultSettings, setTimeout, setPort, runSettings)
64−import Foreign.Store (newStore, readStore, lookupStore)
70+import Foreign.Store (readStore, lookupStore, writeStore, Store(..))
65import Language.Javascript.JSaddle (askJSM)
71import Language.Javascript.JSaddle (askJSM)
66import Control.Monad.IO.Class (MonadIO(..))
72import Control.Monad.IO.Class (MonadIO(..))
74+import Language.Javascript.JSaddle.WebSockets.Compat (getTextMessageByteString)
75+import qualified Data.Text.Encoding as T (decodeUtf8)
68jsaddleOr :: ConnectionOptions -> JSM () -> Application -> IO Application
77jsaddleOr :: ConnectionOptions -> JSM () -> Application -> IO Application
69jsaddleOr opts entryPoint otherApp = do
78jsaddleOr opts entryPoint otherApp = do
70 syncHandlers <- newIORef M.empty
79 syncHandlers <- newIORef M.empty
80+ asyncHandlers <- newIORef M.empty
71 let wsApp :: ServerApp
81 let wsApp :: ServerApp
72 wsApp pending_conn = do
82 wsApp pending_conn = do
73 conn <- acceptRequest pending_conn
83 conn <- acceptRequest pending_conn
84+ initMsg <- receiveDataMessage conn
85+ case getTextMessageByteString initMsg of
74− rec (processResult, processSyncResult, start) <- runJavaScript (sendTextData conn . encode) $ do
87+ rec (processResult, processSyncResult, start) <- runJavaScript (sendTextData conn . encode) $ do
75− syncKey <- T.pack . show . contextId <$> askJSM
88+ syncKey <- T.pack . show . contextId <$> askJSM
76− 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, ()))
77− liftIO $ sendTextData conn (encode syncKey)
91+ liftIO $ sendTextData conn (encode syncKey)
78− entryPoint
92+ entryPoint
79− _ <- forkIO . forever $
93+ start
80− receiveDataMessage conn >>= \case
94+ waitTillClosed conn
81− (WS.Text 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
82− case decode t of
102+ case decode t of
83− Nothing -> error $ "jsaddle Results decode failed : " <> show t
103+ Nothing -> error $ "jsaddle Results decode failed : " <> show t
84− Just r -> processResult r
104+ Just r -> processResult r
85− _ -> error "jsaddle WebSocket unexpected binary data"
105+ _ -> error "jsaddle WebSocket unexpected binary data"
86− start
106+ _ -> error "jsaddle WebSocket unexpected binary data"
89 -- Based on Network.WebSocket.forkPingThread
108 -- Based on Network.WebSocket.forkPingThread
90 waitTillClosed conn = ignore `handle` go 1
109 waitTillClosed conn = ignore `handle` go 1
92 go :: Int -> IO ()
111 go :: Int -> IO ()
93 go i = do
112 go i = do
94− threadDelay (1 * 1000 * 1000)
113+ threadDelay (10 * 1000 * 1000)
95 sendPing conn (T.pack $ show i)
114 sendPing conn (T.pack $ show i)
96 go (i + 1)
115 go (i + 1)
@@ -111,7 +130,11 @@ jsaddleOr opts entryPoint otherApp = do
111 Just handler -> do
130 Just handler -> do
112 next <- encode <$> handler result
131 next <- encode <$> handler result
113 sendResponse $ W.responseLBS H.status200 [("Content-Type", "application/json")] next
132 sendResponse $ W.responseLBS H.status200 [("Content-Type", "application/json")] next
114− _ -> 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
115 return $ websocketsOr opts wsApp syncHandler
138 return $ websocketsOr opts wsApp syncHandler
@@ -120,9 +143,14 @@ jsaddleApp = jsaddleAppWithJs $ jsaddleJs False
121jsaddleAppWithJs :: ByteString -> Application
144jsaddleAppWithJs :: ByteString -> Application
122jsaddleAppWithJs js req sendResponse =
145jsaddleAppWithJs js req sendResponse =
123− fromMaybe
146+ jsaddleAppWithJsOr js
124− (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)
125− (jsaddleAppPartialWithJs js req sendResponse)
153+ (jsaddleAppPartialWithJs js req sendResponse)
127jsaddleWithAppOr :: ConnectionOptions -> JSM () -> Application -> IO Application
155jsaddleWithAppOr :: ConnectionOptions -> JSM () -> Application -> IO Application
128jsaddleWithAppOr opts entryPoint otherApp = jsaddleOr opts entryPoint $ \req sendResponse ->
156jsaddleWithAppOr opts entryPoint otherApp = jsaddleOr opts entryPoint $ \req sendResponse ->
@@ -132,38 +160,58 @@ jsaddleWithAppOr opts entryPoint otherApp = jsaddleOr opts entryPoint $ \req sen
132jsaddleAppPartial :: Request -> (Response -> IO ResponseReceived) -> Maybe (IO ResponseReceived)
160jsaddleAppPartial :: Request -> (Response -> IO ResponseReceived) -> Maybe (IO ResponseReceived)
133jsaddleAppPartial = jsaddleAppPartialWithJs $ jsaddleJs False
161jsaddleAppPartial = jsaddleAppPartialWithJs $ jsaddleJs False
163+indexResponse :: Response
164+indexResponse = W.responseLBS H.status200 [("Content-Type", "text/html")] indexHtml
135jsaddleAppPartialWithJs :: ByteString -> Request -> (Response -> IO ResponseReceived) -> Maybe (IO ResponseReceived)
166jsaddleAppPartialWithJs :: ByteString -> Request -> (Response -> IO ResponseReceived) -> Maybe (IO ResponseReceived)
136jsaddleAppPartialWithJs js req sendResponse = case (W.requestMethod req, W.pathInfo req) of
167jsaddleAppPartialWithJs js req sendResponse = case (W.requestMethod req, W.pathInfo req) of
137− ("GET", []) -> Just $ sendResponse $ W.responseLBS H.status200 [("Content-Type", "text/html")] indexHtml
168+ ("GET", []) -> Just $ sendResponse indexResponse
138 ("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
139 _ -> Nothing
170 _ -> Nothing
172+jsaddleJs :: Bool -> ByteString
173+jsaddleJs = jsaddleJs' Nothing
141-- Use this to generate this string for embedding
175-- Use this to generate this string for embedding
142-- 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
143−jsaddleJs :: Bool -> ByteString
177+jsaddleJs' :: Maybe ByteString -> Bool -> ByteString
144−jsaddleJs refreshOnLoad = "\
178+jsaddleJs' jsaddleUri refreshOnLoad = "\
145− \if(typeof global !== \"undefined\") {\n\
179+ \if(typeof global !== \"undefined\" && typeof require === \"function\") {\n\
146 \ global.window = global;\n\
180 \ global.window = global;\n\
147 \ global.WebSocket = require('ws');\n\
181 \ global.WebSocket = require('ws');\n\
150 \var connect = function() {\n\
184 \var connect = function() {\n\
151− \ var wsaddress = window.location.protocol.replace('http', 'ws')+\"//\"+window.location.hostname+(window.location.port?(\":\"+window.location.port):\"\");\n\
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")
153− \ var ws = new WebSocket(wsaddress);\n\
191+ \ var ws0 = new WebSocket(wsaddress);\n\
154 \ var syncKey = \"\";\n\
192 \ var syncKey = \"\";\n\
156− \ 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\
157 \ " <> initState <> "\n\
198 \ " <> initState <> "\n\
159− \ ws.onmessage = function(e) {\n\
200+ \ ws0.onmessage = function(e) {\n\
160 \ var batch = JSON.parse(e.data);\n\
201 \ var batch = JSON.parse(e.data);\n\
161 \ if(inCallback > 0) {\n\
202 \ if(inCallback > 0) {\n\
162 \ asyncBatch = batch;\n\
203 \ asyncBatch = batch;\n\
163 \ return;\n\
204 \ return;\n\
165 \ if(typeof batch === \"string\") {\n\
206 \ if(typeof batch === \"string\") {\n\
166− \ 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\
167 (if refreshOnLoad
215 (if refreshOnLoad
168 then " var xhr = new XMLHttpRequest();\n\
216 then " var xhr = new XMLHttpRequest();\n\
169 \ xhr.open('POST', '/reload/'+syncKey, true);\n\
217 \ xhr.open('POST', '/reload/'+syncKey, true);\n\
@@ -179,13 +227,13 @@ jsaddleJs refreshOnLoad = "\
179 \ " <> runBatch (\a -> "ws.send(JSON.stringify(" <> a <> "));")
227 \ " <> runBatch (\a -> "ws.send(JSON.stringify(" <> a <> "));")
180 (Just (\a -> "(function(){\n\
228 (Just (\a -> "(function(){\n\
181 \ var xhr = new XMLHttpRequest();\n\
229 \ var xhr = new XMLHttpRequest();\n\
182− \ xhr.open('POST', '/sync/'+syncKey, false);\n\
230+ \ xhr.open('POST', '" <> fromMaybe "" jsaddleUri <> "/sync/'+syncKey, false);\n\
183 \ xhr.setRequestHeader(\"Content-type\", \"application/json\");\n\
231 \ xhr.setRequestHeader(\"Content-type\", \"application/json\");\n\
184 \ xhr.send(JSON.stringify(" <> a <> "));\n\
232 \ xhr.send(JSON.stringify(" <> a <> "));\n\
185 \ return JSON.parse(xhr.response);})()")) <> "\
233 \ return JSON.parse(xhr.response);})()")) <> "\
188− \ ws.onerror = function() {\n\
236+ \ ws0.onerror = function() {\n\
189 \ setTimeout(connect, 1000);\n\
237 \ setTimeout(connect, 1000);\n\
@@ -204,6 +252,13 @@ debug port f = do
204 jsaddleOr defaultConnectionOptions (registerContext >> f >> syncPoint) (withRefresh $ jsaddleAppWithJs $ jsaddleJs True)
252 jsaddleOr defaultConnectionOptions (registerContext >> f >> syncPoint) (withRefresh $ jsaddleAppWithJs $ jsaddleJs True)
205 putStrLn $ "<a href=\"http://localhost:" <> show port <> "\">run</a>"
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)
260+ putStrLn $ "<a href=\"http://localhost:" <> show port <> "\">run</a>"
207refreshMiddleware :: ((Response -> IO ResponseReceived) -> IO ResponseReceived) -> Middleware
262refreshMiddleware :: ((Response -> IO ResponseReceived) -> IO ResponseReceived) -> Middleware
208refreshMiddleware refresh otherApp req sendResponse = case (W.requestMethod req, W.pathInfo req) of
263refreshMiddleware refresh otherApp req sendResponse = case (W.requestMethod req, W.pathInfo req) of
209 ("POST", ["reload", _syncKey]) -> refresh sendResponse
264 ("POST", ["reload", _syncKey]) -> refresh sendResponse
@@ -252,13 +307,13 @@ debugWrapper run = do
252 start' <- takeMVar mvar
307 start' <- takeMVar mvar
253 n <- stop
308 n <- stop
254 start' n >>= restarter mvar
309 start' n >>= restarter mvar
255− lookupStore shutdown_0 >>= \case
310+ lookupStore storeId >>= \case
256 Nothing -> do
311 Nothing -> do
257 restartMVar <- newMVar start
312 restartMVar <- newMVar start
258 void . forkIO $ restarter restartMVar (return 0)
313 void . forkIO $ restarter restartMVar (return 0)
259− void $ newStore restartMVar
314+ void $ writeStore (Store storeId) restartMVar
260 Just shutdownStore -> do
315 Just shutdownStore -> do
261 restartMVar :: MVar (Int -> IO (IO Int)) <- readStore shutdownStore
316 restartMVar :: MVar (Int -> IO (IO Int)) <- readStore shutdownStore
262 void $ tryTakeMVar restartMVar
317 void $ tryTakeMVar restartMVar
263 putMVar restartMVar start
318 putMVar restartMVar start
264− where shutdown_0 = 0
319+ where storeId = 354