Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 38 additions & 23 deletions webapi-session/src/WebApi/Client/Session.hs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ module WebApi.Client.Session
, beginStep
, setStepHeaders
, getLastResponse
, getLastResponseBody

, freshToken
, freshTokens
Expand Down Expand Up @@ -319,8 +320,8 @@ testClientWith :: forall meth r app.
-> WebApiSession app (Response meth r)
testClientWith extras creq = fst <$> testClientRawWith extras creq

-- | 'testClientWith', answering the wire's status and headers as received
-- beside the typed response.
-- | 'testClientWith', answering the wire's status, headers and body as
-- received beside the typed response.
testClientRawWith :: forall meth r app.
( WebApi app
, app ~ NamespaceOf r
Expand All @@ -340,15 +341,15 @@ testClientRawWith :: forall meth r app.
) =>
[H.Header]
-> ClientRequest meth r
-> WebApiSession app (Response meth r, (H.Status, [H.Header]))
-> WebApiSession app (Response meth r, (H.Status, [H.Header], LBS.ByteString))
testClientRawWith extras (MKClientRequest creq) = do
waiReq0 <- liftIO $ toWaiRequest creq
let waiReq = case extras of
[] -> waiReq0
_ -> waiReq0 { requestHeaders = extras ++ requestHeaders waiReq0 }
sresp@SResponse {simpleStatus = status, simpleHeaders = hdrs} <- WebApiSession $ request waiReq
sresp@SResponse {simpleStatus = status, simpleHeaders = hdrs, simpleBody = body} <- WebApiSession $ request waiReq
resp <- WebApiSession $ fromResponse sresp
pure (resp, (status, hdrs))
pure (resp, (status, hdrs, body))


runWebApi :: forall app a.
Expand All @@ -372,6 +373,11 @@ data ClientsState = ClientsState
-- that reads a header the contract does not declare (an error id a
-- failure names, say). 'Nothing' until a call answers, after a
-- transport failure, and at 'beginStep'
, lastBody :: Maybe LBS.ByteString
-- ^ the body of that same response, as received — for a report of
-- what the step got back (a trace), which the typed value, decoded
-- and only 'Show'able, cannot stand for. 'Nothing' exactly when
-- 'lastResponse' is
}


Expand All @@ -391,8 +397,8 @@ initFreshSupply = FreshSupply { nonce = "", next = 0, current = mempty }
-- | Start a step: the tokens made for the previous one are forgotten,
-- and so are its headers and the answer it last saw.
beginStep :: WebApiSessions apps ()
beginStep = modify' $ \ClientsState {clientStates, freshSupply = FreshSupply {nonce, next}} ->
ClientsState {clientStates, freshSupply = FreshSupply {nonce, next, current = mempty}, stepHeaders = [], lastResponse = Nothing}
beginStep = modify' $ \st@ClientsState {freshSupply = FreshSupply {nonce, next}} ->
st {freshSupply = FreshSupply {nonce, next, current = mempty}, stepHeaders = [], lastResponse = Nothing, lastBody = Nothing}

-- | Headers the step being run wants on its wire requests — set after
-- 'beginStep', merged in front by both transports, gone at the next step.
Expand All @@ -406,17 +412,22 @@ setStepHeaders hs = modify' $ \st -> st {stepHeaders = hs}
getLastResponse :: WebApiSessions apps (Maybe (H.Status, [H.Header]))
getLastResponse = gets $ \ClientsState {lastResponse} -> lastResponse

-- | The body of the wire's last answer, as received (see
-- 'getLastResponse'): what a report shows the step got back.
getLastResponseBody :: WebApiSessions apps (Maybe LBS.ByteString)
getLastResponseBody = gets $ \ClientsState {lastBody} -> lastBody


-- | The token for a label in the step being run: made once per step (the
-- same label asks again and gets the same one), never twice in a run.
freshToken :: Text -> WebApiSessions apps Text
freshToken label = do
ClientsState {clientStates, freshSupply = FreshSupply {nonce, next, current}, stepHeaders, lastResponse} <- get
st@ClientsState {freshSupply = FreshSupply {nonce, next, current}} <- get
case M.lookup label current of
Just t -> pure t
Nothing -> do
let t = nonce <> "n" <> T.pack (show next)
put ClientsState {clientStates, freshSupply = FreshSupply {nonce, next = next + 1, current = M.insert label t current}, stepHeaders, lastResponse}
put st {freshSupply = FreshSupply {nonce, next = next + 1, current = M.insert label t current}}

pure t

Expand Down Expand Up @@ -459,7 +470,7 @@ initApps = Applications
}

initClientsState :: ClientsState
initClientsState = ClientsState { clientStates = mempty, freshSupply = initFreshSupply, stepHeaders = [], lastResponse = Nothing }
initClientsState = ClientsState { clientStates = mempty, freshSupply = initFreshSupply, stepHeaders = [], lastResponse = Nothing, lastBody = Nothing }


newtype WebApiSessions (apps :: [Type]) a = WebApiSessions (ReaderT Applications (StateT ClientsState IO) a)
Expand Down Expand Up @@ -500,16 +511,20 @@ testClients creq = do
case M.lookup appRep css of
Nothing -> error $ "Panic: app not found for: " <> show appRep
Just cstate -> do
((a, raw), s) <- liftIO $ runStateT (runReaderT (runWebApiSession $ testClientRawWith extras creq) app) cstate
modify' $ \st@ClientsState {clientStates = css'} -> st {clientStates = M.insert appRep s css', lastResponse = Just raw}
((a, (status, hdrs, body)), s) <- liftIO $ runStateT (runReaderT (runWebApiSession $ testClientRawWith extras creq) app) cstate
modify' $ \st@ClientsState {clientStates = css'} -> st {clientStates = M.insert appRep s css', lastResponse = Just (status, hdrs), lastBody = Just body}
pure a

Nothing -> case M.lookup appRep external of
Just ext -> do
ClientsState {clientStates = css, stepHeaders = extras} <- get
let cstate = M.findWithDefault WaiInt.initState appRep css
(a, raw, s) <- liftIO $ externalClient extras ext cstate (fromClientRequest creq)
modify' $ \st@ClientsState {clientStates = css'} -> st {clientStates = M.insert appRep s css', lastResponse = raw}
modify' $ \st@ClientsState {clientStates = css'} -> st
{ clientStates = M.insert appRep s css'
, lastResponse = (\(status, hdrs, _) -> (status, hdrs)) <$> raw
, lastBody = (\(_, _, body) -> body) <$> raw
}
pure a

Nothing -> error $ "Panic: app not found for: " <> show appRep
Expand All @@ -518,8 +533,8 @@ testClients creq = do
-- following (the model asserts on 3xx + Location, exactly as wai-test does),
-- cookies out merged back into the jar. Transport failures surface as
-- 'OtherError' rather than exceptions so the model can judge them. The
-- raw status and headers come back beside the typed response (none after
-- a transport failure).
-- raw status, headers and body come back beside the typed response (none
-- after a transport failure).

externalClient :: forall meth r.
( ToParam 'PathParam (PathParam meth r)
Expand All @@ -535,7 +550,7 @@ externalClient :: forall meth r.
, ToHListRecTuple (StripContents (RequestBody meth r))
, MkPathFormatString r
, SingMethod meth
) => [H.Header] -> ExternalApp -> WaiInt.ClientState -> Request meth r -> IO (Response meth r, Maybe (H.Status, [H.Header]), WaiInt.ClientState)
) => [H.Header] -> ExternalApp -> WaiInt.ClientState -> Request meth r -> IO (Response meth r, Maybe (H.Status, [H.Header], LBS.ByteString), WaiInt.ClientState)

externalClient extras ExternalApp {baseRequest, manager} cstate req = do
now <- getCurrentTime
Expand Down Expand Up @@ -577,7 +592,7 @@ externalClient extras ExternalApp {baseRequest, manager} cstate req = do
(HC.responseHeaders hresp)
(M.toList $ fmap renderSetCookieBS cooks)
(HC.responseBody hresp)
pure (resp, Just (HC.responseStatus hresp, HC.responseHeaders hresp), cstate')
pure (resp, Just (HC.responseStatus hresp, HC.responseHeaders hresp, HC.responseBody hresp), cstate')


-- | A stored 'SetCookie' as an http-client cookie for @host@. A cookie without
Expand Down Expand Up @@ -637,10 +652,10 @@ addApp waapp WebApiSessionsConfig {applications, clientsState} =
app = getWaiApp waapp
appRep = typeRep (Proxy @app)
Applications {native, external} = applications
ClientsState {clientStates = cstate, freshSupply, stepHeaders, lastResponse} = clientsState
ClientsState {clientStates = cstate} = clientsState
in WebApiSessionsConfig
{ applications = Applications { native = M.insert appRep app native, external}
, clientsState = ClientsState { clientStates = M.insert appRep WaiInt.initState cstate, freshSupply, stepHeaders, lastResponse }
, clientsState = clientsState { clientStates = M.insert appRep WaiInt.initState cstate }
}

-- | Register an app reached over HTTP. @base@ is the parsed base request —
Expand All @@ -651,10 +666,10 @@ addExternalApp base mgr WebApiSessionsConfig {applications, clientsState} =
let
appRep = typeRep (Proxy @app)
Applications {native, external} = applications
ClientsState {clientStates = cstate, freshSupply, stepHeaders, lastResponse} = clientsState
ClientsState {clientStates = cstate} = clientsState
in WebApiSessionsConfig
{ applications = Applications { native, external = M.insert appRep (ExternalApp base mgr) external }
, clientsState = ClientsState { clientStates = M.insert appRep WaiInt.initState cstate, freshSupply, stepHeaders, lastResponse }
, clientsState = clientsState { clientStates = M.insert appRep WaiInt.initState cstate }
}

-- | Run the sessions; each run gets its own nonce for fresh tokens.
Expand All @@ -665,8 +680,8 @@ runWebApis' :: WebApiSessionsConfig apps -> WebApiSessions apps a -> IO (a, WebA
runWebApis' WebApiSessionsConfig {applications, clientsState} (WebApiSessions sess) = do
n <- newNonce
let
ClientsState {clientStates, freshSupply = FreshSupply {next, current}, stepHeaders, lastResponse} = clientsState
st0 = ClientsState {clientStates, freshSupply = FreshSupply {nonce = n, next, current}, stepHeaders, lastResponse}
ClientsState {freshSupply = FreshSupply {next, current}} = clientsState
st0 = clientsState {freshSupply = FreshSupply {nonce = n, next, current}}

(a, clientsStateNew) <- runStateT (runReaderT sess applications) st0
pure (a, WebApiSessionsConfig {applications, clientsState = clientsStateNew})
Expand Down
2 changes: 1 addition & 1 deletion webapi-session/webapi-session.cabal
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
cabal-version: 3.0
name: webapi-session
version: 0.1.0.0
version: 0.1.1.0
synopsis: The concrete session client over webapi contracts
-- Moved out of webapi-test (M8a): multi-app routing, wai + http-client
-- transports, cookie jars, fresh values. Test-named packages never
Expand Down
28 changes: 28 additions & 0 deletions webapi-test/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,33 @@
# Revision history for webapi-test

## 0.2.0.0 -- 2026-11-15 (zenbridge #2712: a run's trace)

* **A run's trace, as data** (`Test.WebApi.Trace`, qc-dynamic). A
`Recorder` keeps one record per step a case played: the request as sent
(fresh values filled, credentials masked, the body clipped), the answer as
received (status, body, the step's value), every check by name with
whether it held, the labels that held, the model after the step (each
class with its values) and the stage before and after. For the run
(`RunTrace`): a line per generated case and per narrowing try (`taken`
when it still failed), the first failing case and the narrowed one in
full, and the label and move counts over the generated cases; JSON in
snake_case. `propDLTraced` records a property; the cases close through
QuickCheck's own callbacks (`PostTest` after every test, narrowing tries
included; `PostFinalFailure` on the narrowed case). `propDL` records
nothing, as before.
* **Checks by name.** A step's postcondition is a list of named checks
(`andCheck`; `andPostcondition` adds one named `postcondition`,
`ensuresRefinement`/`refutesRefinement` add `ensures <n>`/`refutes <n>`).
Every check runs and every failure is reported; it was the first only.
* **Labels** (`andClassify`): a step gives its case a label where a
predicate holds, through QuickCheck's `classify`; a label never fails.
* **Where a step was written** (`setStep`, `StepInfo`): a rule's trail,
summary and operation name, for the trace; it also sets the label.
`EffectCall` carries one (a new field, before the variables).
* **A model's stages**: `WebApiGlobalStateModel` gains `appStageOf`
(`noStage` for a model with none).
* `WebApiSessionsCxt` carries the recorder (`tracingCxt`).

## 0.1.0.0 -- YYYY-mm-dd

* First version. Released on an unsuspecting world.
36 changes: 32 additions & 4 deletions webapi-test/quickcheck-dynamic/Test/WebApi/DynamicLogic.hs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
module Test.WebApi.DynamicLogic
( propDL
, propDLTraced
, prop_api
-- , runWebApiTest
-- , apiAction
Expand All @@ -22,6 +23,7 @@ import Test.QuickCheck.Monadic
import Test.QuickCheck.Monadic qualified as QC
import Data.Reflection
import Data.IORef
import Test.WebApi.Trace (Recorder, beginCase, recordedProperty)
-- import Control.Monad.IO.Class
import Control.Monad.Reader

Expand All @@ -35,6 +37,19 @@ propDL :: forall c xstate apps e s.
) => Proxy s -> (forall a. WebApiSessions apps a -> IO a) -> DL (ApiState s c xstate apps) () -> Property
propDL _ webapiRunner d = forAllDL d (prop_api undefined webapiRunner)

-- | 'propDL', each case it plays recorded into the recorder: the steps as
-- they run, the case closed when QuickCheck finishes it (a generated case
-- or a narrowing try alike; see "Test.WebApi.Trace").
propDLTraced :: forall c xstate apps e s.
( DynLogicModel xstate
, RunModel xstate IO
, XActionError e ~ Error xstate IO
, Typeable e
, Show e
, Reifies s (WebApiGlobalStateModel c xstate apps)
) => Recorder -> Proxy s -> (forall a. WebApiSessions apps a -> IO a) -> DL (ApiState s c xstate apps) () -> Property
propDLTraced rec _ webapiRunner d = recordedProperty rec $ forAllDL d (propApiWith (Just rec) webapiRunner)

prop_api :: forall c xstate apps e s.
( DynLogicModel xstate
, RunModel xstate IO
Expand All @@ -46,10 +61,23 @@ prop_api :: forall c xstate apps e s.
-> (forall a. WebApiSessions apps a -> IO a)
-> Actions (ApiState s c xstate apps)
-> Property
prop_api _newStRef webapiRunner s =
-- let
-- runner =
monadic (ioProperty . webapiRunner . flip runReaderT initWebApiSessionsCxt) $ do
prop_api _newStRef = propApiWith Nothing

-- | The actions run, recorded when there is a recorder.
propApiWith :: forall c xstate apps e s.
( DynLogicModel xstate
, RunModel xstate IO
, XActionError e ~ Error xstate IO
, Typeable e
, Show e
, Reifies s (WebApiGlobalStateModel c xstate apps)
) => Maybe Recorder
-> (forall a. WebApiSessions apps a -> IO a)
-> Actions (ApiState s c xstate apps)
-> Property
propApiWith rec webapiRunner s =
monadic (ioProperty . webapiRunner . flip runReaderT (maybe initWebApiSessionsCxt tracingCxt rec)) $ do
mapM_ (QC.run . liftIO . beginCase) rec
monitor $ counterexample "\nExecution\n"
(_anonSt, _env) <- runActions s
-- let
Expand Down
Loading
Loading