@@ -1,8 +1,5 @@
11{-# LANGUAGE AllowAmbiguousTypes #-}
2−{-# LANGUAGE DataKinds #-}
3−{-# LANGUAGE DerivingStrategies #-}
42{-# LANGUAGE FlexibleContexts #-}
5−{-# LANGUAGE FlexibleInstances #-}
63{-# LANGUAGE GADTs #-}
74{-# LANGUAGE LambdaCase #-}
85{-# LANGUAGE PolyKinds #-}
@@ -10,72 +7,75 @@
107{-# LANGUAGE RecordWildCards #-}
118{-# LANGUAGE ScopedTypeVariables #-}
129{-# LANGUAGE TupleSections #-}
13−{-# LANGUAGE TypeApplications #-}
14−{-# LANGUAGE TypeFamilies #-}
1510
11+{-# LANGUAGE TypeFamilies #-}
1612{-# LANGUAGE UndecidableInstances #-}
1713
1814module Roboservant.Direct
19− ( fuzz, Config(..)
20−
21− -- TODO come up with something smarter than exporting all this, we should
22− -- have some nice error-display functions
23− , RoboservantException(..), FuzzState(..), FuzzOp(..), FailureType(..), Report(..)
15+ ( fuzz',
16+ Config (..),
17+ -- TODO come up with something smarter than exporting all this, we should
18+ -- have some nice error-display functions
19+ RoboservantException (..),
20+ FuzzState (..),
21+ FuzzOp (..),
22+ FailureType (..),
23+ Report (..),
2424 )
2525where
2626
27−import Control.Exception.Lifted(throw,handle,Handler(..), Exception,SomeException,SomeAsyncException, catch, catches)
28−import Control.Monad.State.Strict(MonadState,MonadIO,get,modify',liftIO,runStateT)
29−import Control.Exception.Lifted(throw,Handler(..), Exception,SomeException,SomeAsyncException, catch, catches)
30−import Control.Monad(void,replicateM,forM_)
31−import Control.Monad.State.Strict(MonadState,MonadIO,get,modify',liftIO,execStateT)
32−import Control.Monad.Trans.Control(MonadBaseControl)
33−import Data.Dependent.Map (DMap)
34−import Data.Dynamic (Dynamic(..), dynApply, dynTypeRep, fromDynamic)
35−import Data.List.NonEmpty (NonEmpty(..))
36−import Data.Map.Strict(Map)
37−import qualified Data.Set as Set
38−import Data.Maybe (mapMaybe)
39−import Data.Typeable (TypeRep)
40−import Servant (Endpoints, Proxy (Proxy), Server, ServerError(..))
41−import System.Random(StdGen,randomR,mkStdGen)
42−import qualified Data.List.NonEmpty as NEL
43−import qualified Data.Map.Strict as Map
44−import Data.Time.Clock
45−import Data.List(sortOn)
46−import Control.Arrow(second)
47−import System.Timeout.Lifted(timeout)
48−import GHC.Generics ((:*:)(..))
49−import qualified Data.Vinyl.Functor as V
50−import qualified Data.Vinyl.Curry as V
27+import Control.Exception.Lifted
28+ ( Exception,
29+ Handler (Handler),
30+ SomeAsyncException,
31+ SomeException,
32+ catch,
33+ catches,
34+ handle,
35+ throw,
36+ )
37+import Control.Monad.State.Strict
38+ ( MonadIO (..),
39+ MonadState (get),
40+ StateT (runStateT),
41+ modify',
42+ )
43+import Control.Monad.Trans.Control (MonadBaseControl)
5144import qualified Data.Dependent.Map as DM
52−import qualified Data.Vinyl as V
45+import Data.Dynamic (Dynamic (..))
46+import qualified Data.IntSet as IntSet
47+import Data.List.NonEmpty (NonEmpty (..))
5348import qualified Data.List.NonEmpty as NEL
54−import qualified Data.Map.Strict as Map
55−import Data.Time.Clock
56−import qualified Type.Reflection as R
57−
58−import Roboservant.Types.Breakdown
49+import Data.Maybe (mapMaybe)
50+import qualified Data.Set as Set
51+import Data.Time.Clock (UTCTime, addUTCTime, getCurrentTime)
52+import qualified Data.Vinyl as V
53+import qualified Data.Vinyl.Curry as V
54+import qualified Data.Vinyl.Functor as V
55+import GHC.Generics ((:*:) (..))
5956import Roboservant.Types
6057 ( ApiOffset (..),
61− FlattenServer (..),
62−-- ReifiedApi,
63− ToReifiedApi (..),
64−
65− ReifiedEndpoint(..),
66− Argument(..),
67− TypedF
68−
58+ Argument (..),
59+ InteractionError(..),
60+ Provenance (..),
61+ ReifiedApi,
62+ ReifiedEndpoint (..),
63+ Stash (..),
64+ StashValue (..),
65+ TypedF,
6966 )
67+import Roboservant.Types.Config
7068
69+import System.Random (Random (randomR), StdGen, mkStdGen)
70+import qualified Type.Reflection as R
7171
7272data RoboservantException
7373 = RoboservantException
74− { failureReason :: FailureType
75− , serverException :: Maybe SomeException
76− , something :: Int
77− , fuzzState :: FuzzState
78− } deriving (Show)
74+ { failureReason :: FailureType,
75+ serverException :: Maybe SomeException,
76+ fuzzState :: FuzzState
77+ }
78+ deriving (Show)
7979
8080instance Exception RoboservantException
8181
@@ -84,212 +84,228 @@ data FailureType
8484 | CheckerFailed
8585 | NoPossibleMoves
8686 | InsufficientCoverage Double
87− deriving (Show,Eq)
88−
89−
90−data FuzzOp = FuzzOp
91− { apiOffset :: ApiOffset
92− , provenance :: [Provenance]
93− } deriving (Show,Eq)
94−
95−data Config
96− = Config
97− { seed :: [Dynamic]
98− , maxRuntime :: Integer -- seconds to test for
99− , maxReps :: Integer
100− , rngSeed :: Int
101− , coverageThreshold :: Double
102− }
103−
104−data FuzzState = FuzzState
105− { path :: [FuzzOp]
106− , stash :: Stash
107− , currentRng :: StdGen
108− }
109− deriving Show
87+ deriving (Show, Eq)
88+
89+data FuzzOp
90+ = FuzzOp
91+ { apiOffset :: ApiOffset,
92+ provenance :: [Provenance]
93+ }
94+ deriving (Show, Eq)
95+
96+data FuzzState
97+ = FuzzState
98+ { path :: [FuzzOp],
99+ stash :: Stash,
100+ currentRng :: StdGen
101+ }
102+ deriving (Show)
110103
111−data EndpointOption = forall as. (V.RecordToList as, V.RMap as) => EndpointOption
112− { eoCall :: V.Curried as (IO (Either ServerError (NonEmpty Dynamic)))
113− , eoArgs :: V.Rec (TypedF StashValue) as
114− }
104+data EndpointOption
105+ = forall as.
106+ (V.RecordToList as, V.RMap as) =>
107+ EndpointOption
108+ { eoCall :: V.Curried as (IO (Either InteractionError (NonEmpty (Dynamic, Int)))),
109+ eoArgs :: V.Rec (TypedF StashValue) as
110+ }
115111
116112data StopReason
117113 = TimedOut
118114 | HitMaxIterations
119− deriving (Show,Eq)
115+ deriving (Show, Eq)
120116
121−data Report = Report
122− { textual :: String
123− , rsException :: RoboservantException}
117+data Report
118+ = Report
119+ { textual :: String,
120+ rsException :: RoboservantException
121+ }
124122 deriving (Show)
125123
126−fuzz :: forall api. (FlattenServer api, ToReifiedApi (Endpoints api))
127− => Server api
128− -> Config
129− -> IO ()
130− -> IO (Maybe Report)
131−fuzz server Config{..} checker = handle (pure . Just . formatException) $ do
124+
125+
126+-- fuzzClient :: Client api -> Config -> IO (Maybe Report)
127+-- fuzzClient = undefined
128+
129+
130+
131+fuzz' ::
132+ ReifiedApi ->
133+ Config ->
134+ IO (Maybe Report)
135+fuzz' reifiedApi Config {..} = handle (pure . Just . formatException) $ do
132136 let path = []
133137 stash = addToStash seed mempty
134138 currentRng = mkStdGen rngSeed
135−
136−
137− deadline :: UTCTime <- addUTCTime (fromInteger $ maxRuntime * 1000000) <$> getCurrentTime
138− (stopreason, fs ) <- runStateT
139− (untilDone (maxReps, deadline) go <* (evaluateCoverage =<< get)) FuzzState{..}
140− print stopreason
139+ deadline :: UTCTime <- addUTCTime (realToFrac $ maxRuntime * 1000000) <$> getCurrentTime
140+ (stopreason, _fs) <-
141+ runStateT
142+ (untilDone (maxReps, deadline) go <* (evaluateCoverage =<< get))
143+ FuzzState {..}
144+ logInfo $ show stopreason
141145 pure Nothing
142146 where
143147 -- something less terrible later
144148 formatException :: RoboservantException -> Report
145− formatException r@(RoboservantException failureType exception _state) = Report
146− (unlines [ show failureType , show exception ])
147− r
148−
149− displayDiagnostics FuzzState{..} = liftIO $ do
150− putStrLn "api endpoints covered"
151− mapM_ print (Set.toList $ Set.fromList $ map apiOffset path)
152− putStrLn ""
153− putStrLn "types in stash"
154− mapM_
155− (print . second NEL.length)
156− (sortOn (show . fst) . Map.toList stash)
157−
158− -- evaluateCoverage :: FuzzState -> m ()
159− evaluateCoverage f@FuzzState{..}
149+ formatException r@(RoboservantException failureType exception _state) =
150+ Report
151+ (unlines [show failureType, show exception])
152+ r
153+ displayDiagnostics FuzzState {..} = liftIO $
154+ logInfo $ unlines $
155+ ["api endpoints covered"]
156+ <> (map show . Set.toList . Set.fromList $ map apiOffset path)
157+ <> ["", "types in stash"]
158+ <> DM.foldrWithKey (\_ v r -> (show . NEL.length . getStashValue $ v) : r) [] (getStash stash)
159+ -- <> (map (show . NEL.length . getStashValue ) $ DM.assocs (getStash stash))
160+ -- $ \_k v ->
161+ -- (show . NEL.length $ getStashValue v))
162+
163+ evaluateCoverage f@FuzzState {..}
160164 | coverage > coverageThreshold = pure ()
161165 | otherwise = do
162− displayDiagnostics f
163− throw $ RoboservantException (InsufficientCoverage coverage) Nothing f
164− where hitRoutes = fromIntegral . Set.size . Set.fromList $ map apiOffset path
165− totalRoutes = fromIntegral routeCount
166− coverage = hitRoutes / totalRoutes
167−
168−
169− untilDone :: MonadIO m => (Integer,UTCTime) -> m a -> m StopReason
170− untilDone (0,_) _ = pure HitMaxIterations
166+ displayDiagnostics f
167+ throw $ RoboservantException (InsufficientCoverage coverage) Nothing f
168+ where
169+ hitRoutes = fromIntegral . Set.size . Set.fromList $ map apiOffset path
170+ totalRoutes = fromIntegral routeCount
171+ coverage = hitRoutes / totalRoutes
172+ untilDone :: MonadIO m => (Integer, UTCTime) -> m a -> m StopReason
173+ untilDone (0, _) _ = pure HitMaxIterations
171174 untilDone (n, deadline) action = do
172175 now <- liftIO getCurrentTime
173176 if now > deadline
174177 then pure TimedOut
175178 else do
176− action
177− untilDone (n-1, deadline) action
179+ _ <- action
180+ untilDone (n -1, deadline) action
178181
179− reifiedApi = toReifiedApi (flattenServer @api server) (Proxy @(Endpoints api))
180182 routeCount = length reifiedApi
181−
182− elementOrFail :: (MonadState FuzzState m, MonadIO m)
183− => [a] -> m a
184− elementOrFail [] = liftIO . throw . RoboservantException NoPossibleMoves Nothing =<< get
183+ elementOrFail ::
184+ (MonadState FuzzState m, MonadIO m) =>
185+ [a] ->
186+ m a
187+ elementOrFail [] = liftIO . throw . RoboservantException NoPossibleMoves Nothing =<< get
185188 elementOrFail l = do
186189 st <- get
187− let (index,newGen) = randomR (0, length l - 1) (currentRng st)
188− modify' $ \st' -> st' { currentRng = newGen }
190+ let (index, newGen) = randomR (0, length l - 1) (currentRng st)
191+ modify' $ \st' -> st' {currentRng = newGen}
189192 pure (l !! index)
190−
191− withOp :: (MonadState FuzzState m, MonadIO m)
192− => (forall as. (V.RecordToList as, V.RMap as)
193− => FuzzOp
194− -> V.Curried as (IO (Either ServerError (NonEmpty Dynamic)))
195− -> V.Rec (TypedF V.Identity) as -> m r
196− )
197− -> m r
193+ withOp ::
194+ (MonadState FuzzState m, MonadIO m) =>
195+ ( forall as.
196+ (V.RecordToList as, V.RMap as) =>
197+ FuzzOp ->
198+ V.Curried as (IO (Either InteractionError (NonEmpty (Dynamic, Int)))) ->
199+ V.Rec (TypedF V.Identity) as ->
200+ m r
201+ ) ->
202+ m r
198203 withOp callback = do
199204 -- choose a call to make, from the endpoints with fillable arguments.
200− (offset, EndpointOption{..}) <- elementOrFail . options =<< get
201− r <- V.rtraverse
202− (\(tr :*: StashValue svs) -> elementOrFail $
203− zipWith (\i xy -> V.Const i :*: tr :*: xy)
204− [0..]
205− (NEL.toList svs)
206− )
207− eoArgs
208− let pathSegment = FuzzOp offset $
209− recordToList'
210− (\(V.Const index :*: tr :*: _) -> Provenance (R.SomeTypeRep tr) index)
205+ (offset, EndpointOption {..}) <- elementOrFail . options =<< get
206+ r <-
207+ V.rtraverse
208+ ( \(tr :*: StashValue svs _) ->
209+ elementOrFail $
210+ zipWith
211+ (\i xy -> V.Const i :*: tr :*: xy)
212+ [0 ..]
213+ (NEL.toList svs)
214+ )
215+ eoArgs
216+ let pathSegment =
217+ FuzzOp offset $
218+ recordToList'
219+ (\(V.Const index :*: tr :*: _) -> Provenance (R.SomeTypeRep tr) index)
220+ r
221+ argValues =
222+ V.rmap
223+ (\(_ :*: tr :*: (_, x)) -> tr :*: V.Identity x)
211224 r
212− argValues = V.rmap
213− (\(_ :*: tr :*: (_, x)) -> tr :*: V.Identity x)
214− r
215− modify' (\f -> f { path = path f <> [pathSegment] })
225+ modify' (\f -> f {path = path f <> [pathSegment]})
216226 callback pathSegment eoCall argValues
217227 where
218228 options :: FuzzState -> [(ApiOffset, EndpointOption)]
219− options FuzzState{..} =
229+ options FuzzState {..} =
220230 mapMaybe
221− ( \(offset, ReifiedEndpoint{..}) -> do
222− args <- V.rtraverse (\(tr :*: Argument bf) -> (tr :*:) <$> bf stash) reArguments
223− pure (offset, EndpointOption reEndpointFunc args)
231+ ( \(offset, ReifiedEndpoint {..}) -> do
232+ args <- V.rtraverse (\(tr :*: Argument bf) -> (tr :*:) <$> bf stash) reArguments
233+ pure (offset, EndpointOption reEndpointFunc args)
224234 )
225235 reifiedApi
226−
227− execute :: (MonadState FuzzState m, MonadIO m, V.RecordToList as, V.RMap as)
228− => FuzzOp
229− -> V.Curried as (IO (Either ServerError (NonEmpty Dynamic)))
230− -> V.Rec (TypedF V.Identity) as
231− -> m ()
236+ execute ::
237+ (MonadState FuzzState m, MonadIO m, V.RecordToList as, V.RMap as) =>
238+ FuzzOp ->
239+ V.Curried as (IO (Either InteractionError (NonEmpty (Dynamic, Int)))) ->
240+ V.Rec (TypedF V.Identity) as ->
241+ m ()
232242 execute fuzzop func args = do
233− liftIO $ print fuzzop
234− st <- get
235− let showable = unlines $ ("args":map show argTypes)
236− <> ["fuzzop"
237− , show fuzzop
238− -- ,"dyncall"
239− -- ,show (dynTypeRep dyncall)
240− ,"state"
241− ,show st]
242− liftIO $ putStrLn showable
243+ (liftIO . logInfo . show . (fuzzop,) . stash) =<< get
243244 liftIO (V.runcurry' func argVals) >>= \case
244− -- parameterise this
245− Left (serverError :: ServerError) ->
246− case errHTTPCode serverError of
247− 500 -> throw serverError
248− _ -> do
249− liftIO $ print ("ignoring non-500 error" , serverError)
250− Right (dyn :: NEL.NonEmpty Dynamic) -> do
251− liftIO $ print ("storing", fmap dynTypeRep dyn)
252− modify' (\fs@FuzzState{..} ->
253− fs { stash = addToStash (NEL.toList dyn) stash } )
245+ Left (e::InteractionError) ->
246+ if fatalError e
247+ then throw e
248+ else pure ()
249+ Right (dyn :: NEL.NonEmpty (Dynamic, Int)) ->
250+ modify'
251+ ( \fs@FuzzState {..} ->
252+ fs {stash = addToStash (NEL.toList dyn) stash}
253+ )
254254 where
255255 argVals = V.rmap (\(_ :*: V.Identity x) -> V.Identity x) args
256− argTypes = recordToList' (\(tr :*: _) -> R.SomeTypeRep tr) args
257−
258− go :: (MonadState FuzzState m, MonadIO m, MonadBaseControl IO m)
259− => m ()
256+ -- argTypes = recordToList' (\(tr :*: _) -> R.SomeTypeRep tr) args
257+ go ::
258+ (MonadState FuzzState m, MonadIO m, MonadBaseControl IO m) =>
259+ m ()
260260 go = withOp $ \op func args -> do
261− catches (execute op func args)
262− [ Handler (\(e :: SomeAsyncException) -> throw e)
263− , Handler (\(e :: SomeException) -> do
264− displayDiagnostics =<< get
265− throw . RoboservantException ServerCrashed (Just e) =<< get)
261+ catches
262+ (execute op func args)
263+ [ Handler (\(e :: SomeAsyncException) -> throw e),
264+ Handler
265+ ( \(e :: SomeException) ->
266+ throw . RoboservantException ServerCrashed (Just e) =<< get
267+ )
266268 ]
267− catch (liftIO checker)
268− (\(e :: SomeException) -> throw . RoboservantException CheckerFailed (Just e) =<< get)
269−
270−addToStash :: [Dynamic]
271− -> Stash
272− -> Stash
269+ catch
270+ (liftIO healthCheck)
271+ (\(e :: SomeException) -> throw . RoboservantException CheckerFailed (Just e) =<< get)
272+
273+addToStash ::
274+ [(Dynamic, Int)] ->
275+ Stash ->
276+ Stash
273277addToStash result stash =
274− foldr (\(Dynamic tr x) (Stash dict) -> Stash $
275− DM.insertWith renumber tr (StashValue (([Provenance (R.SomeTypeRep tr) 0],x):|[])) dict
278+ foldr
279+ ( \(Dynamic tr x, hashed) (Stash dict) ->
280+ Stash $
281+ DM.insertWith
282+ renumber
283+ tr
284+ (StashValue (([Provenance (R.SomeTypeRep tr) 0], x) :| []) (IntSet.singleton hashed))
285+ dict
276286 )
277287 stash
278288 result
279289 where
280− renumber :: StashValue a
281− -> StashValue a
282− -> StashValue a
283− renumber (StashValue singleDyn) (StashValue l) = StashValue $ case NEL.toList singleDyn of
284− [([Provenance tr _], dyn)] -> l
285− <> pure ([Provenance tr (length (NEL.last l) + 1)], dyn)
286− _ -> error "should be impossible"
287−
290+ renumber ::
291+ StashValue a ->
292+ StashValue a ->
293+ StashValue a
294+ renumber (StashValue singleDyn singleHash) orig@(StashValue l intSet)
295+ | not $ IntSet.null (singleHash `IntSet.intersection` intSet) = orig
296+ | otherwise =
297+ StashValue
298+ ( case NEL.toList singleDyn of
299+ [([Provenance tr _], dyn)] ->
300+ l <> pure ([Provenance tr (length (NEL.last l) + 1)], dyn)
301+ _ -> error "should be impossible"
302+ )
303+ (IntSet.union singleHash intSet)
288304
289305-- why isn't this in vinyl?
290−recordToList'
291− :: (V.RecordToList as, V.RMap as)
292− => (forall x. f x -> a)
293− -> V.Rec f as
294− -> [a]
306+recordToList' ::
307+ (V.RecordToList as, V.RMap as) =>
308+ (forall x. f x -> a) ->
309+ V.Rec f as ->
310+ [a]
295311recordToList' f = V.recordToList . V.rmap (V.Const . f)