@@ -1,5 +1,8 @@
11{-# LANGUAGE AllowAmbiguousTypes #-}
2+{-# LANGUAGE DataKinds #-}
3+{-# LANGUAGE DerivingStrategies #-}
24{-# LANGUAGE FlexibleContexts #-}
5+{-# LANGUAGE FlexibleInstances #-}
36{-# LANGUAGE GADTs #-}
47{-# LANGUAGE LambdaCase #-}
58{-# LANGUAGE PolyKinds #-}
@@ -7,75 +10,71 @@
710{-# LANGUAGE RecordWildCards #-}
811{-# LANGUAGE ScopedTypeVariables #-}
912{-# LANGUAGE TupleSections #-}
10−
13+{-# LANGUAGE TypeApplications #-}
1114{-# LANGUAGE TypeFamilies #-}
15+
1216{-# LANGUAGE UndecidableInstances #-}
1317
1418module Roboservant.Direct
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 (..),
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(..)
2424 )
2525where
2626
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)
44−import qualified Data.Dependent.Map as DM
45−import Data.Dynamic (Dynamic (..))
46−import qualified Data.IntSet as IntSet
47−import Data.List.NonEmpty (NonEmpty (..))
48−import qualified Data.List.NonEmpty as NEL
49−import Data.Maybe (mapMaybe)
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)
5037import 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
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 ((:*:)(..))
5449import qualified Data.Vinyl.Functor as V
55−import GHC.Generics ((:*:) (..))
50+import qualified Data.Vinyl.Curry as V
51+import qualified Data.Dependent.Map as DM
52+import qualified Data.Vinyl as V
53+import 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
5659import Roboservant.Types
5760 ( ApiOffset (..),
58− Argument (..),
59− InteractionError(..),
60− Provenance (..),
61− ReifiedApi,
62− ReifiedEndpoint (..),
63− Stash (..),
64− StashValue (..),
65− TypedF,
61+ FlattenServer (..),
62+-- ReifiedApi,
63+ ToReifiedApi (..),
64+
65+ ReifiedEndpoint(..),
66+ Argument(..),
67+ TypedF
68+
6669 )
67−import Roboservant.Types.Config
6870
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− fuzzState :: FuzzState
77− }
78− deriving (Show)
74+ { failureReason :: FailureType
75+ , serverException :: Maybe SomeException
76+ , fuzzState :: FuzzState
77+ } deriving (Show)
7978
8079instance Exception RoboservantException
8180
@@ -84,228 +83,214 @@ data FailureType
8483 | CheckerFailed
8584 | NoPossibleMoves
8685 | InsufficientCoverage Double
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)
86+ deriving (Show,Eq)
10387
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− }
11188
112−data StopReason
113− = TimedOut
114− | HitMaxIterations
115− deriving (Show, Eq)
116−
117−data Report
118− = Report
119− { textual :: String,
120− rsException :: RoboservantException
121− }
122− deriving (Show)
89+data FuzzOp = FuzzOp
90+ { apiOffset :: ApiOffset
91+ , provenance :: [Provenance]
92+ } deriving (Show,Eq)
12393
94+data Config
95+ = Config
96+ { seed :: [Dynamic]
97+ , maxRuntime :: Integer -- seconds to test for
98+ , maxReps :: Integer
99+ , rngSeed :: Int
100+ , coverageThreshold :: Double
101+ }
124102
103+data FuzzState = FuzzState
104+ { path :: [FuzzOp]
105+ , stash :: Stash
106+ , currentRng :: StdGen
107+ }
108+ deriving Show
125109
126−-- fuzzClient :: Client api -> Config -> IO (Maybe Report)
127−-- fuzzClient = undefined
110+data EndpointOption = forall as. (V.RecordToList as, V.RMap as) => EndpointOption
111+ { eoCall :: V.Curried as (IO (Either ServerError (NonEmpty Dynamic)))
112+ , eoArgs :: V.Rec (TypedF StashValue) as
113+ }
128114
115+data StopReason
116+ = TimedOut
117+ | HitMaxIterations
118+ deriving (Show,Eq)
129119
120+data Report = Report
121+ { textual :: String
122+ , rsException :: RoboservantException}
123+ deriving (Show)
130124
131−fuzz' ::
132− ReifiedApi ->
133− Config ->
134− IO (Maybe Report)
135−fuzz' reifiedApi Config {..} = handle (pure . Just . formatException) $ do
125+fuzz :: forall api. (FlattenServer api, ToReifiedApi (Endpoints api))
126+ => Server api
127+ -> Config
128+ -> IO ()
129+ -> IO (Maybe Report)
130+fuzz server Config{..} checker = handle (pure . Just . formatException) $ do
136131 let path = []
137132 stash = addToStash seed mempty
138133 currentRng = mkStdGen rngSeed
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
134+
135+ print ("Initial seed", seed, stash)
136+ deadline :: UTCTime <- addUTCTime (fromInteger $ maxRuntime * 1000000) <$> getCurrentTime
137+ (stopreason, fs ) <- runStateT
138+ (untilDone (maxReps, deadline) go <* (evaluateCoverage =<< get)) FuzzState{..}
139+ print stopreason
145140 pure Nothing
146141 where
147142 -- something less terrible later
148143 formatException :: RoboservantException -> Report
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 {..}
144+ formatException r@(RoboservantException failureType exception _state) = Report
145+ (unlines [ show failureType , show exception ])
146+ r
147+
148+ displayDiagnostics FuzzState{..} = liftIO $ do
149+ putStrLn "api endpoints covered"
150+ mapM_ print (Set.toList $ Set.fromList $ map apiOffset path)
151+ putStrLn ""
152+ putStrLn "types in stash"
153+ DM.forWithKey_ (getStash stash) $ \k v ->
154+ print (NEL.length $ getStashValue v)
155+ -- mapM_
156+ -- (print . second NEL.length)
157+ -- (sortOn (show . fst) $ Map.toList $ getStash stash)
158+
159+ -- evaluateCoverage :: FuzzState -> m ()
160+ evaluateCoverage f@FuzzState{..}
164161 | coverage > coverageThreshold = pure ()
165162 | otherwise = do
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
163+ displayDiagnostics f
164+ throw $ RoboservantException (InsufficientCoverage coverage) Nothing f
165+ where hitRoutes = fromIntegral . Set.size . Set.fromList $ map apiOffset path
166+ totalRoutes = fromIntegral routeCount
167+ coverage = hitRoutes / totalRoutes
168+
169+
170+ untilDone :: MonadIO m => (Integer,UTCTime) -> m a -> m StopReason
171+ untilDone (0,_) _ = pure HitMaxIterations
174172 untilDone (n, deadline) action = do
175173 now <- liftIO getCurrentTime
176174 if now > deadline
177175 then pure TimedOut
178176 else do
179− _ <- action
180− untilDone (n -1, deadline) action
177+ action
178+ untilDone (n-1, deadline) action
181179
180+ reifiedApi = toReifiedApi (flattenServer @api server) (Proxy @(Endpoints api))
182181 routeCount = length reifiedApi
183− elementOrFail ::
184− (MonadState FuzzState m, MonadIO m) =>
185− [a] ->
186− m a
187− elementOrFail [] = liftIO . throw . RoboservantException NoPossibleMoves Nothing =<< get
182+
183+ elementOrFail :: (MonadState FuzzState m, MonadIO m)
184+ => [a] -> m a
185+ elementOrFail [] = liftIO . throw . RoboservantException NoPossibleMoves Nothing =<< get
188186 elementOrFail l = do
189187 st <- get
190− let (index, newGen) = randomR (0, length l - 1) (currentRng st)
191− modify' $ \st' -> st' {currentRng = newGen}
188+ let (index,newGen) = randomR (0, length l - 1) (currentRng st)
189+ modify' $ \st' -> st' { currentRng = newGen }
192190 pure (l !! index)
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
191+
192+ withOp :: (MonadState FuzzState m, MonadIO m)
193+ => (forall as. (V.RecordToList as, V.RMap as)
194+ => FuzzOp
195+ -> V.Curried as (IO (Either ServerError (NonEmpty Dynamic)))
196+ -> V.Rec (TypedF V.Identity) as -> m r
197+ )
198+ -> m r
203199 withOp callback = do
204200 -- choose a call to make, from the endpoints with fillable arguments.
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)
201+ (offset, EndpointOption{..}) <- elementOrFail . options =<< get
202+ r <- V.rtraverse
203+ (\(tr :*: StashValue svs) -> elementOrFail $
204+ zipWith (\i xy -> V.Const i :*: tr :*: xy)
205+ [0..]
206+ (NEL.toList svs)
207+ )
208+ eoArgs
209+ let pathSegment = FuzzOp offset $
210+ recordToList'
211+ (\(V.Const index :*: tr :*: _) -> Provenance (R.SomeTypeRep tr) index)
224212 r
225− modify' (\f -> f {path = path f <> [pathSegment]})
213+ argValues = V.rmap
214+ (\(_ :*: tr :*: (_, x)) -> tr :*: V.Identity x)
215+ r
216+ modify' (\f -> f { path = path f <> [pathSegment] })
226217 callback pathSegment eoCall argValues
227218 where
228219 options :: FuzzState -> [(ApiOffset, EndpointOption)]
229− options FuzzState {..} =
220+ options FuzzState{..} =
230221 mapMaybe
231− ( \(offset, ReifiedEndpoint {..}) -> do
232− args <- V.rtraverse (\(tr :*: Argument bf) -> (tr :*:) <$> bf stash) reArguments
233− pure (offset, EndpointOption reEndpointFunc args)
222+ ( \(offset, ReifiedEndpoint{..}) -> do
223+ args <- V.rtraverse (\(tr :*: Argument bf) -> (tr :*:) <$> bf stash) reArguments
224+ pure (offset, EndpointOption reEndpointFunc args)
234225 )
235226 reifiedApi
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 ()
227+
228+ execute :: (MonadState FuzzState m, MonadIO m, V.RecordToList as, V.RMap as)
229+ => FuzzOp
230+ -> V.Curried as (IO (Either ServerError (NonEmpty Dynamic)))
231+ -> V.Rec (TypedF V.Identity) as
232+ -> m ()
242233 execute fuzzop func args = do
243− (liftIO . logInfo . show . (fuzzop,) . stash) =<< get
234+ (liftIO . print . (fuzzop,) . stash ) =<< get
235+ st <- get
236+ let showable = unlines $ ("args":map show argTypes)
237+ <> ["fuzzop"
238+ , show fuzzop
239+ -- ,"dyncall"
240+ -- ,show (dynTypeRep dyncall)
241+ ,"state"
242+ ]
243+ -- liftIO $ putStrLn showable
244244 liftIO (V.runcurry' func argVals) >>= \case
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− )
245+ -- parameterise this
246+ Left (serverError :: ServerError) ->
247+ case errHTTPCode serverError of
248+ 500 -> throw serverError
249+ _ -> do
250+ liftIO $ print ("ignoring non-500 error" , serverError)
251+ Right (dyn :: NEL.NonEmpty Dynamic) -> do
252+ -- liftIO $ print ("storing", fmap dynTypeRep dyn)
253+ modify' (\fs@FuzzState{..} ->
254+ fs { stash = addToStash (NEL.toList dyn) stash } )
254255 where
255256 argVals = V.rmap (\(_ :*: V.Identity x) -> V.Identity x) args
256− -- argTypes = recordToList' (\(tr :*: _) -> R.SomeTypeRep tr) args
257− go ::
258− (MonadState FuzzState m, MonadIO m, MonadBaseControl IO m) =>
259− m ()
257+ argTypes = recordToList' (\(tr :*: _) -> R.SomeTypeRep tr) args
258+
259+ go :: (MonadState FuzzState m, MonadIO m, MonadBaseControl IO m)
260+ => m ()
260261 go = withOp $ \op func args -> do
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− )
262+ catches (execute op func args)
263+ [ Handler (\(e :: SomeAsyncException) -> throw e)
264+ , Handler (\(e :: SomeException) -> do
265+ displayDiagnostics =<< get
266+ throw . RoboservantException ServerCrashed (Just e) =<< get)
268267 ]
269− catch
270− (liftIO healthCheck)
271− (\(e :: SomeException) -> throw . RoboservantException CheckerFailed (Just e) =<< get)
272−
273−addToStash ::
274− [(Dynamic, Int)] ->
275− Stash ->
276− Stash
268+ catch (liftIO checker)
269+ (\(e :: SomeException) -> throw . RoboservantException CheckerFailed (Just e) =<< get)
270+
271+addToStash :: [Dynamic]
272+ -> Stash
273+ -> Stash
277274addToStash result stash =
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
275+ foldr (\(Dynamic tr x) (Stash dict) -> Stash $
276+ DM.insertWith renumber tr (StashValue (([Provenance (R.SomeTypeRep tr) 0],x):|[])) dict
286277 )
287278 stash
288279 result
289280 where
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)
281+ renumber :: StashValue a
282+ -> StashValue a
283+ -> StashValue a
284+ renumber (StashValue singleDyn) (StashValue l) = StashValue $ case NEL.toList singleDyn of
285+ [([Provenance tr _], dyn)] -> l
286+ <> pure ([Provenance tr (length (NEL.last l) + 1)], dyn)
287+ _ -> error "should be impossible"
288+
304289
305290-- why isn't this in vinyl?
306−recordToList' ::
307− (V.RecordToList as, V.RMap as) =>
308− (forall x. f x -> a) ->
309− V.Rec f as ->
310− [a]
291+recordToList'
292+ :: (V.RecordToList as, V.RMap as)
293+ => (forall x. f x -> a)
294+ -> V.Rec f as
295+ -> [a]
311296recordToList' f = V.recordToList . V.rmap (V.Const . f)