/
Request.hs
210 lines (192 loc) · 5.63 KB
/
Request.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
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
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
module Test.Integration.Framework.Request
( request
, unsafeRequest
, Headers(..)
, Payload(..)
, RequestException(..)
, Context(..)
, TxDescription(..)
) where
import Prelude
import Cardano.CLI
( Port (..) )
import Cardano.Wallet.Primitive.Types
( NetworkParameters )
import Cardano.Wallet.Transaction
( DelegationAction )
import Control.Monad.Catch
( Exception (..), MonadCatch (..), throwM )
import Control.Monad.IO.Class
( MonadIO, liftIO )
import Data.Aeson
( FromJSON )
import Data.ByteString.Lazy
( ByteString )
import Data.Generics.Internal.VL.Lens
( (^.) )
import Data.Generics.Product.Typed
( HasType, typed )
import Data.Proxy
( Proxy (..) )
import Data.Text
( Text )
import GHC.Generics
( Generic )
import Network.HTTP.Client
( HttpException (..)
, HttpExceptionContent
, Manager
, RequestBody (..)
, httpLbs
, method
, parseRequest
, requestBody
, requestHeaders
, responseBody
, responseStatus
)
import Network.HTTP.Types.Header
( RequestHeaders )
import Network.HTTP.Types.Method
( Method )
import Network.HTTP.Types.Status
( status500 )
import Numeric.Natural
( Natural )
import Test.Integration.Faucet
( Faucet )
import qualified Data.Aeson as Aeson
import qualified Data.ByteString.Lazy.Char8 as BL8
import qualified Data.Text as T
import qualified Network.HTTP.Client as HTTP
import qualified Network.HTTP.Types.Status as HTTP
-- | Running Context for our integration test
data Context t = Context
{ _cleanup
:: IO ()
-- ^ Cleanup action for the context
, _manager
:: (Text, Manager)
-- ^ The underlying BaseUrl and Manager used by the Wallet Client
, _walletPort
:: Port "wallet"
-- ^ Server TCP port
, _faucet
:: Faucet
-- ^ A 'Faucet' handle in to have access to funded wallets in
-- integration tests.
, _feeEstimator :: TxDescription -> (Natural, Natural)
-- ^ A fee estimator for the integration tests
, _networkParameters :: NetworkParameters
-- ^ Blockchain parameters for the underlying chain
, _target
:: Proxy t
} deriving Generic
-- | Describe a transaction in terms of its inputs and outputs
data TxDescription
= DelegDescription DelegationAction
| PaymentDescription
{ nInputs :: Int
, nOutputs :: Int
, nChanges :: Int
}
deriving (Show)
-- | The result when 'request' fails.
data RequestException
= DecodeFailure ByteString
-- ^ JSON decoding the given response data failed.
| ClientError Aeson.Value
-- ^ The HTTP response status code indicated failure.
| HttpException HttpExceptionContent
-- ^ A wild exception upon sending the request
deriving (Show)
instance Exception RequestException
-- | The payload of the request
data Payload
= Json Aeson.Value
| NonJson ByteString
| Empty
deriving (Show)
-- | The headers of the request
data Headers
= Headers RequestHeaders
| Default
| None
deriving (Show)
-- | Makes a request to the API and decodes the response.
request
:: forall a m s.
( FromJSON a
, MonadIO m
, MonadCatch m
, HasType (Text, Manager) s
)
=> s
-> (Method, Text)
-- ^ HTTP method and request path
-> Headers
-- ^ Request headers
-> Payload
-- ^ Request body
-> m (HTTP.Status, Either RequestException a)
request ctx (verb, path) reqHeaders body = do
let (base, manager) = ctx ^. typed @(Text, Manager)
req <- parseRequest $ T.unpack $ base <> path
let io = handleResponse <$> liftIO (httpLbs (prepareReq req) manager)
catch io handleException
where
prepareReq :: HTTP.Request -> HTTP.Request
prepareReq req = req
{ method = verb
, requestBody = payload
, requestHeaders = headers
}
where
headers = case reqHeaders of
Headers x -> x
Default -> [ ("Content-Type", "application/json")
, ("Accept", "application/json")
]
None -> mempty
payload = case body of
Json x -> (RequestBodyLBS . Aeson.encode) x
NonJson x -> RequestBodyLBS x
Empty -> mempty
handleResponse res = case responseStatus res of
s | s < status500 -> either
(\err -> (s, Left $ DecodeFailure $ BL8.pack $ err <> ": " <> show res))
((s,) . Right)
(Aeson.eitherDecode $ responseBody res)
-- TODO: decode API error responses into ClientError
s -> (s, Left $ decodeFailure res)
handleException = \case
e@InvalidUrlException{} ->
throwM e
HttpExceptionRequest _ e ->
return (status500, Left (HttpException e))
decodeFailure :: HTTP.Response ByteString -> RequestException
decodeFailure res = DecodeFailure $ responseBody res
-- | Makes a request to the API, but throws if it fails.
unsafeRequest
:: forall a m t.
( FromJSON a
, MonadIO m
, MonadCatch m
)
=> Context t
-> (Method, Text)
-> Payload
-> m (HTTP.Status, a)
unsafeRequest ctx req body = do
(s, res) <- request ctx req Default body
either throwM (pure . (s,)) res