@@ -19,13 +19,9 @@ module Language.Javascript.JSaddle.WebSockets (
20 , jsaddleApp
20 , jsaddleApp
21 , jsaddleWithAppOr
21 , jsaddleWithAppOr
24 , jsaddleAppPartial
22 , jsaddleAppPartial
25 , jsaddleJs
23 , jsaddleJs
29 , debugWrapper
25 , debugWrapper
@@ -60,57 +56,44 @@ import qualified Data.Map as M (empty, insert, lookup)
60import Data.IORef
56import Data.IORef
61 (readIORef, newIORef, atomicModifyIORef')
57 (readIORef, newIORef, atomicModifyIORef')
62import Data.ByteString.Lazy (ByteString)
58import Data.ByteString.Lazy (ByteString)
63−import qualified Data.ByteString.Lazy as LBS
64− (toStrict, stripPrefix)
65import Control.Concurrent.MVar
59import Control.Concurrent.MVar
66 (tryTakeMVar, MVar, tryPutMVar, modifyMVar_, putMVar, takeMVar,
60 (tryTakeMVar, MVar, tryPutMVar, modifyMVar_, putMVar, takeMVar,
67 readMVar, newMVar, newEmptyMVar, modifyMVar)
61 readMVar, newMVar, newEmptyMVar, modifyMVar)
68import Network.Wai.Handler.Warp
62import Network.Wai.Handler.Warp
69 (defaultSettings, setTimeout, setPort, runSettings)
63 (defaultSettings, setTimeout, setPort, runSettings)
70−import Foreign.Store (readStore, lookupStore, writeStore, Store(..))
64+import Foreign.Store (newStore, readStore, lookupStore)
71import Language.Javascript.JSaddle (askJSM)
65import Language.Javascript.JSaddle (askJSM)
72import Control.Monad.IO.Class (MonadIO(..))
66import Control.Monad.IO.Class (MonadIO(..))
74import Language.Javascript.JSaddle.WebSockets.Compat (getTextMessageByteString)
68import Language.Javascript.JSaddle.WebSockets.Compat (getTextMessageByteString)
75−import qualified Data.Text.Encoding as T (decodeUtf8)
77jsaddleOr :: ConnectionOptions -> JSM () -> Application -> IO Application
70jsaddleOr :: ConnectionOptions -> JSM () -> Application -> IO Application
78jsaddleOr opts entryPoint otherApp = do
71jsaddleOr opts entryPoint otherApp = do
79 syncHandlers <- newIORef M.empty
72 syncHandlers <- newIORef M.empty
80− asyncHandlers <- newIORef M.empty
81 let wsApp :: ServerApp
73 let wsApp :: ServerApp
82 wsApp pending_conn = do
74 wsApp pending_conn = do
83 conn <- acceptRequest pending_conn
75 conn <- acceptRequest pending_conn
84− initMsg <- receiveDataMessage conn
85− case getTextMessageByteString initMsg of
87− rec (processResult, processSyncResult, start) <- runJavaScript (sendTextData conn . encode) $ do
76+ rec (processResult, processSyncResult, start) <- runJavaScript (sendTextData conn . encode) $ do
88− syncKey <- T.pack . show . contextId <$> askJSM
77+ syncKey <- T.pack . show . contextId <$> askJSM
89− liftIO $ atomicModifyIORef' syncHandlers (\m -> (M.insert syncKey processSyncResult m, ()))
78+ 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)
79+ liftIO $ sendTextData conn (encode syncKey)
92− entryPoint
80+ entryPoint
96− M.lookup (T.decodeUtf8 $ LBS.toStrict syncKey) <$> readIORef syncHandlers >>= \case
97− Nothing -> error "jsaddle missing sync message handler"
98− Just processResult ->
99− forever $
81+ _ <- forkIO . forever $
100− receiveDataMessage conn >>= \msg -> case getTextMessageByteString msg of
82+ receiveDataMessage conn >>= \msg -> case getTextMessageByteString msg of
101− Just t ->
83+ Just t ->
102− case decode t of
84+ case decode t of
103− Nothing -> error $ "jsaddle Results decode failed : " <> show t
85+ Nothing -> error $ "jsaddle Results decode failed : " <> show t
104− Just r -> processResult r
86+ Just r -> processResult r
105− _ -> error "jsaddle WebSocket unexpected binary data"
87+ _ -> error "jsaddle WebSocket unexpected binary data"
106− _ -> error "jsaddle WebSocket unexpected binary data"
88+ start
108 -- Based on Network.WebSocket.forkPingThread
91 -- Based on Network.WebSocket.forkPingThread
109 waitTillClosed conn = ignore `handle` go 1
92 waitTillClosed conn = ignore `handle` go 1
111 go :: Int -> IO ()
94 go :: Int -> IO ()
112 go i = do
95 go i = do
113− threadDelay (10 * 1000 * 1000)
96+ threadDelay (1 * 1000 * 1000)
114 sendPing conn (T.pack $ show i)
97 sendPing conn (T.pack $ show i)
115 go (i + 1)
98 go (i + 1)
@@ -143,14 +126,9 @@ jsaddleApp = jsaddleAppWithJs $ jsaddleJs False
144jsaddleAppWithJs :: ByteString -> Application
127jsaddleAppWithJs :: ByteString -> Application
145jsaddleAppWithJs js req sendResponse =
128jsaddleAppWithJs js req sendResponse =
146− jsaddleAppWithJsOr js
129+ fromMaybe
147− (\_ _ -> sendResponse $ W.responseLBS H.status403 [("Content-Type", "text/plain")] "Forbidden")
130+ (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)
153− (jsaddleAppPartialWithJs js req sendResponse)
131+ (jsaddleAppPartialWithJs js req sendResponse)
155jsaddleWithAppOr :: ConnectionOptions -> JSM () -> Application -> IO Application
133jsaddleWithAppOr :: ConnectionOptions -> JSM () -> Application -> IO Application
156jsaddleWithAppOr opts entryPoint otherApp = jsaddleOr opts entryPoint $ \req sendResponse ->
134jsaddleWithAppOr opts entryPoint otherApp = jsaddleOr opts entryPoint $ \req sendResponse ->
@@ -169,49 +147,32 @@ jsaddleAppPartialWithJs js req sendResponse = case (W.requestMethod req, W.pathI
169 ("GET", ["jsaddle.js"]) -> Just $ sendResponse $ W.responseLBS H.status200 [("Content-Type", "application/javascript")] js
147 ("GET", ["jsaddle.js"]) -> Just $ sendResponse $ W.responseLBS H.status200 [("Content-Type", "application/javascript")] js
170 _ -> Nothing
148 _ -> Nothing
172−jsaddleJs :: Bool -> ByteString
173−jsaddleJs = jsaddleJs' Nothing
175-- Use this to generate this string for embedding
150-- Use this to generate this string for embedding
176-- sed -e 's|\\|\\\\|g' -e 's|^| \\|' -e 's|$|\\n\\|' -e 's|"|\\"|g' data/jsaddle.js | pbcopy
151-- sed -e 's|\\|\\\\|g' -e 's|^| \\|' -e 's|$|\\n\\|' -e 's|"|\\"|g' data/jsaddle.js | pbcopy
177−jsaddleJs' :: Maybe ByteString -> Bool -> ByteString
152+jsaddleJs :: Bool -> ByteString
178−jsaddleJs' jsaddleUri refreshOnLoad = "\
153+jsaddleJs refreshOnLoad = "\
179− \if(typeof global !== \"undefined\" && typeof require === \"function\") {\n\
154+ \if(typeof global !== \"undefined\") {\n\
180 \ global.window = global;\n\
155 \ global.window = global;\n\
181 \ global.WebSocket = require('ws');\n\
156 \ global.WebSocket = require('ws');\n\
184 \var connect = function() {\n\
159 \var connect = function() {\n\
186− <> maybe "window.location.protocol.replace('http', 'ws')+\"//\"+window.location.hostname+(window.location.port?(\":\"+window.location.port):\"\")"
160+ \ var wsaddress = window.location.protocol.replace('http', 'ws')+\"//\"+window.location.hostname+(window.location.port?(\":\"+window.location.port):\"\");\n\
187− (\ s -> "\"ws" <> s <> "\"")
188− (jsaddleUri >>= LBS.stripPrefix "http")
191− \ var ws0 = new WebSocket(wsaddress);\n\
162+ \ var ws = new WebSocket(wsaddress);\n\
192 \ var syncKey = \"\";\n\
163 \ var syncKey = \"\";\n\
194− \ ws0.onopen = function(e) {\n\
165+ \ ws.onopen = function(e) {\n\
195− \ ws0.send(\"\");\n\
196− \ var initialResults = [];\n\
197− \ var ws = {send: function(m) {initialResults.push(m);}};\n\
198 \ " <> initState <> "\n\
166 \ " <> initState <> "\n\
200− \ ws0.onmessage = function(e) {\n\
168+ \ ws.onmessage = function(e) {\n\
201 \ var batch = JSON.parse(e.data);\n\
169 \ var batch = JSON.parse(e.data);\n\
202 \ if(inCallback > 0) {\n\
170 \ if(inCallback > 0) {\n\
203 \ asyncBatch = batch;\n\
171 \ asyncBatch = batch;\n\
204 \ return;\n\
172 \ return;\n\
206 \ if(typeof batch === \"string\") {\n\
174 \ if(typeof batch === \"string\") {\n\
207− \ syncKey = batch;\n\
175+ \ 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\
215 (if refreshOnLoad
176 (if refreshOnLoad
216 then " var xhr = new XMLHttpRequest();\n\
177 then " var xhr = new XMLHttpRequest();\n\
217 \ xhr.open('POST', '/reload/'+syncKey, true);\n\
178 \ xhr.open('POST', '/reload/'+syncKey, true);\n\
@@ -227,13 +188,13 @@ jsaddleJs' jsaddleUri refreshOnLoad = "\
227 \ " <> runBatch (\a -> "ws.send(JSON.stringify(" <> a <> "));")
188 \ " <> runBatch (\a -> "ws.send(JSON.stringify(" <> a <> "));")
228 (Just (\a -> "(function(){\n\
189 (Just (\a -> "(function(){\n\
229 \ var xhr = new XMLHttpRequest();\n\
190 \ var xhr = new XMLHttpRequest();\n\
230− \ xhr.open('POST', '" <> fromMaybe "" jsaddleUri <> "/sync/'+syncKey, false);\n\
191+ \ xhr.open('POST', '/sync/'+syncKey, false);\n\
231 \ xhr.setRequestHeader(\"Content-type\", \"application/json\");\n\
192 \ xhr.setRequestHeader(\"Content-type\", \"application/json\");\n\
232 \ xhr.send(JSON.stringify(" <> a <> "));\n\
193 \ xhr.send(JSON.stringify(" <> a <> "));\n\
233 \ return JSON.parse(xhr.response);})()")) <> "\
194 \ return JSON.parse(xhr.response);})()")) <> "\
236− \ ws0.onerror = function() {\n\
197+ \ ws.onerror = function() {\n\
237 \ setTimeout(connect, 1000);\n\
198 \ setTimeout(connect, 1000);\n\
@@ -252,13 +213,6 @@ debug port f = do
252 jsaddleOr defaultConnectionOptions (registerContext >> f >> syncPoint) (withRefresh $ jsaddleAppWithJs $ jsaddleJs True)
213 jsaddleOr defaultConnectionOptions (registerContext >> f >> syncPoint) (withRefresh $ jsaddleAppWithJs $ jsaddleJs True)
253 putStrLn $ "<a href=\"http://localhost:" <> show port <> "\">run</a>"
214 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>"
262refreshMiddleware :: ((Response -> IO ResponseReceived) -> IO ResponseReceived) -> Middleware
216refreshMiddleware :: ((Response -> IO ResponseReceived) -> IO ResponseReceived) -> Middleware
263refreshMiddleware refresh otherApp req sendResponse = case (W.requestMethod req, W.pathInfo req) of
217refreshMiddleware refresh otherApp req sendResponse = case (W.requestMethod req, W.pathInfo req) of
264 ("POST", ["reload", _syncKey]) -> refresh sendResponse
218 ("POST", ["reload", _syncKey]) -> refresh sendResponse
@@ -307,13 +261,13 @@ debugWrapper run = do
307 start' <- takeMVar mvar
261 start' <- takeMVar mvar
308 n <- stop
262 n <- stop
309 start' n >>= restarter mvar
263 start' n >>= restarter mvar
310− lookupStore storeId >>= \case
264+ lookupStore shutdown_0 >>= \case
311 Nothing -> do
265 Nothing -> do
312 restartMVar <- newMVar start
266 restartMVar <- newMVar start
313 void . forkIO $ restarter restartMVar (return 0)
267 void . forkIO $ restarter restartMVar (return 0)
314− void $ writeStore (Store storeId) restartMVar
268+ void $ newStore restartMVar
315 Just shutdownStore -> do
269 Just shutdownStore -> do
316 restartMVar :: MVar (Int -> IO (IO Int)) <- readStore shutdownStore
270 restartMVar :: MVar (Int -> IO (IO Int)) <- readStore shutdownStore
317 void $ tryTakeMVar restartMVar
271 void $ tryTakeMVar restartMVar
318 putMVar restartMVar start
272 putMVar restartMVar start
319− where storeId = 354
273+ where shutdown_0 = 0