packages feed

effectful-config-file-0.1.3.0: src/Effectful/Config/Watch.hs

{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeOperators #-}

-- | Reload a configuration when its file changes.
module Effectful.Config.Watch (
  watchConfig,
) where

import Control.Concurrent (threadDelay)
import Control.Concurrent.MVar (
  modifyMVar,
  newEmptyMVar,
  takeMVar,
  tryPutMVar,
  tryTakeMVar,
 )
import Control.Monad (forever, void)
import Data.Error.Config (ConfigError)
import qualified Data.Text as T (pack)
import Effectful (Eff, IOE, liftIO, withSeqEffToIO, type (:>))
import Effectful.Config (Config, readConfig')
import Effectful.Config.Log (Log, logWarn)
import Effectful.Error.Static (runErrorNoCallStack)
import Effectful.Reader.Static (ask)
import System.Directory (canonicalizePath)
import System.FSNotify (eventPath, watchDir, withManager)
import System.FilePath (takeDirectory, takeFileName, (</>))
import Toml.Schema.FromValue (FromValue)

-- | Watch a configuration file and reload it into the shared configuration
-- on change, calling the callback with the old and new values. Changes are
-- debounced; a file that fails to parse is logged and the old value kept.
-- Blocks forever.
--
-- @since 0.1.3.0
watchConfig
  :: IOE :> es
  => Log :> es
  => Config c :> es
  => FromValue c
  => FilePath
  -> (c -> c -> Eff es ())
  -- ^ called with old and new configuration after each reload
  -> Eff es ()
watchConfig path callback = do
  mvar <- ask
  dir <- liftIO (canonicalizePath (takeDirectory path))
  let file = dir </> takeFileName path
  withSeqEffToIO $ \runInIO -> do
    trigger <- newEmptyMVar
    withManager $ \mgr -> do
      _ <- watchDir mgr dir ((== file) . eventPath) (\_ -> void (tryPutMVar trigger ()))
      forever $ do
        takeMVar trigger
        threadDelay 200000
        void (tryTakeMVar trigger)
        runInIO $
          runErrorNoCallStack @ConfigError (readConfig' file) >>= \r -> case r of
            Left e -> logWarn ("config reload failed: " <> T.pack (show e))
            Right new -> do
              old <- liftIO (modifyMVar mvar (\o -> pure (new, o)))
              callback old new