aboutsummaryrefslogtreecommitdiff
path: root/hsm-core/Hsm/Core/Zmq/Client.hs
blob: 97728f7266774f5a0e71fbda21a4a0c57db32839 (plain)
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
{-# LANGUAGE AllowAmbiguousTypes #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE OverloadedRecordDot #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeFamilies #-}

module Hsm.Core.Zmq.Client
  ( Client
  , receive
  , poll
  , runClient
  ) where

import Control.Monad (forM_)
import Control.Monad.Loops (whileM)
import Data.ByteString (ByteString)
import Data.Text (Text, pack, unpack)
import Data.Text.Encoding (encodeUtf8)
import Effectful (Dispatch(Static), DispatchOf, Eff, IOE, (:>))
import Effectful.Dispatch.Static qualified as E
import Effectful.Log (Log, localDomain, logInfo_, logTrace_)
import Effectful.Reader.Static (Reader, ask)
import Effectful.Resource (Resource)
import GHC.Records (HasField)
import Hsm.Core.Message (topic)
import Hsm.Core.Zmq (withSocket)
import Streamly.Data.Stream (Stream, repeatM)
import System.ZMQ4 qualified as Z

data Client a b

type instance DispatchOf Client = Static E.WithSideEffects

newtype instance E.StaticRep Client =
  Client (Z.Socket Z.Sub)

domain :: Text
domain = "client"

receiver :: (Log :> es, Client :> es) => Eff es ByteString
receiver = do
  Client sock <- E.getStaticRep
  message <- E.unsafeEff_ $ Z.receive sock
  localDomain domain
    $ logTrace_
    $ "Message received with topic: " <> topic message
  return message

receive :: (Log :> es, Client :> es) => Stream (Eff es) ByteString
receive = repeatM receiver

poll :: (Log :> es, Client :> es) => Stream (Eff es) [ByteString]
poll =
  repeatM $ do
    ms <- whileM newMsg receiver
    localDomain domain
      $ localDomain "poller"
      $ logTrace_
      $ pack (show $ length ms) <> " new message(s) on queue"
    return ms
  where
    newMsg = do
      Client sock <- E.getStaticRep
      peek <- E.unsafeEff_ $ Z.poll 0 [Z.Sock sock [Z.In] Nothing]
      return $ peek /= [[]]

runClient ::
     forall env es a.
     ( HasField "subEps" env [Text]
     , HasField "topics" env [Text]
     , IOE :> es
     , Log :> es
     , Reader env :> es
     , Resource :> es
     )
  => Eff (Client : es) a
  -> Eff es a
runClient action =
  withSocket Z.Sub >>= \sock ->
    E.evalStaticRep (Client sock) $ do
      localDomain domain $ do
        logInfo_ "Initializing ZMQ client"
        env <- ask @env
        forM_ env.subEps $ E.unsafeEff_ . Z.connect sock . unpack
        forM_ env.topics $ E.unsafeEff_ . Z.subscribe sock . encodeUtf8
        logTrace_ $ "Listening to " <> pack (show env.subEps)
        logTrace_ $ "Subscribed to " <> pack (show env.topics)
      action