/
Types.hs
302 lines (260 loc) · 8.18 KB
/
Types.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
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
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TemplateHaskell #-}
module Database.InfluxDB.Types
( -- * Series, columns and data points
Series(..)
, seriesColumns
, seriesPoints
, SeriesData(..)
, Column
, Value(..)
-- * Data types for HTTP API
, Credentials(..)
, Server(..)
, Database(..)
, User(..)
, Admin(..)
, Ping(..)
, Interface
, ShardSpace(..)
-- * Server pool
, ServerPool
, serverRetryPolicy
, newServerPool
, newServerPoolWithRetryPolicy
, activeServer
, failover
-- * Exceptions
, InfluxException(..)
, jsonDecodeError
, seriesDecodeError
) where
import Control.Applicative (empty)
import Control.Exception (Exception, throwIO)
import Data.Data (Data)
import Data.IORef
import Data.Int (Int64)
import Data.Monoid ((<>))
import Data.Sequence (Seq, ViewL(..), (|>))
import Data.Text (Text)
import Data.Typeable (Typeable)
import Data.Vector (Vector)
import Data.Word (Word32)
import GHC.Generics (Generic)
import qualified Data.Sequence as Seq
import Control.Retry (RetryPolicy, limitRetries, exponentialBackoff)
import Data.Aeson ((.=), (.:))
import Data.Aeson.TH
import qualified Data.Aeson as A
import Database.InfluxDB.Types.Internal (stripPrefixOptions)
#if MIN_VERSION_aeson(0, 7, 0)
import Data.Scientific
#else
import Data.Attoparsec.Number
#endif
-----------------------------------------------------------
-- Compatibility for older GHC
#if __GLASGOW_HASKELL__ < 706
import Control.Exception (evaluate)
atomicModifyIORef' :: IORef a -> (a -> (a, b)) -> IO b
atomicModifyIORef' ref f = do
b <- atomicModifyIORef ref $ \x ->
let (a, b) = f x
in (a, a `seq` b)
evaluate b
#endif
-----------------------------------------------------------
-- | A series consists of name, columns and points. The columns and points are
-- expressed in a separate type 'SeriesData'.
data Series = Series
{ seriesName :: {-# UNPACK #-} !Text
-- ^ Series name
, seriesData :: {-# UNPACK #-} !SeriesData
-- ^ Columns and data points in the series
} deriving (Typeable, Generic)
-- | Convenient accessor for columns.
seriesColumns :: Series -> Vector Column
seriesColumns = seriesDataColumns . seriesData
-- | Convenient accessor for points.
seriesPoints :: Series -> [Vector Value]
seriesPoints = seriesDataPoints . seriesData
instance A.ToJSON Series where
toJSON Series {..} = A.object
[ "name" .= seriesName
, "columns" .= seriesDataColumns
, "points" .= seriesDataPoints
]
where
SeriesData {..} = seriesData
instance A.FromJSON Series where
parseJSON (A.Object v) = do
name <- v .: "name"
columns <- v .: "columns"
points <- v .: "points"
return Series
{ seriesName = name
, seriesData = SeriesData
{ seriesDataColumns = columns
, seriesDataPoints = points
}
}
parseJSON _ = empty
-- | 'SeriesData' consists of columns and points.
data SeriesData = SeriesData
{ seriesDataColumns :: Vector Column
, seriesDataPoints :: [Vector Value]
} deriving (Eq, Show, Typeable, Generic)
type Column = Text
-- | An InfluxDB value represented as a Haskell value.
data Value
= Int !Int64
| Float !Double
| String !Text
| Bool !Bool
| Null
deriving (Eq, Show, Data, Typeable, Generic)
instance A.ToJSON Value where
toJSON (Int n) = A.toJSON n
toJSON (Float d) = A.toJSON d
toJSON (String xs) = A.toJSON xs
toJSON (Bool b) = A.toJSON b
toJSON Null = A.Null
instance A.FromJSON Value where
parseJSON (A.Object o) = fail $ "Unexpected object: " ++ show o
parseJSON (A.Array a) = fail $ "Unexpected array: " ++ show a
parseJSON (A.String xs) = return $ String xs
parseJSON (A.Bool b) = return $ Bool b
parseJSON A.Null = return Null
parseJSON (A.Number n) = return $! numberToValue
where
#if MIN_VERSION_aeson(0, 7, 0)
numberToValue
-- If the number is larger than Int64, it must be
-- a float64 (Double in Haskell).
| n > maxInt = Float $ toRealFloat n
| e < 0 = Float $ realToFrac n
| otherwise = Int $ fromIntegral $ coefficient n * 10 ^ e
where
e = base10Exponent n
#if !MIN_VERSION_scientific(0, 3, 0)
toRealFloat = realToFrac
-- scientific
#endif
#else
numberToValue = case n of
I i
-- If the number is larger than Int64, it must be
-- a float64 (Double in Haskell).
| i > maxInt -> Float $ fromIntegral i
| otherwise -> Int $ fromIntegral i
D d -> Float d
-- aeson
#endif
maxInt = fromIntegral (maxBound :: Int64)
-----------------------------------------------------------
-- | User credentials.
data Credentials = Credentials
{ credsUser :: !Text
, credsPassword :: !Text
} deriving (Show, Typeable, Generic)
-- | Server location.
data Server = Server
{ serverHost :: !Text
-- ^ Hostname or IP address
, serverPort :: !Int
, serverSsl :: !Bool
-- ^ SSL is enabled or not in the server side
} deriving (Show, Typeable, Generic)
-- | Non-empty set of server locations. The active server will always be used
-- until any HTTP communications fail.
data ServerPool = ServerPool
{ serverActive :: !Server
-- ^ Current active server
, serverBackup :: !(Seq Server)
-- ^ The rest of the servers in the pool.
, serverRetryPolicy :: !RetryPolicy
}
newtype Database = Database
{ databaseName :: Text
} deriving (Show, Typeable, Generic)
-- | User
data User = User
{ userName :: Text
, userIsAdmin :: Bool
} deriving (Show, Typeable, Generic)
-- | Administrator
newtype Admin = Admin
{ adminName :: Text
} deriving (Show, Typeable, Generic)
newtype Ping = Ping
{ pingStatus :: Text
} deriving (Show, Typeable, Generic)
type Interface = Text
data ShardSpace = ShardSpace
{ shardSpaceDatabase :: Maybe Text
, shardSpaceName :: Text
, shardSpaceRegex :: Text
, shardSpaceRetentionPolicy :: Text
, shardSpaceShardDuration :: Text
, shardSpaceReplicationFactor :: Word32
, shardSpaceSplit :: Word32
} deriving (Show, Typeable, Generic)
-----------------------------------------------------------
-- Server pool manipulation
-- | Create a non-empty server pool. You must specify at least one server
-- location to create a pool.
newServerPool :: Server -> [Server] -> IO (IORef ServerPool)
newServerPool = newServerPoolWithRetryPolicy defaultRetryPolicy
where
defaultRetryPolicy :: RetryPolicy
defaultRetryPolicy = limitRetries 5 <> exponentialBackoff 50
newServerPoolWithRetryPolicy
:: RetryPolicy -> Server -> [Server] -> IO (IORef ServerPool)
newServerPoolWithRetryPolicy retryPolicy active backups =
newIORef ServerPool
{ serverActive = active
, serverBackup = Seq.fromList backups
, serverRetryPolicy = retryPolicy
}
-- | Get a server from the pool.
activeServer :: IORef ServerPool -> IO Server
activeServer ref = do
ServerPool { serverActive } <- readIORef ref
return serverActive
-- | Move the current server to the backup pool and pick one of the backup
-- server as the new active server. Currently the scheduler works in
-- round-robin fashion.
failover :: IORef ServerPool -> IO ()
failover ref = atomicModifyIORef' ref $ \pool@ServerPool {..} ->
case Seq.viewl serverBackup of
EmptyL -> (pool, ())
active :< rest -> (newPool, ())
where
newPool = pool
{ serverActive = active
, serverBackup = rest |> serverActive
}
-----------------------------------------------------------
-- Exceptions
data InfluxException
= JsonDecodeError String
| SeriesDecodeError String
deriving (Show, Typeable)
instance Exception InfluxException
jsonDecodeError :: String -> IO a
jsonDecodeError = throwIO . JsonDecodeError
seriesDecodeError :: String -> IO a
seriesDecodeError = throwIO . SeriesDecodeError
-----------------------------------------------------------
-- Aeson instances
deriveFromJSON (stripPrefixOptions "database") ''Database
deriveFromJSON (stripPrefixOptions "admin") ''Admin
deriveFromJSON (stripPrefixOptions "user") ''User
deriveFromJSON (stripPrefixOptions "ping") ''Ping
deriveFromJSON (stripPrefixOptions "shardSpace") ''ShardSpace