Skip to content
This repository
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 572 lines (490 sloc) 22.35 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE BangPatterns #-}

module Snap.Snaplet.Internal.Initializer
  ( addPostInitHook
  , addPostInitHookBase
  , toSnapletHook
  , bracketInit
  , modifyCfg
  , nestSnaplet
  , embedSnaplet
  , makeSnaplet
  , nameSnaplet
  , onUnload
  , addRoutes
  , wrapSite
  , runInitializer
  , runSnaplet
  , combineConfig
  , serveSnaplet
  , printInfo
  ) where

import Prelude hiding (catch)
import Control.Concurrent.MVar
import Control.Error
import Control.Exception (SomeException)
import Control.Lens
import Control.Monad
import Control.Monad.CatchIO hiding (Handler)
import Control.Monad.Reader
import Control.Monad.State
import Control.Monad.Trans.Writer hiding (pass)
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as B
import Data.Configurator
import Data.IORef
import Data.Maybe
import Data.Text (Text)
import qualified Data.Text as T
import Snap.Http.Server
import Snap.Core
import Snap.Util.GZip
import System.Directory
import System.Directory.Tree
import System.FilePath.Posix
import System.IO

import Snap.Snaplet.Config
import qualified Snap.Snaplet.Internal.LensT as LT
import qualified Snap.Snaplet.Internal.Lensed as L
import Snap.Snaplet.Internal.Types


------------------------------------------------------------------------------
-- | 'get' for InitializerState.
iGet :: Initializer b v (InitializerState b)
iGet = Initializer $ LT.getBase


------------------------------------------------------------------------------
-- | 'modify' for InitializerState.
iModify :: (InitializerState b -> InitializerState b) -> Initializer b v ()
iModify f = Initializer $ do
    b <- LT.getBase
    LT.putBase $ f b


------------------------------------------------------------------------------
-- | 'gets' for InitializerState.
iGets :: (InitializerState b -> a) -> Initializer b v a
iGets f = Initializer $ do
    b <- LT.getBase
    return $ f b


------------------------------------------------------------------------------
-- | Converts a plain hook into a Snaplet hook.
toSnapletHook :: (v -> EitherT Text IO v)
              -> (Snaplet v -> EitherT Text IO (Snaplet v))
toSnapletHook f (Snaplet cfg val) = do
    val' <- f val
    return $! Snaplet cfg val'


------------------------------------------------------------------------------
-- | Adds an IO action that modifies the current snaplet state to be run at
-- the end of initialization on the state that was created. This makes it
-- easier to allow one snaplet's state to be modified by another snaplet's
-- initializer. A good example of this is when a snaplet has templates that
-- define its views. The Heist snaplet provides the 'addTemplates' function
-- which allows other snaplets to set up their own templates. 'addTemplates'
-- is implemented using this function.
addPostInitHook :: (v -> EitherT Text IO v)
                -> Initializer b v ()
addPostInitHook = addPostInitHook' . toSnapletHook


addPostInitHook' :: (Snaplet v -> EitherT Text IO (Snaplet v))
                 -> Initializer b v ()
addPostInitHook' h = do
    h' <- upHook h
    addPostInitHookBase h'


------------------------------------------------------------------------------
-- | Variant of addPostInitHook for when you have things wrapped in a Snaplet.
addPostInitHookBase :: (Snaplet b -> EitherT Text IO (Snaplet b))
                    -> Initializer b v ()
addPostInitHookBase = Initializer . lift . tell . Hook


------------------------------------------------------------------------------
-- | Helper function for transforming hooks.
upHook :: (Snaplet v -> EitherT Text IO (Snaplet v))
       -> Initializer b v (Snaplet b -> EitherT Text IO (Snaplet b))
upHook h = Initializer $ do
    l <- ask
    return $ upHook' l h


------------------------------------------------------------------------------
-- | Helper function for transforming hooks.
upHook' :: Monad m => SimpleLoupe b a -> (a -> m a) -> b -> m b
upHook' l h b = do
    v <- h (b ^# l)
    return $ storing l v b


------------------------------------------------------------------------------
-- | Modifies the Initializer's SnapletConfig.
modifyCfg :: (SnapletConfig -> SnapletConfig) -> Initializer b v ()
modifyCfg f = iModify $ over curConfig $ \c -> f c


------------------------------------------------------------------------------
-- | If a snaplet has a filesystem presence, this function creates and copies
-- the files if they dont' already exist.
setupFilesystem :: Maybe (IO FilePath)
                    -- ^ The directory where the snaplet's reference files are
                    -- stored. Nothing if the snaplet doesn't come with any
                    -- files that need to be installed.
                -> FilePath
                    -- ^ Directory where the files should be copied.
                -> Initializer b v ()
setupFilesystem Nothing _ = return ()
setupFilesystem (Just getSnapletDataDir) targetDir = do
    exists <- liftIO $ doesDirectoryExist targetDir
    unless exists $ do
        printInfo "...setting up filesystem"
        liftIO $ createDirectoryIfMissing True targetDir
        srcDir <- liftIO getSnapletDataDir
        liftIO $ readDirectoryWith (doCopy srcDir targetDir) srcDir
        return ()
  where
    doCopy srcRoot targetRoot filename = do
        createDirectoryIfMissing True directory
        copyFile filename toDir
      where
        toDir = targetRoot </> makeRelative srcRoot filename
        directory = dropFileName toDir


------------------------------------------------------------------------------
-- | All snaplet initializers must be wrapped in a call to @makeSnaplet@,
-- which handles standardized housekeeping common to all snaplets.
-- Common usage will look something like
-- this:
--
-- @
-- fooInit :: SnapletInit b Foo
-- fooInit = makeSnaplet \"foo\" \"An example snaplet\" Nothing $ do
-- -- Your initializer code here
-- return $ Foo 42
-- @
--
-- Note that you're writing your initializer code in the Initializer monad,
-- and makeSnaplet converts it into an opaque SnapletInit type. This allows
-- us to use the type system to ensure that the API is used correctly.
makeSnaplet :: Text
                -- ^ A default id for this snaplet. This is only used when
                -- the end-user has not already set an id using the
                -- nameSnaplet function.
            -> Text
                -- ^ A human readable description of this snaplet.
            -> Maybe (IO FilePath)
                -- ^ The path to the directory holding the snaplet's reference
                -- filesystem content. This will almost always be the
                -- directory returned by Cabal's getDataDir command, but it
                -- has to be passed in because it is defined in a
                -- package-specific import. Setting this value to Nothing
                -- doesn't preclude the snaplet from having files in in the
                -- filesystem, it just means that they won't be copied there
                -- automatically.
            -> Initializer b v v
                -- ^ Snaplet initializer.
            -> SnapletInit b v
makeSnaplet snapletId desc getSnapletDataDir m = SnapletInit $ do
    modifyCfg $ \c -> if isNothing $ _scId c
        then set scId (Just snapletId) c else c
    sid <- iGets (T.unpack . fromJust . _scId . _curConfig)
    topLevel <- iGets _isTopLevel
    unless topLevel $ do
        modifyCfg $ over scUserConfig (subconfig (T.pack sid))
        modifyCfg $ \c -> set scFilePath
          (_scFilePath c </> "snaplets" </> sid) c
    iModify (set isTopLevel False)
    modifyCfg $ set scDescription desc
    cfg <- iGets _curConfig
    printInfo $ T.pack $ concat
      ["Initializing "
      ,sid
      ," @ /"
      ,B.unpack $ buildPath $ _scRouteContext cfg
      ]

    -- This has to happen here because it needs to be after scFilePath is set
    -- up but before the config file is read.
    setupFilesystem getSnapletDataDir (_scFilePath cfg)

    env <- iGets _environment
    let configLocation = _scFilePath cfg </> (env ++ ".cfg")
    liftIO $ addToConfig [Optional configLocation]
                         (_scUserConfig cfg)
    mkSnaplet m


------------------------------------------------------------------------------
-- | Internal function that gets the SnapletConfig out of the initializer
-- state and uses it to create a (Snaplet a).
mkSnaplet :: Initializer b v a -> Initializer b v (Snaplet a)
mkSnaplet m = do
    res <- m
    cfg <- iGets _curConfig
    return $ Snaplet cfg res


------------------------------------------------------------------------------
-- | Brackets an initializer computation, restoring curConfig after the
-- computation returns.
bracketInit :: Initializer b v a -> Initializer b v a
bracketInit m = do
    s <- iGet
    res <- m
    iModify (set curConfig (_curConfig s))
    return res


------------------------------------------------------------------------------
-- | Handles modifications to InitializerState that need to happen before a
-- snaplet is called with either nestSnaplet or embedSnaplet.
setupSnapletCall :: ByteString -> Initializer b v ()
setupSnapletCall rte = do
    curId <- iGets (fromJust . _scId . _curConfig)
    modifyCfg (over scAncestry (curId:))
    modifyCfg (over scId (const Nothing))
    unless (B.null rte) $ modifyCfg (over scRouteContext (rte:))


------------------------------------------------------------------------------
-- | Runs another snaplet's initializer and returns the initialized Snaplet
-- value. Calling an initializer with nestSnaplet gives the nested snaplet
-- access to the same base state that the current snaplet has. This makes it
-- possible for the child snaplet to make use of functionality provided by
-- sibling snaplets.
nestSnaplet :: ByteString
                -- ^ The root url for all the snaplet's routes. An empty
                -- string gives the routes the same root as the parent
                -- snaplet's routes.
            -> SnapletLens v v1
                -- ^ Lens identifying the snaplet
            -> SnapletInit b v1
                -- ^ The initializer function for the subsnaplet.
            -> Initializer b v (Snaplet v1)
nestSnaplet rte l (SnapletInit snaplet) =
    with l $ bracketInit $ do
        setupSnapletCall rte
        snaplet


------------------------------------------------------------------------------
-- | Runs another snaplet's initializer and returns the initialized Snaplet
-- value. The difference between this and nestSnaplet is the first type
-- parameter in the third argument. The \"v1 v1\" makes the child snaplet
-- think that it is top-level, which means that it will not be able to use
-- functionality provided by snaplets included above it in the snaplet tree.
-- This strongly isolates the child snaplet, and allows you to eliminate the b
-- type variable. The embedded snaplet can still get functionality from other
-- snaplets, but only if it nests or embeds the snaplet itself.
embedSnaplet :: ByteString
                 -- ^ The root url for all the snaplet's routes. An empty
                 -- string gives the routes the same root as the parent
                 -- snaplet's routes.
                 --
                 -- NOTE: Because of the stronger isolation provided by
                 -- embedSnaplet, you should be more careful about using an
                 -- empty string here.
             -> SnapletLens v v1
                -- ^ Lens identifying the snaplet
             -> SnapletInit v1 v1
                -- ^ The initializer function for the subsnaplet.
             -> Initializer b v (Snaplet v1)
embedSnaplet rte l (SnapletInit snaplet) = bracketInit $ do
    curLens <- getLens
    setupSnapletCall ""
    chroot rte (cloneLens curLens . subSnaplet l) snaplet


------------------------------------------------------------------------------
-- | Changes the base state of an initializer.
chroot :: ByteString
       -> SnapletLens (Snaplet b) v1
       -> Initializer v1 v1 a
       -> Initializer b v a
chroot rte l (Initializer m) = do
    curState <- iGet
    ((a,s), (Hook hook)) <- liftIO $ runWriterT $ LT.runLensT m id $
        curState {
          _handlers = [],
          _hFilter = id
        }
    let handler = chrootHandler l $ _hFilter s $ route $ _handlers s
    iModify $ over handlers (++[(rte,handler)])
            . set cleanup (_cleanup s)
    addPostInitHookBase $ upHook' l hook
    return a


------------------------------------------------------------------------------
-- | Changes the base state of a handler.
chrootHandler :: SnapletLens (Snaplet v) b'
              -> Handler b' b' a -> Handler b v a
chrootHandler l (Handler h) = Handler $ do
    s <- get
    (a, s') <- liftSnap $ L.runLensed h id (s ^# l)
    modify $ storing l s'
    return a


------------------------------------------------------------------------------
-- | Sets a snaplet's name. All snaplets have a default name set by the
-- snaplet author. This function allows you to override that name. You will
-- have to do this if you have more than one instance of the same kind of
-- snaplet because snaplet names must be unique. This function must
-- immediately surround the snaplet's initializer. For example:
--
-- @fooState <- nestSnaplet \"fooA\" $ nameSnaplet \"myFoo\" $ fooInit@
nameSnaplet :: Text
                -- ^ The snaplet name
            -> SnapletInit b v
                -- ^ The snaplet initializer function
            -> SnapletInit b v
nameSnaplet nm (SnapletInit m) = SnapletInit $
    modifyCfg (set scId (Just nm)) >> m


------------------------------------------------------------------------------
-- | Adds routing to the current 'Handler'. The new routes are merged with
-- the main routing section and take precedence over existing routing that was
-- previously defined.
addRoutes :: [(ByteString, Handler b v ())]
           -> Initializer b v ()
addRoutes rs = do
    l <- getLens
    ctx <- iGets (_scRouteContext . _curConfig)
    let modRoute (r,h) = ( buildPath (r:ctx)
                         , setPattern r >> withTop' l h)
    let rs' = map modRoute rs
    iModify (\v -> over handlers (++rs') v)
  where
    setPattern r = do
      p <- getRoutePattern
      when (isNothing p) $ setRoutePattern r


------------------------------------------------------------------------------
-- | Wraps the /base/ snaplet's routing in another handler, allowing you to run
-- code before and after all routes in an application.
--
-- Here are some examples of things you might do:
--
-- > wrapSite (\site -> logHandlerStart >> site >> logHandlerFinished)
-- > wrapSite (\site -> ensureAdminUser >> site)
--
wrapSite :: (Handler b v () -> Handler b v ())
             -- ^ Handler modifier function
         -> Initializer b v ()
wrapSite f0 = do
    f <- mungeFilter f0
    iModify (\v -> over hFilter (f.) v)


------------------------------------------------------------------------------
mungeFilter :: (Handler b v () -> Handler b v ())
            -> Initializer b v (Handler b b () -> Handler b b ())
mungeFilter f = do
    myLens <- Initializer ask
    return $ \m -> with' myLens $ f' m
  where
    f' (Handler m) = f $ Handler $ L.withTop id m


------------------------------------------------------------------------------
-- | Attaches an unload handler to the snaplet. The unload handler will be
-- called when the server shuts down, or is reloaded.
onUnload :: IO () -> Initializer b v ()
onUnload m = do
    cleanupRef <- iGets _cleanup
    liftIO $ atomicModifyIORef cleanupRef f
  where
    f curCleanup = (curCleanup >> m, ())


------------------------------------------------------------------------------
-- |
logInitMsg :: IORef Text -> Text -> IO ()
logInitMsg ref msg = atomicModifyIORef ref (\cur -> (cur `T.append` msg, ()))


------------------------------------------------------------------------------
-- | Initializers should use this function for all informational or error
-- messages to be displayed to the user. On application startup they will be
-- sent to the console. When executed from the reloader, they will be sent
-- back to the user in the HTTP response.
printInfo :: Text -> Initializer b v ()
printInfo msg = do
    logRef <- iGets _initMessages
    liftIO $ logInitMsg logRef (msg `T.append` "\n")


------------------------------------------------------------------------------
-- | Builds an IO reload action for storage in the SnapletState.
mkReloader :: FilePath
           -> String
           -> MVar (Snaplet b)
           -> IORef (IO ())
           -> Initializer b b (Snaplet b)
           -> IO (Either Text Text)
mkReloader cwd env mvar cleanupRef i = do
    join $ readIORef cleanupRef
    !res <- runInitializer' mvar env i cwd
    either (return . Left) good res
  where
    good (b,is) = do
        _ <- swapMVar mvar b
        msgs <- readIORef $ _initMessages is
        return $ Right msgs


------------------------------------------------------------------------------
-- | Runs a top-level snaplet in the Snap monad.
runBase :: Handler b b a
        -> MVar (Snaplet b)
        -> Snap a
runBase (Handler m) mvar = do
    !b <- liftIO (readMVar mvar)
    (!a, _) <- L.runLensed m id b
    return $! a


------------------------------------------------------------------------------
-- | Internal function for running Initializers. If any exceptions were
-- thrown by the initializer, this function catches them, runs any cleanup
-- actions that had been registered, and returns an expanded error message
-- containing the exception details as well as all messages generated by the
-- initializer before the exception was thrown.
runInitializer :: MVar (Snaplet b)
               -> String
               -> Initializer b b (Snaplet b)
               -> IO (Either Text (Snaplet b, InitializerState b))
runInitializer mvar env b =
    getCurrentDirectory >>= runInitializer' mvar env b


------------------------------------------------------------------------------
runInitializer' :: MVar (Snaplet b)
                -> String
                -> Initializer b b (Snaplet b)
                -> FilePath
                -> IO (Either Text (Snaplet b, InitializerState b))
runInitializer' mvar env b@(Initializer i) cwd = do
    cleanupRef <- newIORef (return ())
    let builtinHandlers = [("/admin/reload", reloadSite)]
    let cfg = SnapletConfig [] cwd Nothing "" empty [] Nothing
                            (mkReloader cwd env mvar cleanupRef b)
    logRef <- newIORef ""

    let body = runEitherT $ do
            ((res, s), (Hook hook)) <- lift $ runWriterT $ LT.runLensT i id $
                InitializerState True cleanupRef builtinHandlers id cfg logRef
                                 env
            res' <- hook res
            right (res', s)

        handler e = do
            join $ readIORef cleanupRef
            logMessages <- readIORef logRef

            return $ Left $ T.unlines
                [ "Initializer threw an exception..."
                , T.pack $ show (e :: SomeException)
                , ""
                , "...but before it died it generated the following output:"
                , logMessages
                ]

    catch body handler


------------------------------------------------------------------------------
-- | Given an environment and a Snaplet initializer, produce a concatenated log
-- of all messages generated during initialization, a snap handler, and a
-- cleanup action. The environment is an arbitrary string such as \"devel\" or
-- \"production\". This string is used to determine the name of the
-- configuration files used by each snaplet. If an environment of Nothing is
-- used, then runSnaplet defaults to \"devel\".
runSnaplet :: Maybe String -> SnapletInit b b -> IO (Text, Snap (), IO ())
runSnaplet env (SnapletInit b) = do
    snapletMVar <- newEmptyMVar
    eRes <- runInitializer snapletMVar (fromMaybe "devel" env) b
    let go (siteSnaplet,is) = do
        putMVar snapletMVar siteSnaplet
        msgs <- liftIO $ readIORef $ _initMessages is
        let handler = runBase (_hFilter is $ route $ _handlers is) snapletMVar
        cleanupAction <- readIORef $ _cleanup is
        return (msgs, handler, cleanupAction)
    either (error . ('\n':) . T.unpack) go eRes


------------------------------------------------------------------------------
-- | Given a configuration and a snap handler, complete it and produce the
-- completed configuration as well as a new toplevel handler with things like
-- compression and a 500 handler set up.
combineConfig :: Config Snap a -> Snap () -> IO (Config Snap a, Snap ())
combineConfig config handler = do
    conf <- completeConfig config

    let catch500 = (flip catch $ fromJust $ getErrorHandler conf)
    let compress = if fromJust (getCompression conf)
                     then withCompression else id
    let site = compress $ catch500 handler

    return (conf, site)


------------------------------------------------------------------------------
-- | Initialize and run a Snaplet. This function parses command-line arguments,
-- runs the given Snaplet initializer, and starts an HTTP server running the
-- Snaplet's toplevel 'Handler'.
serveSnaplet :: Config Snap AppConfig
                 -- ^ The configuration of the server - you can usually pass a
                 -- default 'Config' via
                 -- 'Snap.Http.Server.Config.defaultConfig'.
             -> SnapletInit b b
                 -- ^ The snaplet initializer function.
             -> IO ()
serveSnaplet startConfig initializer = do
    config <- commandLineAppConfig startConfig
    let env = appEnvironment =<< getOther config
    (msgs, handler, doCleanup) <- runSnaplet env initializer

    (conf, site) <- combineConfig config handler
    createDirectoryIfMissing False "log"
    let serve = simpleHttpServe conf

    liftIO $ hPutStrLn stderr $ T.unpack msgs
    _ <- try $ serve $ site
         :: IO (Either SomeException ())
    doCleanup


Something went wrong with that request. Please try again.