module Faktory.Producer
  ( Producer(..)
  , newProducer
  , newProducerEnv
  , closeProducer
  , pushJob
  , flush
  )
where

import Faktory.Prelude

import Data.Aeson
import Faktory.Client
import Faktory.Settings
import GHC.Stack

newtype Producer = Producer
  { Producer -> Client
producerClient :: Client
  }

newProducer :: Settings -> IO Producer
newProducer :: Settings -> IO Producer
newProducer Settings
settings = Client -> Producer
Producer (Client -> Producer) -> IO Client -> IO Producer
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> HasCallStack => Settings -> Maybe WorkerId -> IO Client
Settings -> Maybe WorkerId -> IO Client
newClient Settings
settings Maybe WorkerId
forall a. Maybe a
Nothing

newProducerEnv :: IO Producer
newProducerEnv :: IO Producer
newProducerEnv = Settings -> IO Producer
newProducer (Settings -> IO Producer) -> IO Settings -> IO Producer
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< IO Settings
envSettings

closeProducer :: Producer -> IO ()
closeProducer :: Producer -> IO ()
closeProducer = Client -> IO ()
closeClient (Client -> IO ()) -> (Producer -> Client) -> Producer -> IO ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Producer -> Client
producerClient

-- | Push a Job to the Server
pushJob :: (HasCallStack, ToJSON a) => Producer -> a -> IO ()
pushJob :: Producer -> a -> IO ()
pushJob Producer
producer a
job = HasCallStack => Client -> ByteString -> [ByteString] -> IO ()
Client -> ByteString -> [ByteString] -> IO ()
commandOK (Producer -> Client
producerClient Producer
producer) ByteString
"PUSH" [a -> ByteString
forall a. ToJSON a => a -> ByteString
encode a
job]

-- | Clear all job data in the Faktory server
--
-- Use with caution!
--
flush :: HasCallStack => Producer -> IO ()
flush :: Producer -> IO ()
flush Producer
producer = HasCallStack => Client -> ByteString -> [ByteString] -> IO ()
Client -> ByteString -> [ByteString] -> IO ()
commandOK (Producer -> Client
producerClient Producer
producer) ByteString
"FLUSH" []