forked from simonmar/haskell-eXchange-2015
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHttpDataSource2.hs
81 lines (63 loc) · 2.41 KB
/
HttpDataSource2.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
{-# LANGUAGE
StandaloneDeriving, GADTs, TypeFamilies,
FlexibleInstances, MultiParamTypeClasses, GeneralizedNewtypeDeriving,
OverloadedStrings, DeriveDataTypeable
#-}
module HttpDataSource2
( getURL
, initDataSource
, HttpException(..)
) where
import Data.Hashable
import Data.Typeable
import qualified Data.Map as Map
import Control.Monad
import Data.Maybe
import Data.List
import Haxl.Core
import Control.Exception
import Control.Concurrent.Async
import Network.HTTP.Conduit
import qualified Data.ByteString.Lazy as L
import Text.Printf
import qualified Data.Text as T
-- -----------------------------------------------------------------------------
-- Request type
data HttpRequest a where
GetURL :: T.Text -> HttpRequest L.ByteString
deriving instance Show (HttpRequest a)
deriving instance Typeable HttpRequest
instance ShowP HttpRequest where showp = show
deriving instance Eq (HttpRequest a)
instance Hashable (HttpRequest a) where
hashWithSalt salt (GetURL u) = hashWithSalt salt u
-- -----------------------------------------------------------------------------
-- Requests
getURL :: T.Text -> GenHaxl u () L.ByteString
getURL = dataFetch . GetURL
instance StateKey HttpRequest where
data State HttpRequest = HttpState Manager
initDataSource :: IO (State HttpRequest)
initDataSource = HttpState <$> newManager tlsManagerSettings
instance DataSourceName HttpRequest where
dataSourceName _ = "HttpDataSource"
instance DataSource u HttpRequest where
-- fetch :: State HttpRequest -> Flags -> u -> PerformFetch HttpRequest
fetch (HttpState manager) _flags _userEnv =
SyncFetch $ batchFetch manager
-- fetch (HttpState mgr) _flags _userEnv blockedFetches = undefined
-- fetch _state _flags _userEnv blockedFetches = undefined
-- SyncFetch $ do
-- printf "Fetching %d urls.\n" (length blockedFetches)
-- void $ mapConcurrently (fetchURL mgr) blockedFetches
batchFetch :: Manager -> [BlockedFetch HttpRequest] -> IO ()
batchFetch manager blockedFetches = do
printf "Fetching %d urls.\n" (length blockedFetches)
void $ mapConcurrently (fetchURL manager) blockedFetches
fetchURL :: Manager -> BlockedFetch HttpRequest -> IO ()
fetchURL mgr (BlockedFetch (GetURL url) var) = do
e <- Control.Exception.try $ do
let request = parseRequest_ $ T.unpack url
responseBody <$> httpLbs request mgr
either (putFailure var) (putSuccess var)
(e :: Either SomeException L.ByteString)