/
Servant.hs
167 lines (150 loc) · 5.22 KB
/
Servant.hs
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
{-# OPTIONS_GHC -fno-warn-orphans #-}
module App.Servant (main) where
import App.AppEnv (AppEnv (appEnvConfig, appEnvHttpConfig), appEnvInit)
import App.Cart
( BookingId,
CartException (CartException),
CartId (CartId),
CartStatus (CartStatusLocked, CartStatusOpen, CartStatusPurchased),
PaymentId,
getCartStatus,
markCartAsPurchased,
processBooking,
processPayment,
withCart,
)
import App.Config (Config (configPurchaseDelay))
import App.Json (defaultToJSON)
import App.Logging (monadLoggerLogImpl)
import Blammo.Logging
( Message ((:#)),
MonadLogger (monadLoggerLog),
logInfo,
logWarn,
(.=),
)
import Control.Concurrent (threadDelay)
import Control.Monad.Except (ExceptT (ExceptT))
import Control.Monad.IO.Class (MonadIO (liftIO))
import Control.Monad.Reader (MonadReader, ReaderT, asks, runReaderT)
import Data.Aeson (ToJSON (toJSON), encode, object)
import Data.Text (Text)
import GHC.Generics (Generic)
import Network.HTTP.Req
( MonadHttp (getHttpConfig, handleHttpException),
)
import Network.Wai.Handler.Warp (run)
import Servant
( Capture,
Context (EmptyContext, (:.)),
ErrorFormatters (notFoundErrorFormatter),
FromHttpApiData,
Handler (Handler),
HasServer (ServerT),
JSON,
Post,
Proxy (Proxy),
ServerError (errBody, errHeaders),
defaultErrorFormatters,
err404,
err409,
err500,
hoistServer,
serveWithContext,
(:>),
)
import Servant.Server (NotFoundErrorFormatter)
import UnliftIO (MonadUnliftIO)
import UnliftIO.Async (concurrently)
import UnliftIO.Exception (catch, throwIO, try)
newtype App a = App
{ unApp :: ReaderT AppEnv IO a
}
deriving (Functor, Applicative, Monad, MonadReader AppEnv, MonadIO, MonadUnliftIO)
instance MonadLogger App where
monadLoggerLog = monadLoggerLogImpl
instance MonadHttp App where
handleHttpException = throwIO
getHttpConfig = asks appEnvHttpConfig
appToHandler :: AppEnv -> App a -> Handler a
appToHandler app m =
Handler $ ExceptT $ try $ runReaderT (unApp m) app
type Api = "cart" :> Capture "cartId" CartId :> "purchase" :> Post '[JSON] CartPurchaseResponse
deriving instance FromHttpApiData CartId
data CartPurchaseResponse = CartPurchaseResponse
{ cartPurchaseResponseCartId :: CartId,
cartPurchaseResponsePurchaseDelay :: Int,
cartPurchaseResponseBookingId :: BookingId,
cartPurchaseResponsePaymentId :: PaymentId
}
deriving (Generic)
instance ToJSON CartPurchaseResponse where
toJSON = defaultToJSON "cartPurchaseResponse"
postCartPurchaseHandler :: CartId -> App CartPurchaseResponse
postCartPurchaseHandler cartId = do
cartStatusMaybe <- getCartStatus cartId
case cartStatusMaybe of
Nothing -> do
logWarn $ "Cart does not exist" :# ["cart_id" .= cartId]
throwIO $ jsonError err404 "Cart does not exist"
Just CartStatusPurchased -> do
logWarn $ "Cart already purchased" :# ["cart_id" .= cartId]
throwIO $ jsonError err409 "Cart already purchased"
Just CartStatusLocked -> do
logWarn $ "Cart locked" :# ["cart_id" .= cartId]
throwIO $ jsonError err409 "Cart locked"
Just CartStatusOpen -> do
withCart cartId $ do
logInfo $ "Cart purchase starting" :# ["cart_id" .= cartId]
let action :: App (Either Text (BookingId, PaymentId))
action = Right <$> concurrently (processBooking cartId) (processPayment cartId)
handleError :: CartException -> App (Either Text (BookingId, PaymentId))
handleError (CartException msg) = pure $ Left msg
result <- catch action handleError
case result of
Left msg -> do
logWarn $ ("Cart purchase failed: " <> msg) :# ["cart_id" .= cartId]
throwIO $ jsonError err500 ("Cart purchase failed: " <> msg)
Right (bookingId, paymentId) -> do
purchaseDelay <- asks (configPurchaseDelay . appEnvConfig)
liftIO $ threadDelay purchaseDelay
markCartAsPurchased cartId
logInfo $ "Cart purchase successful" :# ["cart_id" .= cartId]
pure $
CartPurchaseResponse
{ cartPurchaseResponseCartId = cartId,
cartPurchaseResponsePurchaseDelay = purchaseDelay,
cartPurchaseResponseBookingId = bookingId,
cartPurchaseResponsePaymentId = paymentId
}
jsonError :: ServerError -> Text -> ServerError
jsonError err msg =
err
{ errBody = encode $ object ["error" .= msg],
errHeaders = [("Content-Type", "application/json")]
}
notFoundFormatter :: NotFoundErrorFormatter
notFoundFormatter _ =
let msg :: Text
msg = "Path not found"
in err404
{ errBody = encode $ object ["error" .= msg],
errHeaders = [("Content-Type", "application/json")]
}
customErrorFormatters :: ErrorFormatters
customErrorFormatters =
defaultErrorFormatters
{ notFoundErrorFormatter = notFoundFormatter
}
server :: ServerT Api App
server = postCartPurchaseHandler
api :: Proxy Api
api = Proxy
main :: IO ()
main = do
app <- appEnvInit
let port = 3000
hoistedServer = hoistServer api (appToHandler app) server
context = customErrorFormatters :. EmptyContext
waiApp = serveWithContext api context hoistedServer
run port waiApp