root / src / Ganeti / JSON.hs @ b9202225
History | View | Annotate | Download (12.3 kB)
1 |
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-} |
---|---|
2 |
{-# OPTIONS_GHC -fno-warn-orphans #-} |
3 |
|
4 |
{-| JSON utility functions. -} |
5 |
|
6 |
{- |
7 |
|
8 |
Copyright (C) 2009, 2010, 2011, 2012, 2013 Google Inc. |
9 |
|
10 |
This program is free software; you can redistribute it and/or modify |
11 |
it under the terms of the GNU General Public License as published by |
12 |
the Free Software Foundation; either version 2 of the License, or |
13 |
(at your option) any later version. |
14 |
|
15 |
This program is distributed in the hope that it will be useful, but |
16 |
WITHOUT ANY WARRANTY; without even the implied warranty of |
17 |
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
18 |
General Public License for more details. |
19 |
|
20 |
You should have received a copy of the GNU General Public License |
21 |
along with this program; if not, write to the Free Software |
22 |
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA |
23 |
02110-1301, USA. |
24 |
|
25 |
-} |
26 |
|
27 |
module Ganeti.JSON |
28 |
( fromJResult |
29 |
, fromJResultE |
30 |
, readJSONWithDesc |
31 |
, readEitherString |
32 |
, JSRecord |
33 |
, loadJSArray |
34 |
, fromObj |
35 |
, maybeFromObj |
36 |
, fromObjWithDefault |
37 |
, fromKeyValue |
38 |
, fromJVal |
39 |
, fromJValE |
40 |
, jsonHead |
41 |
, getMaybeJsonHead |
42 |
, getMaybeJsonElem |
43 |
, asJSObject |
44 |
, asObjectList |
45 |
, tryFromObj |
46 |
, arrayMaybeFromJVal |
47 |
, tryArrayMaybeFromObj |
48 |
, toArray |
49 |
, optionalJSField |
50 |
, optFieldsToObj |
51 |
, HasStringRepr(..) |
52 |
, GenericContainer(..) |
53 |
, Container |
54 |
, MaybeForJSON(..) |
55 |
, TimeAsDoubleJSON(..) |
56 |
) |
57 |
where |
58 |
|
59 |
import Control.DeepSeq |
60 |
import Control.Monad (liftM) |
61 |
import Control.Monad.Error.Class |
62 |
import Data.Maybe (fromMaybe, catMaybes) |
63 |
import qualified Data.Map as Map |
64 |
import System.Time (ClockTime(..)) |
65 |
import Text.Printf (printf) |
66 |
|
67 |
import qualified Text.JSON as J |
68 |
import Text.JSON.Pretty (pp_value) |
69 |
|
70 |
-- Note: this module should not import any Ganeti-specific modules |
71 |
-- beside BasicTypes, since it's used in THH which is used itself to |
72 |
-- build many other modules. |
73 |
|
74 |
import Ganeti.BasicTypes |
75 |
|
76 |
-- * JSON-related functions |
77 |
|
78 |
instance NFData J.JSValue where |
79 |
rnf J.JSNull = () |
80 |
rnf (J.JSBool b) = rnf b |
81 |
rnf (J.JSRational b r) = rnf b `seq` rnf r |
82 |
rnf (J.JSString s) = rnf $ J.fromJSString s |
83 |
rnf (J.JSArray a) = rnf a |
84 |
rnf (J.JSObject o) = rnf o |
85 |
|
86 |
instance (NFData a) => NFData (J.JSObject a) where |
87 |
rnf = rnf . J.fromJSObject |
88 |
|
89 |
-- | A type alias for a field of a JSRecord. |
90 |
type JSField = (String, J.JSValue) |
91 |
|
92 |
-- | A type alias for the list-based representation of J.JSObject. |
93 |
type JSRecord = [JSField] |
94 |
|
95 |
-- | Annotate @readJSON@ error messages with descriptions of what |
96 |
-- is being parsed into what. |
97 |
readJSONWithDesc :: (J.JSON a) |
98 |
=> String -- ^ description of @a@ |
99 |
-> Bool -- ^ include input in |
100 |
-- error messages |
101 |
-> J.JSValue -- ^ input value |
102 |
-> J.Result a |
103 |
readJSONWithDesc typ incInput input = |
104 |
case J.readJSON input of |
105 |
J.Ok r -> J.Ok r |
106 |
J.Error e -> J.Error $ if incInput then msg ++ " from " ++ show input |
107 |
else msg |
108 |
where msg = "Can't parse value for type " ++ typ ++ ": " ++ e |
109 |
|
110 |
-- | Converts a JSON Result into a monadic value. |
111 |
fromJResult :: Monad m => String -> J.Result a -> m a |
112 |
fromJResult s (J.Error x) = fail (s ++ ": " ++ x) |
113 |
fromJResult _ (J.Ok x) = return x |
114 |
|
115 |
-- | Converts a JSON Result into a MonadError value. |
116 |
fromJResultE :: (Error e, MonadError e m) => String -> J.Result a -> m a |
117 |
fromJResultE s (J.Error x) = throwError . strMsg $ s ++ ": " ++ x |
118 |
fromJResultE _ (J.Ok x) = return x |
119 |
|
120 |
-- | Tries to read a string from a JSON value. |
121 |
-- |
122 |
-- In case the value was not a string, we fail the read (in the |
123 |
-- context of the current monad. |
124 |
readEitherString :: (Monad m) => J.JSValue -> m String |
125 |
readEitherString v = |
126 |
case v of |
127 |
J.JSString s -> return $ J.fromJSString s |
128 |
_ -> fail "Wrong JSON type" |
129 |
|
130 |
-- | Converts a JSON message into an array of JSON objects. |
131 |
loadJSArray :: (Monad m) |
132 |
=> String -- ^ Operation description (for error reporting) |
133 |
-> String -- ^ Input message |
134 |
-> m [J.JSObject J.JSValue] |
135 |
loadJSArray s = fromJResult s . J.decodeStrict |
136 |
|
137 |
-- | Helper function for missing-key errors |
138 |
buildNoKeyError :: JSRecord -> String -> String |
139 |
buildNoKeyError o k = |
140 |
printf "key '%s' not found, object contains only %s" k (show (map fst o)) |
141 |
|
142 |
-- | Reads the value of a key in a JSON object. |
143 |
fromObj :: (J.JSON a, Monad m) => JSRecord -> String -> m a |
144 |
fromObj o k = |
145 |
case lookup k o of |
146 |
Nothing -> fail $ buildNoKeyError o k |
147 |
Just val -> fromKeyValue k val |
148 |
|
149 |
-- | Reads the value of an optional key in a JSON object. Missing |
150 |
-- keys, or keys that have a \'null\' value, will be returned as |
151 |
-- 'Nothing', otherwise we attempt deserialisation and return a 'Just' |
152 |
-- value. |
153 |
maybeFromObj :: (J.JSON a, Monad m) => |
154 |
JSRecord -> String -> m (Maybe a) |
155 |
maybeFromObj o k = |
156 |
case lookup k o of |
157 |
Nothing -> return Nothing |
158 |
-- a optional key with value JSNull is the same as missing, since |
159 |
-- we can't convert it meaningfully anyway to a Haskell type, and |
160 |
-- the Python code can emit 'null' for optional values (depending |
161 |
-- on usage), and finally our encoding rules treat 'null' values |
162 |
-- as 'missing' |
163 |
Just J.JSNull -> return Nothing |
164 |
Just val -> liftM Just (fromKeyValue k val) |
165 |
|
166 |
-- | Reads the value of a key in a JSON object with a default if |
167 |
-- missing. Note that both missing keys and keys with value \'null\' |
168 |
-- will cause the default value to be returned. |
169 |
fromObjWithDefault :: (J.JSON a, Monad m) => |
170 |
JSRecord -> String -> a -> m a |
171 |
fromObjWithDefault o k d = liftM (fromMaybe d) $ maybeFromObj o k |
172 |
|
173 |
arrayMaybeFromJVal :: (J.JSON a, Monad m) => J.JSValue -> m [Maybe a] |
174 |
arrayMaybeFromJVal (J.JSArray xs) = |
175 |
mapM parse xs |
176 |
where |
177 |
parse J.JSNull = return Nothing |
178 |
parse x = liftM Just $ fromJVal x |
179 |
arrayMaybeFromJVal v = |
180 |
fail $ "Expecting array, got '" ++ show (pp_value v) ++ "'" |
181 |
|
182 |
-- | Reads an array of optional items |
183 |
arrayMaybeFromObj :: (J.JSON a, Monad m) => |
184 |
JSRecord -> String -> m [Maybe a] |
185 |
arrayMaybeFromObj o k = |
186 |
case lookup k o of |
187 |
Just a -> arrayMaybeFromJVal a |
188 |
_ -> fail $ buildNoKeyError o k |
189 |
|
190 |
-- | Wrapper for arrayMaybeFromObj with better diagnostic |
191 |
tryArrayMaybeFromObj :: (J.JSON a) |
192 |
=> String -- ^ Textual "owner" in error messages |
193 |
-> JSRecord -- ^ The object array |
194 |
-> String -- ^ The desired key from the object |
195 |
-> Result [Maybe a] |
196 |
tryArrayMaybeFromObj t o = annotateResult t . arrayMaybeFromObj o |
197 |
|
198 |
-- | Reads a JValue, that originated from an object key. |
199 |
fromKeyValue :: (J.JSON a, Monad m) |
200 |
=> String -- ^ The key name |
201 |
-> J.JSValue -- ^ The value to read |
202 |
-> m a |
203 |
fromKeyValue k val = |
204 |
fromJResult (printf "key '%s'" k) (J.readJSON val) |
205 |
|
206 |
-- | Small wrapper over readJSON. |
207 |
fromJVal :: (Monad m, J.JSON a) => J.JSValue -> m a |
208 |
fromJVal v = |
209 |
case J.readJSON v of |
210 |
J.Error s -> fail ("Cannot convert value '" ++ show (pp_value v) ++ |
211 |
"', error: " ++ s) |
212 |
J.Ok x -> return x |
213 |
|
214 |
-- | Small wrapper over 'readJSON' for 'MonadError'. |
215 |
fromJValE :: (Error e, MonadError e m, J.JSON a) => J.JSValue -> m a |
216 |
fromJValE v = |
217 |
case J.readJSON v of |
218 |
J.Error s -> throwError . strMsg $ |
219 |
"Cannot convert value '" ++ show (pp_value v) ++ |
220 |
"', error: " ++ s |
221 |
J.Ok x -> return x |
222 |
|
223 |
-- | Helper function that returns Null or first element of the list. |
224 |
jsonHead :: (J.JSON b) => [a] -> (a -> b) -> J.JSValue |
225 |
jsonHead [] _ = J.JSNull |
226 |
jsonHead (x:_) f = J.showJSON $ f x |
227 |
|
228 |
-- | Helper for extracting Maybe values from a possibly empty list. |
229 |
getMaybeJsonHead :: (J.JSON b) => [a] -> (a -> Maybe b) -> J.JSValue |
230 |
getMaybeJsonHead [] _ = J.JSNull |
231 |
getMaybeJsonHead (x:_) f = maybe J.JSNull J.showJSON (f x) |
232 |
|
233 |
-- | Helper for extracting Maybe values from a list that might be too short. |
234 |
getMaybeJsonElem :: (J.JSON b) => [a] -> Int -> (a -> Maybe b) -> J.JSValue |
235 |
getMaybeJsonElem [] _ _ = J.JSNull |
236 |
getMaybeJsonElem xs 0 f = getMaybeJsonHead xs f |
237 |
getMaybeJsonElem (_:xs) n f |
238 |
| n < 0 = J.JSNull |
239 |
| otherwise = getMaybeJsonElem xs (n - 1) f |
240 |
|
241 |
-- | Converts a JSON value into a JSON object. |
242 |
asJSObject :: (Monad m) => J.JSValue -> m (J.JSObject J.JSValue) |
243 |
asJSObject (J.JSObject a) = return a |
244 |
asJSObject _ = fail "not an object" |
245 |
|
246 |
-- | Coneverts a list of JSON values into a list of JSON objects. |
247 |
asObjectList :: (Monad m) => [J.JSValue] -> m [J.JSObject J.JSValue] |
248 |
asObjectList = mapM asJSObject |
249 |
|
250 |
-- | Try to extract a key from an object with better error reporting |
251 |
-- than fromObj. |
252 |
tryFromObj :: (J.JSON a) => |
253 |
String -- ^ Textual "owner" in error messages |
254 |
-> JSRecord -- ^ The object array |
255 |
-> String -- ^ The desired key from the object |
256 |
-> Result a |
257 |
tryFromObj t o = annotateResult t . fromObj o |
258 |
|
259 |
-- | Ensure a given JSValue is actually a JSArray. |
260 |
toArray :: (Monad m) => J.JSValue -> m [J.JSValue] |
261 |
toArray (J.JSArray arr) = return arr |
262 |
toArray o = |
263 |
fail $ "Invalid input, expected array but got " ++ show (pp_value o) |
264 |
|
265 |
-- | Creates a Maybe JSField. If the value string is Nothing, the JSField |
266 |
-- will be Nothing as well. |
267 |
optionalJSField :: (J.JSON a) => String -> Maybe a -> Maybe JSField |
268 |
optionalJSField name (Just value) = Just (name, J.showJSON value) |
269 |
optionalJSField _ Nothing = Nothing |
270 |
|
271 |
-- | Creates an object with all the non-Nothing fields of the given list. |
272 |
optFieldsToObj :: [Maybe JSField] -> J.JSValue |
273 |
optFieldsToObj = J.makeObj . catMaybes |
274 |
|
275 |
-- * Container type (special type for JSON serialisation) |
276 |
|
277 |
-- | Class of types that can be converted from Strings. This is |
278 |
-- similar to the 'Read' class, but it's using a different |
279 |
-- serialisation format, so we have to define a separate class. Mostly |
280 |
-- useful for custom key types in JSON dictionaries, which have to be |
281 |
-- backed by strings. |
282 |
class HasStringRepr a where |
283 |
fromStringRepr :: (Monad m) => String -> m a |
284 |
toStringRepr :: a -> String |
285 |
|
286 |
-- | Trivial instance 'HasStringRepr' for 'String'. |
287 |
instance HasStringRepr String where |
288 |
fromStringRepr = return |
289 |
toStringRepr = id |
290 |
|
291 |
-- | The container type, a wrapper over Data.Map |
292 |
newtype GenericContainer a b = |
293 |
GenericContainer { fromContainer :: Map.Map a b } |
294 |
deriving (Show, Eq) |
295 |
|
296 |
instance (NFData a, NFData b) => NFData (GenericContainer a b) where |
297 |
rnf = rnf . Map.toList . fromContainer |
298 |
|
299 |
-- | Type alias for string keys. |
300 |
type Container = GenericContainer String |
301 |
|
302 |
-- | Container loader. |
303 |
readContainer :: (Monad m, HasStringRepr a, Ord a, J.JSON b) => |
304 |
J.JSObject J.JSValue -> m (GenericContainer a b) |
305 |
readContainer obj = do |
306 |
let kjvlist = J.fromJSObject obj |
307 |
kalist <- mapM (\(k, v) -> do |
308 |
k' <- fromStringRepr k |
309 |
v' <- fromKeyValue k v |
310 |
return (k', v')) kjvlist |
311 |
return $ GenericContainer (Map.fromList kalist) |
312 |
|
313 |
{-# ANN showContainer "HLint: ignore Use ***" #-} |
314 |
-- | Container dumper. |
315 |
showContainer :: (HasStringRepr a, J.JSON b) => |
316 |
GenericContainer a b -> J.JSValue |
317 |
showContainer = |
318 |
J.makeObj . map (\(k, v) -> (toStringRepr k, J.showJSON v)) . |
319 |
Map.toList . fromContainer |
320 |
|
321 |
instance (HasStringRepr a, Ord a, J.JSON b) => |
322 |
J.JSON (GenericContainer a b) where |
323 |
showJSON = showContainer |
324 |
readJSON (J.JSObject o) = readContainer o |
325 |
readJSON v = fail $ "Failed to load container, expected object but got " |
326 |
++ show (pp_value v) |
327 |
|
328 |
-- | A Maybe newtype that allows for serialization more appropriate to the |
329 |
-- semantics of Maybe and JSON in our calls. Does not produce needless |
330 |
-- and confusing dictionaries. |
331 |
newtype MaybeForJSON a = MaybeForJSON { unMaybeForJSON :: Maybe a } |
332 |
deriving (Show, Eq, Ord) |
333 |
instance (J.JSON a) => J.JSON (MaybeForJSON a) where |
334 |
readJSON J.JSNull = return $ MaybeForJSON Nothing |
335 |
readJSON x = (MaybeForJSON . Just) `liftM` J.readJSON x |
336 |
showJSON (MaybeForJSON (Just x)) = J.showJSON x |
337 |
showJSON (MaybeForJSON Nothing) = J.JSNull |
338 |
|
339 |
newtype TimeAsDoubleJSON |
340 |
= TimeAsDoubleJSON { unTimeAsDoubleJSON :: ClockTime } |
341 |
deriving (Show, Eq, Ord) |
342 |
instance J.JSON TimeAsDoubleJSON where |
343 |
readJSON v = do |
344 |
t <- J.readJSON v :: J.Result Double |
345 |
return . TimeAsDoubleJSON . uncurry TOD |
346 |
$ divMod (round $ t * pico) (pico :: Integer) |
347 |
where |
348 |
pico :: (Num a) => a |
349 |
pico = 10^(12 :: Int) |
350 |
showJSON (TimeAsDoubleJSON (TOD ss ps)) = J.showJSON |
351 |
(fromIntegral ss + fromIntegral ps / 10^(12 :: Int) :: Double) |