Debian Codegraph @

Web/Scotty/Internal/Types.hs

raw
1 {-# LANGUAGE DeriveDataTypeable #-}
2 {-# LANGUAGE DerivingStrategies #-}
3 {-# LANGUAGE FlexibleInstances #-}
4 {-# LANGUAGE GeneralizedNewtypeDeriving #-}
5 {-# LANGUAGE MultiParamTypeClasses #-}
6 {-# language ScopedTypeVariables #-}
7 {-# LANGUAGE TypeFamilies #-}
8 {-# LANGUAGE UndecidableInstances #-}
9 {-# LANGUAGE RecordWildCards #-}
10 module Web.Scotty.Internal.Types where
11
12 import Blaze.ByteString.Builder (Builder)
13
14 import Control.Applicative
15 import Control.Concurrent.MVar
16 import Control.Concurrent.STM (TVar, atomically, readTVarIO, modifyTVar')
17 import qualified Control.Exception as E
18 import Control.Monad (MonadPlus(..))
19 import Control.Monad.Base (MonadBase)
20 import Control.Monad.Catch (MonadCatch, MonadThrow)
21 import Control.Monad.Error.Class (MonadError(..))
22 import Control.Monad.IO.Class (MonadIO(..))
23 import UnliftIO (MonadUnliftIO(..))
24 import Control.Monad.Reader (MonadReader(..), ReaderT, asks, mapReaderT)
25 import Control.Monad.State.Strict (State, StateT(..))
26 import Control.Monad.Trans.Class (MonadTrans(..))
27 import Control.Monad.Trans.Control (MonadBaseControl, MonadTransControl)
28 import qualified Control.Monad.Trans.Resource as RT (InternalState, InvalidAccess)
29
30 import qualified Data.ByteString as BS
31 import qualified Data.ByteString.Lazy.Char8 as LBS8 (ByteString)
32 import Data.Default.Class (Default, def)
33 import Data.String (IsString(..))
34 import qualified Data.Text as T (Text, pack)
35 import Data.Typeable (Typeable)
36
37 import Network.HTTP.Types
38
39 import Network.Wai hiding (Middleware, Application)
40 import qualified Network.Wai as Wai
41 import qualified Network.Wai.Handler.Warp as W (Settings, defaultSettings, InvalidRequest(..))
42 import Network.Wai.Parse (FileInfo)
43 import qualified Network.Wai.Parse as WPS (ParseRequestBodyOptions, RequestParseException(..))
44
45 import UnliftIO.Exception (Handler(..), catch, catches)
46
47
48
49
50 --------------------- Options -----------------------
51 data Options = Options { verbose :: Int -- ^ 0 = silent, 1(def) = startup banner
52 , settings :: W.Settings -- ^ Warp 'Settings'
53 -- Note: to work around an issue in warp,
54 -- the default FD cache duration is set to 0
55 -- so changes to static files are always picked
56 -- up. This likely has performance implications,
57 -- so you may want to modify this for production
58 -- servers using `setFdCacheDuration`.
59 }
60
61 instance Default Options where
62 def = defaultOptions
63
64 defaultOptions :: Options
65 defaultOptions = Options 1 W.defaultSettings
66
67 newtype RouteOptions = RouteOptions { maxRequestBodySize :: Maybe Kilobytes -- max allowed request size in KB
68 }
69
70 instance Default RouteOptions where
71 def = defaultRouteOptions
72
73 defaultRouteOptions :: RouteOptions
74 defaultRouteOptions = RouteOptions Nothing
75
76 type Kilobytes = Int
77 ----- Transformer Aware Applications/Middleware -----
78 type Middleware m = Application m -> Application m
79 type Application m = Request -> m Response
80
81 ------------------ Scotty Request Body --------------------
82
83 data BodyChunkBuffer = BodyChunkBuffer { hasFinishedReadingChunks :: Bool -- ^ whether we've reached the end of the stream yet
84 , chunksReadSoFar :: [BS.ByteString]
85 }
86 -- | The key part of having two MVars is that we can "clone" the BodyInfo to create a copy where the index is reset to 0, but the chunk cache is the same. Passing a cloned BodyInfo into each matched route allows them each to start from the first chunk if they call bodyReader.
87 --
88 -- Introduced in (#308)
89 data BodyInfo = BodyInfo { bodyInfoReadProgress :: MVar Int -- ^ index into the stream read so far
90 , bodyInfoChunkBuffer :: MVar BodyChunkBuffer
91 , bodyInfoDirectChunkRead :: IO BS.ByteString -- ^ can be called to get more chunks
92 }
93
94 --------------- Scotty Applications -----------------
95
96 data ScottyState m =
97 ScottyState { middlewares :: [Wai.Middleware]
98 , routes :: [BodyInfo -> Middleware m]
99 , handler :: Maybe (ErrorHandler m)
100 , routeOptions :: RouteOptions
101 }
102
103 -- instance Default (ScottyState m) where
104 -- def = defaultScottyState
105
106 defaultScottyState :: ScottyState m
107 defaultScottyState = ScottyState [] [] Nothing defaultRouteOptions
108
109 addMiddleware :: Wai.Middleware -> ScottyState m -> ScottyState m
110 addMiddleware m s@(ScottyState {middlewares = ms}) = s { middlewares = m:ms }
111
112 addRoute :: (BodyInfo -> Middleware m) -> ScottyState m -> ScottyState m
113 addRoute r s@(ScottyState {routes = rs}) = s { routes = r:rs }
114
115 setHandler :: Maybe (ErrorHandler m) -> ScottyState m -> ScottyState m
116 setHandler h s = s { handler = h }
117
118 updateMaxRequestBodySize :: RouteOptions -> ScottyState m -> ScottyState m
119 updateMaxRequestBodySize RouteOptions { .. } s@ScottyState { routeOptions = ro } =
120 let ro' = ro { maxRequestBodySize = maxRequestBodySize }
121 in s { routeOptions = ro' }
122
123 newtype ScottyT m a =
124 ScottyT { runS :: ReaderT Options (State (ScottyState m)) a }
125 deriving ( Functor, Applicative, Monad )
126
127
128 ------------------ Scotty Errors --------------------
129
130 -- | Internal exception mechanism used to modify the request processing flow.
131 --
132 -- The exception constructor is not exposed to the user and all exceptions of this type are caught
133 -- and processed within the 'runAction' function.
134 data ActionError
135 = AERedirect T.Text -- ^ Redirect
136 | AENext -- ^ Stop processing this route and skip to the next one
137 | AEFinish -- ^ Stop processing the request
138 deriving (Show, Typeable)
139 instance E.Exception ActionError
140
141 tryNext :: MonadUnliftIO m => m a -> m Bool
142 tryNext io = catch (io >> pure True) $ \e ->
143 case e of
144 AENext -> pure False
145 _ -> pure True
146
147 -- | E.g. when a parameter is not found in a query string (400 Bad Request) or when parsing a JSON body fails (422 Unprocessable Entity)
148 data StatusError = StatusError Status T.Text deriving (Show, Typeable)
149 instance E.Exception StatusError
150 {-# DEPRECATED StatusError "If it is supposed to be caught, a proper exception type should be defined" #-}
151
152 -- | Specializes a 'Handler' to the 'ActionT' monad
153 type ErrorHandler m = Handler (ActionT m) ()
154
155 -- | Thrown e.g. when a request is too large
156 data ScottyException
157 = RequestTooLarge
158 | MalformedJSON LBS8.ByteString T.Text
159 | FailedToParseJSON LBS8.ByteString T.Text
160 | PathParameterNotFound T.Text
161 | QueryParameterNotFound T.Text
162 | FormFieldNotFound T.Text
163 | FailedToParseParameter T.Text T.Text T.Text
164 | WarpRequestException W.InvalidRequest
165 | WaiRequestParseException WPS.RequestParseException -- request parsing
166 | ResourceTException RT.InvalidAccess -- use after free
167 deriving (Show, Typeable)
168 instance E.Exception ScottyException
169
170 ------------------ Scotty Actions -------------------
171 type Param = (T.Text, T.Text)
172
173 -- | Type parameter @t@ is the file content. Could be @()@ when not needed or a @FilePath@ for temp files instead.
174 type File t = (T.Text, FileInfo t)
175
176 data ActionEnv = Env { envReq :: Request
177 , envPathParams :: [Param]
178 , envQueryParams :: [Param]
179 , envFormDataAction :: RT.InternalState -> WPS.ParseRequestBodyOptions -> IO ([Param], [File FilePath])
180 , envBody :: IO LBS8.ByteString
181 , envBodyChunk :: IO BS.ByteString
182 , envResponse :: TVar ScottyResponse
183 }
184
185
186
187
188 formParamsAndFilesWith :: MonadUnliftIO m =>
189 RT.InternalState
190 -> WPS.ParseRequestBodyOptions
191 -> ActionT m ([Param], [File FilePath])
192 formParamsAndFilesWith istate prbo = action `catch` (\(e :: RT.InvalidAccess) -> E.throw $ ResourceTException e)
193 where
194 action = do
195 act <- ActionT $ asks envFormDataAction
196 liftIO $ act istate prbo
197
198 getResponse :: MonadIO m => ActionEnv -> m ScottyResponse
199 getResponse ae = liftIO $ readTVarIO (envResponse ae)
200
201 getResponseAction :: (MonadIO m) => ActionT m ScottyResponse
202 getResponseAction = do
203 ae <- ActionT ask
204 getResponse ae
205
206 modifyResponse :: (MonadIO m) => (ScottyResponse -> ScottyResponse) -> ActionT m ()
207 modifyResponse f = do
208 tv <- ActionT $ asks envResponse
209 liftIO $ atomically $ modifyTVar' tv f
210
211 data BodyPartiallyStreamed = BodyPartiallyStreamed deriving (Show, Typeable)
212
213 instance E.Exception BodyPartiallyStreamed
214
215 data Content = ContentBuilder Builder
216 | ContentFile FilePath
217 | ContentStream StreamingBody
218 | ContentResponse Response
219
220 data ScottyResponse = SR { srStatus :: Status
221 , srHeaders :: ResponseHeaders
222 , srContent :: Content
223 }
224
225 setContent :: Content -> ScottyResponse -> ScottyResponse
226 setContent c sr = sr { srContent = c }
227
228 setHeaderWith :: ([(HeaderName, BS.ByteString)] -> [(HeaderName, BS.ByteString)]) -> ScottyResponse -> ScottyResponse
229 setHeaderWith f sr = sr { srHeaders = f (srHeaders sr) }
230
231 setStatus :: Status -> ScottyResponse -> ScottyResponse
232 setStatus s sr = sr { srStatus = s }
233
234 instance Default ScottyResponse where
235 def = defaultScottyResponse
236
237 -- | The default response has code 200 OK and empty body
238 defaultScottyResponse :: ScottyResponse
239 defaultScottyResponse = SR status200 [] (ContentBuilder mempty)
240
241
242 newtype ActionT m a = ActionT { runAM :: ReaderT ActionEnv m a }
243 deriving newtype (Functor, Applicative, Monad, MonadIO, MonadTrans, MonadThrow, MonadCatch, MonadBase b, MonadBaseControl b, MonadTransControl, MonadUnliftIO)
244
245 withActionEnv :: Monad m =>
246 (ActionEnv -> ActionEnv) -> ActionT m a -> ActionT m a
247 withActionEnv f (ActionT r) = ActionT $ local f r
248
249 instance MonadReader r m => MonadReader r (ActionT m) where
250 ask = ActionT $ lift ask
251 local f = ActionT . mapReaderT (local f) . runAM
252
253 -- | Models the invariant that only 'StatusError's can be thrown and caught.
254 instance (MonadUnliftIO m) => MonadError StatusError (ActionT m) where
255 throwError = E.throw
256 catchError = catch
257 -- | Modeled after the behaviour in scotty < 0.20, 'fail' throws a 'StatusError' with code 500 ("Server Error"), which can be caught with 'E.catch'.
258 instance (MonadIO m) => MonadFail (ActionT m) where
259 fail = E.throw . StatusError status500 . T.pack
260 -- | 'empty' throws 'ActionError' 'AENext', whereas '(<|>)' catches any 'ActionError's or 'StatusError's in the first action and proceeds to the second one.
261 instance (MonadUnliftIO m) => Alternative (ActionT m) where
262 empty = E.throw AENext
263 a <|> b = do
264 ok <- tryAnyStatus a
265 if ok then a else b
266 instance (MonadUnliftIO m) => MonadPlus (ActionT m) where
267 mzero = empty
268 mplus = (<|>)
269
270 -- | catches either ActionError (thrown by 'next'),
271 -- 'ScottyException' (thrown if e.g. a query parameter is not found)
272 -- or 'StatusError' (via 'raiseStatus')
273 tryAnyStatus :: MonadUnliftIO m => m a -> m Bool
274 tryAnyStatus io = (io >> pure True) `catches` [h1, h2, h3]
275 where
276 h1 = Handler $ \(_ :: ActionError) -> pure False
277 h2 = Handler $ \(_ :: StatusError) -> pure False
278 h3 = Handler $ \(_ :: ScottyException) -> pure False
279
280 instance (Semigroup a) => Semigroup (ScottyT m a) where
281 x <> y = (<>) <$> x <*> y
282
283 instance
284 ( Monoid a
285 ) => Monoid (ScottyT m a) where
286 mempty = return mempty
287
288 instance
289 ( Monad m
290 , Semigroup a
291 ) => Semigroup (ActionT m a) where
292 x <> y = (<>) <$> x <*> y
293
294 instance
295 ( Monad m, Monoid a
296 ) => Monoid (ActionT m a) where
297 mempty = return mempty
298
299 ------------------ Scotty Routes --------------------
300 data RoutePattern = Capture T.Text
301 | Literal T.Text
302 | Function (Request -> Maybe [Param])
303
304 instance IsString RoutePattern where
305 fromString = Capture . T.pack
306
307