packages feed

hs-hath-1.4.0: app/Main.hs

{-# LANGUAGE CPP #-}

module Main ( main ) where

import           Database.SQLite.Simple ( withConnection )

import           Hath.CLI               ( Options(..), applyOptionsToConfig, parseOptions )
import           Hath.Cache.SQLite      ( VerificationStats(..), initializeDB, verifyAllFiles )
import           Hath.Config            ( CacheBackend(..), ClientConfig(..), readClientConfig )
import           Hath.RPC               ( clientLogin
                                        , getCertificate
                                        , loginFailure
                                        , runRPCIO
                                        , serverStat
                                        )
import           Hath.Server            ( ServerAction(GracefulShutdown)
                                        , ServerOptions(..)
                                        , needsRenewal
                                        , startServer
                                        )
import           Hath.ServerTime        ( serverNow )

import           Relude

#if defined(mingw32_HOST_OS)
import           GHC.ConsoleHandler     ( Handler(Catch), installHandler )
#else
import           System.Posix           ( Handler(Catch), installHandler, sigINT, sigTERM )
#endif

import           UnliftIO               ( TChan, newTChanIO, readTChan, timeout, writeTChan )

main :: IO ()
main = do
  options <- parseOptions
  config <- applyOptionsToConfig options <$> readClientConfig (toText $ optConfigPath options)
  when (optValidateConfig options) $ do
    putStrLn "Configuration is valid."
    exitSuccess

  -- for the other backends cachePath is a directory, or not used at all
  when (cacheBackend config == CacheBackendSQLite) $ prepareSQLiteCache options config

  actions <- newTChanIO
  onStop $ atomically $ writeTChan actions GracefulShutdown

  runRPCIO config serverStat
    >>= either (\e -> giveUp actions 5 ("RPC is not available (" <> show e <> "), exiting...")) pure
  settings <- runRPCIO config clientLogin >>= either (uncurry (giveUp actions) . loginFailure) pure
  certs <- runRPCIO config getCertificate
    >>= either (\e -> giveUp actions 5 ("Unable to fetch certs (" <> show e <> "), exiting...")) pure
  now <- serverNow
  when (needsRenewal now (fst certs)) $ do
    putStrLn "The certificate from the server expires within a day; try again later."
    exitFailure
  exitWith =<< startServer
    config
    ServerOptions { disableRateLimit  = optDisableRateLimit options
                  , trustProxyHeaders = optTrustProxyHeaders options
                  , skipStartupVerify = optSkipStartupVerify options
                  }
    settings
    certs
    actions

prepareSQLiteCache :: Options -> ClientConfig -> IO ()
prepareSQLiteCache options config = withConnection (toString $ cachePath config) $ \conn -> do
  initializeDB conn
  unless (optSkipStartupVerify options) $ do
    putStrLn "Verifying cache integrity (this may take a while)..."
    stats <- verifyAllFiles conn
    putStrLn "Verification complete:"
    putStrLn $ "  Files verified: " <> show (verifiedCount stats)
    putStrLn $ "  Corrupted files removed: " <> show (corruptedCount stats)
    putStrLn $ "  Time elapsed: " <> show (verificationTime stats)
    when (corruptedCount stats > 0)
      $ putStrLn
      $ "WARNING: " <> show (corruptedCount stats) <> " corrupted files were found and removed."

-- On Windows, GHC's RTS does not catch console window close events.
onStop :: IO () -> IO ()
#if defined(mingw32_HOST_OS)
onStop stop = void $ installHandler $ Catch $ const stop
#else
onStop stop = forM_ [ sigINT, sigTERM ] $ \signal -> installHandler signal (Catch stop) Nothing
#endif

-- | Wait before exiting so a supervisor restart does not hammer the RPC server; a stop signal cuts the wait short.
giveUp :: TChan ServerAction -> Int -> Text -> IO a
giveUp actions seconds message = do
  putTextLn message
  void $ timeout (seconds * 1000000) $ atomically $ readTChan actions
  exitFailure