bos / configurator

A Haskell library supporting flexible, dynamic file-based configuration.
Other
128 stars 27 forks source link

reloader combinator #15

Closed mwotton closed 11 years ago

mwotton commented 11 years ago

Was wondering if there's a better way of doing this:

{-# LANGUAGE OverloadedStrings #-}
import Data.Configurator
import Data.Configurator.Types
import Control.Concurrent
import Control.Monad(forever)
import Data.IORef

withLiveConfig :: Config -> Name -> (Value -> IO ()) -> IO ()
withLiveConfig config key action = do
  val <- require config key
  ref <- newIORef =<< (forkIO $ action val)

  subscribe config (exact key) $ \k mv -> case mv of
    Nothing -> putStrLn ("no update for " ++ show k)
    Just v -> do
      putStrLn ("update for " ++ show k)
      pid <- readIORef ref
      killThread pid
      (forkIO $ action v) >>= writeIORef ref

main :: IO ()
main = do
  (config, _thread) <- autoReload autoConfig { onError = print } [Required "foo.conf"]
  _otherpid <- withLiveConfig config "foo" (\(String val) -> forever $ do
                                               threadDelay 1000000
                                               putStrLn $ show val)
  threadDelay 1000000000000

obviously, i shouldn't assume it's a string in the test harness and the combinator shouldn't spew to stdout, but it's enough for demonstration. Am I missing a combinator in the library? It seems like this would be generally useful.

mwotton commented 11 years ago

blah, this is insufficient. i will think again.