-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
rpcClient.hs
executable file
·57 lines (47 loc) · 1.83 KB
/
rpcClient.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#!/usr/bin/env stack
-- stack --install-ghc runghc --package bytestring --package text --package amqp --package uuid
{-# LANGUAGE OverloadedStrings #-}
import Control.Concurrent (MVar, newEmptyMVar, putMVar,
takeMVar)
import Control.Monad (when)
import qualified Data.ByteString.Lazy.Char8 as BL
import Data.Maybe (fromJust)
import Data.Text (Text)
import Data.UUID (toText)
import Data.UUID.V4 (nextRandom)
import Network.AMQP
type QueueName = Text
main :: IO ()
main = do
conn <- openConnection "127.0.0.1" "/" "guest" "guest"
ch <- openChannel conn
putStrLn " [x] Requesting fib(30)"
res <- callFib ch rpcQueue 30
putStrLn $ " [.] Got '" ++ show res ++ "'"
closeConnection conn
where
rpcQueue = "rpc_queue"
callFib :: Channel -> QueueName -> Int -> IO Int
callFib ch queue n = do
cid <- genCorrelationId
rqn <- declareReplyQueue
let body = BL.pack . show $ n
let message = newMsg {msgCorrelationID = Just cid, msgReplyTo = Just rqn, msgBody = body}
publishMsg ch "" queue message
m <- newEmptyMVar
consumeMsgs ch rqn Ack $ handleResponse cid m
res <- takeMVar m
return res
where
genCorrelationId = toText <$> nextRandom
declareReplyQueue = do
let opts = newQueue {queueAutoDelete = True, queueExclusive = True}
(rqn, _, _) <- declareQueue ch opts
return rqn
handleResponse :: Text -> MVar Int -> (Message, Envelope) -> IO ()
handleResponse corrId m (msg, envelope) = do
let msgCorrId = fromJust (msgCorrelationID msg)
when (msgCorrId == corrId) $ do
res <- readIO (BL.unpack . msgBody $ msg)
putMVar m res
ackEnv envelope