{-|
Module: IHP.ScriptSupport
Description: Run scripts inside the framework context, but outside of the usual web request response lifecycle
Copyright: (c) digitally induced GmbH, 2020
-}
module IHP.ScriptSupport (runScript, Script, module IHP.FrameworkConfig) where

import IHP.Prelude
import IHP.FrameworkConfig
import IHP.ModelSupport
import Control.Exception (finally)
import IHP.Log (Logger(cleanup))
import Main.Utf8 (withUtf8)

-- | A script is just an IO action which requires a database connection and framework config
type Script = (?modelContext :: ModelContext, ?context :: FrameworkConfig) => IO ()

-- | Initializes IHP and then runs the script inside the framework context
runScript :: ConfigBuilder -> Script -> IO ()
runScript :: ConfigBuilder -> Script -> IO ()
runScript ConfigBuilder
configBuilder Script
taskMain = IO () -> IO ()
forall (m :: * -> *) r. (MonadIO m, MonadMask m) => m r -> m r
withUtf8 do
    frameworkConfig :: FrameworkConfig
frameworkConfig@FrameworkConfig { Environment
environment :: Environment
$sel:environment:FrameworkConfig :: FrameworkConfig -> Environment
environment, NominalDiffTime
dbPoolIdleTime :: NominalDiffTime
$sel:dbPoolIdleTime:FrameworkConfig :: FrameworkConfig -> NominalDiffTime
dbPoolIdleTime, Int
dbPoolMaxConnections :: Int
$sel:dbPoolMaxConnections:FrameworkConfig :: FrameworkConfig -> Int
dbPoolMaxConnections, ByteString
databaseUrl :: ByteString
$sel:databaseUrl:FrameworkConfig :: FrameworkConfig -> ByteString
databaseUrl, Logger
logger :: Logger
$sel:logger:FrameworkConfig :: FrameworkConfig -> Logger
logger } <- ConfigBuilder -> IO FrameworkConfig
buildFrameworkConfig ConfigBuilder
configBuilder
    ModelContext
modelContext <- NominalDiffTime -> Int -> ByteString -> Logger -> IO ModelContext
createModelContext NominalDiffTime
dbPoolIdleTime Int
dbPoolMaxConnections ByteString
databaseUrl Logger
logger

    let ?modelContext = ?modelContext::ModelContext
ModelContext
modelContext
    let ?context = ?context::FrameworkConfig
FrameworkConfig
frameworkConfig
    IO ()
Script
taskMain IO () -> IO () -> IO ()
forall a b. IO a -> IO b -> IO a
`finally` Logger -> IO ()
cleanup Logger
logger
{-# INLINABLE runScript #-}