diff --git a/scripts/dev.sh b/scripts/dev.sh index 75278e5543c64..d1825ebefe428 100755 --- a/scripts/dev.sh +++ b/scripts/dev.sh @@ -484,7 +484,7 @@ elif [ "$MODE" = "test" ]; then if [ "$RUN_HLINT" = true ]; then cd "$PROJECT_ROOT/server" - hlint . + hlint src-* fi # RUN_HLINT diff --git a/server/.hlint.yaml b/server/.hlint.yaml index 2d9ec6f5b1b04..a20aad86b9cc3 100644 --- a/server/.hlint.yaml +++ b/server/.hlint.yaml @@ -35,6 +35,10 @@ # Will suggest replacing "wibbleMany [myvar]" with "wibbleOne myvar" # - error: {lhs: "wibbleMany [x]", rhs: wibbleOne x} +- warn: {lhs: "maybe (f x) f", rhs: "f . fromMaybe x"} +- warn: {lhs: "either (f . g) (f . h)", rhs: "f . either g h"} +- warn: {lhs: "onNothing x (return y)", rhs: "return (fromMaybe y x)"} +- warn: {lhs: "onLeft x (return . f)", rhs: "return (either f id x)"} # Turn on hints that are off by default # @@ -52,50 +56,27 @@ # - ignore: {name: Use let} # - ignore: {name: Use const, within: SpecialModule} # Only within certain modules -- ignore: {name: Use <$>} - ignore: {name: Reduce duplication} -- ignore: {name: Use fromMaybe} - ignore: {name: Redundant $} - ignore: {name: Redundant bracket} - ignore: {name: Use fmap} - ignore: {name: Use first} - ignore: {name: Use if} - ignore: {name: Redundant <$>} -- ignore: {name: Functor law} -- ignore: {name: Move brackets to avoid $} -- ignore: {name: Use null} -- ignore: {name: Use map once} - ignore: {name: Use ++} -- ignore: {name: Use lambda-case} - ignore: {name: Use const} - ignore: {name: Eta reduce} - ignore: {name: Redundant multi-way if} - ignore: {name: Use newtype instead of data} - ignore: {name: Use bimap} -- ignore: {name: Use section} - ignore: {name: Use $>} -- ignore: {name: Use unless} -- ignore: {name: Redundant $!} - ignore: {name: "Use ?~"} -- ignore: {name: Use Just} -- ignore: {name: Redundant flip} -- ignore: {name: Use for_} -- ignore: {name: Avoid lambda} -- ignore: {name: Use mapM} -- ignore: {name: Redundant lambda} - ignore: {name: Use <=<} -- ignore: {name: Replace case with maybe} - ignore: {name: Use sequenceA} - ignore: {name: Use camelCase} -- ignore: {name: Avoid lambda using `infix`} -- ignore: {name: Redundant irrefutable pattern} -- ignore: {name: Use tuple-section} -- ignore: {name: Use mapMaybe} -- ignore: {name: Use second} -- ignore: {name: Use isNothing} -- ignore: {name: Use maybe} - ignore: {name: Redundant return} -- ignore: {name: Unused LANGUAGE pragma} +- ignore: {name: Use <$>, within: Hasura.RQL.DDL.Metadata} +- ignore: {name: Functor law, within: Hasura.Server.AuthSpec} # Define some custom infix operators # - fixity: infixr 3 ~^#^~ @@ -103,3 +84,22 @@ # To generate a suitable file for HLint do: # $ hlint --default > .hlint.yaml + + +- group: + name: hasura-prelude + enabled: true + imports: + - package base + rules: + - warn: {lhs: "maybe b return a", rhs: "onNothing a b"} + - warn: {lhs: "maybe (return ()) b a", rhs: "onJust a b"} + - warn: {lhs: "either b return a", rhs: "onLeft a b"} + +- group: + name: data-text-extended + enabled: true + imports: + - package base + rules: + - warn: {lhs: "Data.Text.intercalate \", \" x", rhs: "commaSeparated x", note: "From Data.Text.Extended"} diff --git a/server/bench-wrk/wrk-websocket-server/src/Wrk/Server.hs b/server/bench-wrk/wrk-websocket-server/src/Wrk/Server.hs index 53e1d5e0cf00e..95e0952d75230 100644 --- a/server/bench-wrk/wrk-websocket-server/src/Wrk/Server.hs +++ b/server/bench-wrk/wrk-websocket-server/src/Wrk/Server.hs @@ -56,7 +56,7 @@ processReq conn msg lock = do catchIO :: IO (Either ErrorMessage a) -> IO (Either ErrorMessage a) catchIO f = do resIOE <- E.try f - either (return . Left . ioExToErr) return resIOE + return $ either (Left . ioExToErr) id resIOE ioExToErr :: E.SomeException -> ErrorMessage ioExToErr e = ErrorMessage $ J.object ["IOError" J..= show e ] @@ -253,5 +253,5 @@ uptoFirstMatch str = fmap T.concat $ AT.manyTill nextPossibleMatch $ AT.string s takeIncludingFirstMatch :: T.Text -> AT.Parser T.Text takeIncludingFirstMatch str = withSubStr <|> errMsg where - withSubStr = fmap (`T.append` str) $ uptoFirstMatch str + withSubStr = (`T.append` str) <$> uptoFirstMatch str errMsg = fail $ "Could not find sub-string: " <> T.unpack str diff --git a/server/src-bench-cache/Main.hs b/server/src-bench-cache/Main.hs index 09b06952b52f9..6b0f1ddc1aa73 100644 --- a/server/src-bench-cache/Main.hs +++ b/server/src-bench-cache/Main.hs @@ -35,7 +35,7 @@ main = defaultMain [ ] -- simple insert benchmark. Try to avoid drift by initialising fresh -- and measuring 1000 inserts at a time. - , env (randomInts 1000) $ \ ~rs-> + , env (randomInts 1000) $ \rs -> bgroup "insert x1000" [ -- use perRunEnv so we can be sure we're not triggering cache -- evictions in bounded due to long bootstrap batch runs @@ -45,7 +45,7 @@ main = defaultMain [ -- an eviction on each insert, all LRU counters at zero. Simulates a scan. , bench "bounded evicting scan" $ let preloaded = populate 5000 (Cache.initialise 5000) Cache.insertAllStripes - in perRunEnv (preloaded) $ \(cache, _) -> + in perRunEnv preloaded $ \(cache, _) -> V.mapM_ (\k -> Cache.insert k k cache) rs ] @@ -147,7 +147,7 @@ realisticBenches name wrk = -- We should also look into just generating a report by hand that takes -- into account per-thread misses without actually simulating them with -- burnCycles. - putStrLn $ "TIMING: " <>(show $ fromIntegral (aft - bef) / (1000*1000 :: Double)) <> "ms" + putStrLn $ "TIMING: " <> show (fromIntegral (aft - bef) / (1000*1000 :: Double)) <> "ms" -- putStrLn $ "HITS/MISSES: "<> show _hitsMisses -- DEBUGGING/FYI return () where @@ -198,9 +198,9 @@ readBenches n = env (populate n (Cache.initialise (fromIntegral $ n*2)) Cache.insertAllStripes) $ \ ~(cache, k)-> bgroup "bounded" [ bench "hit" $ - nfAppIO (\k' -> Cache.lookup k' cache) k + nfAppIO (`Cache.lookup` cache) k , bench "miss" $ - nfAppIO (\k' -> Cache.lookup k' cache) 0xDEAD + nfAppIO (`Cache.lookup` cache) 0xDEAD ] ] diff --git a/server/src-lib/Control/Arrow/Extended.hs b/server/src-lib/Control/Arrow/Extended.hs index 422f3e4335e8b..1130358637c72 100644 --- a/server/src-lib/Control/Arrow/Extended.hs +++ b/server/src-lib/Control/Arrow/Extended.hs @@ -102,7 +102,7 @@ instance Applicative (Traversal a r) where Yield v k -> Yield v ((<*> tx) . k) traversal :: (Traversable t) => t a -> Traversal a b (t b) -traversal = traverse (flip Yield Done) +traversal = traverse (`Yield` Done) -- | 'traverse' lifted to arrows. See also Note [Weird control operator types]. traverseA :: (ArrowChoice arr, Traversable t) => arr (e, (a, s)) b -> arr (e, (t a, s)) (t b) diff --git a/server/src-lib/Control/Arrow/Trans.hs b/server/src-lib/Control/Arrow/Trans.hs index d0ef64bd345b2..443655a1ffcce 100644 --- a/server/src-lib/Control/Arrow/Trans.hs +++ b/server/src-lib/Control/Arrow/Trans.hs @@ -38,7 +38,7 @@ liftEitherA :: (ArrowChoice arr, ArrowError e arr) => arr (Either e a) a liftEitherA = throwA ||| returnA {-# INLINE liftEitherA #-} -mapErrorA :: (ArrowError e arr) => arr (a, s) b -> arr (a, ((e -> e), s)) b +mapErrorA :: (ArrowError e arr) => arr (a, s) b -> arr (a, (e -> e, s)) b mapErrorA f = proc (a, (g, s)) -> (f -< (a, s)) `catchA` \e -> throwA -< g e {-# INLINE mapErrorA #-} @@ -178,7 +178,7 @@ newtype WriterA w arr a b = MkWriterA (arr (a, w) (b, w)) pattern WriterA :: (Monoid w, Arrow arr) => arr a (b, w) -> WriterA w arr a b -pattern WriterA { runWriterA } <- MkWriterA ((\f -> f . arr (, mempty)) -> runWriterA) +pattern WriterA { runWriterA } <- MkWriterA (\f -> f . arr (, mempty) -> runWriterA) where WriterA f = MkWriterA (arr (\((b, w), w1) -> let !w2 = w1 <> w in (b, w2)) . first f) {-# COMPLETE WriterA #-} diff --git a/server/src-lib/Data/URL/Template.hs b/server/src-lib/Data/URL/Template.hs index 3030f25485a95..8673f52894e71 100644 --- a/server/src-lib/Data/URL/Template.hs +++ b/server/src-lib/Data/URL/Template.hs @@ -88,7 +88,7 @@ instance Arbitrary Variable where instance Arbitrary URLTemplate where arbitrary = URLTemplate <$> listOf (oneof [genText, genVariable]) where - genText = (TIText . T.pack) <$> listOf1 (elements $ alphaNumerics <> " ://") + genText = TIText . T.pack <$> listOf1 (elements $ alphaNumerics <> " ://") genVariable = TIVariable <$> arbitrary genURLTemplate :: Gen URLTemplate diff --git a/server/src-lib/Hasura/App.hs b/server/src-lib/Hasura/App.hs index 93c55760c5b33..1686dd0ce2668 100644 --- a/server/src-lib/Hasura/App.hs +++ b/server/src-lib/Hasura/App.hs @@ -137,7 +137,7 @@ parseArgs = do rawHGEOpts <- execParser opts env <- getEnvironment let eitherOpts = runWithEnv env $ mkHGEOptions rawHGEOpts - either (printErrExit InvalidEnvironmentVariableOptionsError) return eitherOpts + onLeft eitherOpts $ printErrExit InvalidEnvironmentVariableOptionsError where opts = info (helper <*> hgeOpts) ( fullDesc <> @@ -221,7 +221,7 @@ initialiseCtx env hgeCmd rci = do pure (InitCtx httpManager instanceId loggers connInfo pool latch res, initTime) where procConnInfo = - either (printErrExit InvalidDatabaseConnectionParamsError . ("Fatal Error : " <>)) return $ mkConnInfo rci + onLeft (mkConnInfo rci) $ printErrExit InvalidDatabaseConnectionParamsError . ("Fatal Error : " <>) getMinimalPool pgLogger ci = do let connParams = Q.defaultConnParams { Q.cpConns = 1 } @@ -260,7 +260,7 @@ migrateCatalogSchema env logger pool httpManager sqlGenCtx = do runTxIO :: Q.PGPool -> Q.TxMode -> Q.TxE QErr a -> IO a runTxIO pool isoLevel tx = do eVal <- liftIO $ runExceptT $ Q.runTx pool isoLevel tx - either (printErrJExit DatabaseMigrationError) return eVal + onLeft eVal (printErrJExit DatabaseMigrationError) -- | A latch for the graceful shutdown of a server process. newtype ShutdownLatch = ShutdownLatch { unShutdownLatch :: C.MVar () } @@ -335,7 +335,7 @@ runHGEServer env ServeOptions{..} InitCtx{..} pgExecCtx initTime shutdownApp pos authModeRes <- runExceptT $ setupAuthMode soAdminSecret soAuthHook soJwtSecret soUnAuthRole _icHttpManager logger - authMode <- either (printErrExit AuthConfigurationError . T.unpack) return authModeRes + authMode <- onLeft authModeRes (printErrExit AuthConfigurationError . T.unpack) _idleGCThread <- C.forkImmortal "ourIdleGC" logger $ liftIO $ ourIdleGC logger (seconds 0.3) (seconds 10) (seconds 60) @@ -459,7 +459,7 @@ runHGEServer env ServeOptions{..} InitCtx{..} pgExecCtx initTime shutdownApp pos prepareScheduledEvents pool (Logger logger) = do liftIO $ logger $ mkGenericStrLog LevelInfo "scheduled_triggers" "preparing data" res <- liftIO $ runTx pool (Q.ReadCommitted, Nothing) unlockAllLockedScheduledEvents - either (printErrJExit EventSubSystemError) return res + onLeft res (printErrJExit EventSubSystemError) -- | shutdownEvents will be triggered when a graceful shutdown has been inititiated, it will -- get the locked events from the event engine context and the scheduled event engine context diff --git a/server/src-lib/Hasura/Backends/Postgres/Connection.hs b/server/src-lib/Hasura/Backends/Postgres/Connection.hs index 26bbfbe8e341b..c56c31ab320d4 100644 --- a/server/src-lib/Hasura/Backends/Postgres/Connection.hs +++ b/server/src-lib/Hasura/Backends/Postgres/Connection.hs @@ -46,13 +46,13 @@ import Hasura.Session data PGExecCtx = PGExecCtx - { _pecRunReadOnly :: (forall a. Q.TxE QErr a -> ExceptT QErr IO a) + { _pecRunReadOnly :: forall a. Q.TxE QErr a -> ExceptT QErr IO a -- ^ Run a Q.ReadOnly transaction - , _pecRunReadNoTx :: (forall a. Q.TxE QErr a -> ExceptT QErr IO a) + , _pecRunReadNoTx :: forall a. Q.TxE QErr a -> ExceptT QErr IO a -- ^ Run a read only statement without an explicit transaction block - , _pecRunReadWrite :: (forall a. Q.TxE QErr a -> ExceptT QErr IO a) + , _pecRunReadWrite :: forall a. Q.TxE QErr a -> ExceptT QErr IO a -- ^ Run a Q.ReadWrite transaction - , _pecCheckHealth :: (IO Bool) + , _pecCheckHealth :: IO Bool -- ^ Checks the health of this execution context } @@ -60,9 +60,9 @@ data PGExecCtx mkPGExecCtx :: Q.TxIsolation -> Q.PGPool -> PGExecCtx mkPGExecCtx isoLevel pool = PGExecCtx - { _pecRunReadOnly = (Q.runTx pool (isoLevel, Just Q.ReadOnly)) - , _pecRunReadNoTx = (Q.runTx' pool) - , _pecRunReadWrite = (Q.runTx pool (isoLevel, Just Q.ReadWrite)) + { _pecRunReadOnly = Q.runTx pool (isoLevel, Just Q.ReadOnly) + , _pecRunReadNoTx = Q.runTx' pool + , _pecRunReadWrite = Q.runTx pool (isoLevel, Just Q.ReadWrite) , _pecCheckHealth = checkDbConnection } where diff --git a/server/src-lib/Hasura/Eventing/EventTrigger.hs b/server/src-lib/Hasura/Eventing/EventTrigger.hs index 790797ef419eb..076c319813306 100644 --- a/server/src-lib/Hasura/Eventing/EventTrigger.hs +++ b/server/src-lib/Hasura/Eventing/EventTrigger.hs @@ -350,7 +350,7 @@ processError pool e retryConf decodedHeaders ep err = do respStatus = hrsStatus errResp mkInvocation ep respStatus decodedHeaders respPayload respHeaders HOther detail -> do - let errMsg = (TBS.fromLBS $ encode detail) + let errMsg = TBS.fromLBS $ encode detail mkInvocation ep 500 decodedHeaders errMsg [] liftIO $ runExceptT $ Q.runTx pool (Q.ReadCommitted, Just Q.ReadWrite) $ do insertInvocation invocation @@ -381,7 +381,7 @@ retryOrSetError e retryConf err = do mkInvocation :: EventPayload -> Int -> [HeaderConf] -> TBS.TByteString -> [HeaderConf] - -> (Invocation 'EventType) + -> Invocation 'EventType mkInvocation ep status reqHeaders respBody respHeaders = let resp = if isClientError status then mkClientErr respBody @@ -506,7 +506,7 @@ instance Q.ToPrepArg EventIdArray where -- when a graceful shutdown is initiated. unlockEvents :: [EventId] -> Q.TxE QErr Int unlockEvents eventIds = - (runIdentity . Q.getRow) <$> Q.withQE defaultTxErrorHandler + runIdentity . Q.getRow <$> Q.withQE defaultTxErrorHandler [Q.sql| WITH "cte" AS (UPDATE hdb_catalog.event_log diff --git a/server/src-lib/Hasura/Eventing/HTTP.hs b/server/src-lib/Hasura/Eventing/HTTP.hs index 4e96f742c176b..6c7e41b89f3e2 100644 --- a/server/src-lib/Hasura/Eventing/HTTP.hs +++ b/server/src-lib/Hasura/Eventing/HTTP.hs @@ -132,7 +132,7 @@ data Invocation (a :: TriggerTypes) { iEventId :: EventId , iStatus :: Int , iRequest :: WebhookRequest - , iResponse :: (Response a) + , iResponse :: Response a } data ExtraLogContext diff --git a/server/src-lib/Hasura/Eventing/ScheduledTrigger.hs b/server/src-lib/Hasura/Eventing/ScheduledTrigger.hs index f8c9d19ebf401..ac998091f6399 100644 --- a/server/src-lib/Hasura/Eventing/ScheduledTrigger.hs +++ b/server/src-lib/Hasura/Eventing/ScheduledTrigger.hs @@ -321,7 +321,7 @@ insertCronEventsFor cronTriggersWithStats = do } Q.unitQE defaultTxErrorHandler (Q.fromText insertCronEventsSql) () False where - toArr (CronEventSeed n t) = [(triggerNameToTxt n), (formatTime' t)] + toArr (CronEventSeed n t) = [triggerNameToTxt n, formatTime' t] toTupleExp = TupleExp . map SELit insertCronEvents :: [CronEventSeed] -> Q.TxE QErr () @@ -336,7 +336,7 @@ insertCronEvents events = do } Q.unitQE defaultTxErrorHandler (Q.fromText insertCronEventsSql) () False where - toArr (CronEventSeed n t) = [(triggerNameToTxt n), (formatTime' t)] + toArr (CronEventSeed n t) = [triggerNameToTxt n, formatTime' t] toTupleExp = TupleExp . map SELit generateCronEventsFrom :: UTCTime -> CronTriggerInfo-> [CronEventSeed] @@ -542,7 +542,7 @@ processError pgpool se decodedHeaders type' reqJson err = do respStatus = hrsStatus errResp mkInvocation se respStatus decodedHeaders respPayload respHeaders reqJson HOther detail -> do - let errMsg = (TBS.fromLBS $ J.encode detail) + let errMsg = TBS.fromLBS $ J.encode detail mkInvocation se 500 decodedHeaders errMsg [] reqJson liftExceptTIO $ Q.runTx pgpool (Q.ReadCommitted, Just Q.ReadWrite) $ do @@ -648,7 +648,7 @@ mkInvocation -> TBS.TByteString -> [HeaderConf] -> J.Value - -> (Invocation 'ScheduledType) + -> Invocation 'ScheduledType mkInvocation ScheduledEventFull {sefId} status reqHeaders respBody respHeaders reqBodyJson = let resp = if isClientError status then mkClientErr respBody @@ -660,7 +660,7 @@ mkInvocation ScheduledEventFull {sefId} status reqHeaders respBody respHeaders r (mkWebhookReq reqBodyJson reqHeaders invocationVersionST) resp -insertInvocation :: (Invocation 'ScheduledType) -> ScheduledEventType -> Q.TxE QErr () +insertInvocation :: Invocation 'ScheduledType -> ScheduledEventType -> Q.TxE QErr () insertInvocation invo type' = do case type' of Cron -> do @@ -784,7 +784,7 @@ instance Q.ToPrepArg ScheduledEventIdArray where unlockCronEvents :: [ScheduledEventId] -> Q.TxE QErr Int unlockCronEvents scheduledEventIds = - (runIdentity . Q.getRow) <$> Q.withQE defaultTxErrorHandler + runIdentity . Q.getRow <$> Q.withQE defaultTxErrorHandler [Q.sql| WITH "cte" AS (UPDATE hdb_catalog.hdb_cron_events @@ -796,7 +796,7 @@ unlockCronEvents scheduledEventIds = unlockOneOffScheduledEvents :: [ScheduledEventId] -> Q.TxE QErr Int unlockOneOffScheduledEvents scheduledEventIds = - (runIdentity . Q.getRow) <$> Q.withQE defaultTxErrorHandler + runIdentity . Q.getRow <$> Q.withQE defaultTxErrorHandler [Q.sql| WITH "cte" AS (UPDATE hdb_catalog.hdb_scheduled_events diff --git a/server/src-lib/Hasura/GraphQL/Execute/Action.hs b/server/src-lib/Hasura/GraphQL/Execute/Action.hs index 7212ad6151e0e..05d85c3a0e9da 100644 --- a/server/src-lib/Hasura/GraphQL/Execute/Action.hs +++ b/server/src-lib/Hasura/GraphQL/Execute/Action.hs @@ -320,7 +320,7 @@ asyncActionsProcessor env logger cacheRef pgPool httpManager = forever $ do runTx :: (Monoid a) => Q.TxE QErr a -> IO a runTx q = do res <- runExceptT $ Q.runTx' pgPool q - either mempty return res + onLeft res mempty callHandler :: ActionCache -> ActionLogItem -> m () callHandler actionCache actionLogItem = Tracing.runTraceT "async actions processor" do @@ -427,7 +427,7 @@ callWebhook env manager outputType outputFields reqHeaders confHeaders requestBody = J.encode postPayload requestBodySize = BL.length requestBody url = unResolvedWebhook resolvedWebhook - responseTimeout = HTTP.responseTimeoutMicro $ (unTimeout timeoutSeconds) * 1000000 + responseTimeout = HTTP.responseTimeoutMicro $ unTimeout timeoutSeconds * 1000000 httpResponse <- do initReq <- liftIO $ HTTP.parseRequest (T.unpack url) let req = initReq { HTTP.method = "POST" @@ -475,7 +475,7 @@ callWebhook env manager outputType outputFields reqHeaders confHeaders webhookResponse <- decodeValue responseValue case webhookResponse of AWRArray objs -> do - when (not expectingArray) $ + unless expectingArray $ throwUnexpected "expecting object for action webhook response but got array" mapM_ validateResponseObject objs AWRObject obj -> do @@ -503,12 +503,12 @@ callWebhook env manager outputType outputFields reqHeaders confHeaders validateResponseObject obj = do -- Fields not specified in the output type shouldn't be present in the response let extraFields = filter (not . flip Map.member outputFields) $ Map.keys obj - when (not $ null extraFields) $ throwUnexpected $ + unless (null extraFields) $ throwUnexpected $ "unexpected fields in webhook response: " <> showNames extraFields void $ flip Map.traverseWithKey outputFields $ \fieldName fieldTy -> -- When field is non-nullable, it has to present in the response with no null value - when (not $ G.isNullable fieldTy) $ case Map.lookup fieldName obj of + unless (G.isNullable fieldTy) $ case Map.lookup fieldName obj of Nothing -> throwUnexpected $ "field " <> fieldName <<> " expected in webhook response, but not found" Just v -> when (v == J.Null) $ throwUnexpected $ diff --git a/server/src-lib/Hasura/GraphQL/Execute/LiveQuery/Poll.hs b/server/src-lib/Hasura/GraphQL/Execute/LiveQuery/Poll.hs index 54e13fe3c35c1..924c1824132eb 100644 --- a/server/src-lib/Hasura/GraphQL/Execute/LiveQuery/Poll.hs +++ b/server/src-lib/Hasura/GraphQL/Execute/LiveQuery/Poll.hs @@ -479,5 +479,5 @@ pollQuery pollerId lqOpts pgExecCtx pgQuery cohortMap postPollHook = do -- Postgres response is not present in the cohort map of this batch -- (this shouldn't happen but if it happens it means a logic error and -- we should log it) - in (pure respBS, cohortId, Just $!(respHash, respSize),) <$> + in (pure respBS, cohortId, Just (respHash, respSize),) <$> Map.lookup cohortId cohortSnapshotMap diff --git a/server/src-lib/Hasura/GraphQL/Execute/Prepare.hs b/server/src-lib/Hasura/GraphQL/Execute/Prepare.hs index 6e8741d5d1032..398b692a1586b 100644 --- a/server/src-lib/Hasura/GraphQL/Execute/Prepare.hs +++ b/server/src-lib/Hasura/GraphQL/Execute/Prepare.hs @@ -74,9 +74,7 @@ initPlanningSt = prepareWithPlan :: (MonadState PlanningSt m) => UnpreparedValue -> m S.SQLExp prepareWithPlan = \case UVParameter PGColumnValue{ pcvValue = colVal } varInfoM -> do - argNum <- case fmap getName varInfoM of - Just var -> getVarArgNum var - Nothing -> getNextArgNum + argNum <- maybe getNextArgNum (getVarArgNum . getName) varInfoM addPrepArg argNum (toBinaryValue colVal, pstValue colVal) return $ toPrepParam argNum (pstType colVal) diff --git a/server/src-lib/Hasura/GraphQL/Explain.hs b/server/src-lib/Hasura/GraphQL/Explain.hs index b002a1809abe5..218ae9c35a3f8 100644 --- a/server/src-lib/Hasura/GraphQL/Explain.hs +++ b/server/src-lib/Hasura/GraphQL/Explain.hs @@ -139,7 +139,7 @@ explainGQLQuery pgExecCtx sc (GQLExplain query userVarsRaw maybeIsRelay) = do (plan, _) <- E.buildLiveQueryPlan pgExecCtx userInfo validSubscriptionQueries runInTx $ encJFromJValue <$> E.explainLiveQueryPlan plan where - queryType = bool E.QueryHasura E.QueryRelay $ fromMaybe False maybeIsRelay + queryType = bool E.QueryHasura E.QueryRelay $ Just True == maybeIsRelay sessionVariables = mkSessionVariablesText $ maybe [] Map.toList userVarsRaw runInTx :: LazyTx QErr EncJSON -> m EncJSON diff --git a/server/src-lib/Hasura/GraphQL/RemoteServer.hs b/server/src-lib/Hasura/GraphQL/RemoteServer.hs index 4bcecbb34d978..8e51aa1c49280 100644 --- a/server/src-lib/Hasura/GraphQL/RemoteServer.hs +++ b/server/src-lib/Hasura/GraphQL/RemoteServer.hs @@ -66,7 +66,7 @@ fetchRemoteSchema env manager schemaName schemaInfo@(RemoteSchemaInfo url header , HTTP.responseTimeout = HTTP.responseTimeoutMicro (timeout * 1000000) } res <- liftIO $ try $ HTTP.httpLbs req manager - resp <- either throwHttpErr return res + resp <- onLeft res throwHttpErr let respData = resp ^. Wreq.responseBody statusCode = resp ^. Wreq.responseStatus . Wreq.statusCode @@ -74,7 +74,7 @@ fetchRemoteSchema env manager schemaName schemaInfo@(RemoteSchemaInfo url header -- Parse the JSON into flat GraphQL type AST (FromIntrospection introspectRes) :: (FromIntrospection IntrospectionResult) <- - either (remoteSchemaErr . T.pack) return $ J.eitherDecode respData + onLeft (J.eitherDecode respData) (remoteSchemaErr . T.pack) -- Check that the parsed GraphQL type info is valid by running the schema generation (queryParsers, mutationParsers, subscriptionParsers) <- @@ -194,7 +194,7 @@ instance J.FromJSON (FromIntrospection G.InputValueDefinition) where instance J.FromJSON (FromIntrospection (G.Value Void)) where parseJSON = J.withText "Value Void" $ \t -> let parseValueConst = G.runParser G.value - in fmap FromIntrospection $ either (fail . T.unpack) return $ parseValueConst t + in FromIntrospection <$> onLeft (parseValueConst t) (fail . T.unpack) instance J.FromJSON (FromIntrospection (G.InterfaceTypeDefinition [G.Name])) where parseJSON = J.withObject "InterfaceTypeDefinition" $ \o -> do @@ -338,7 +338,7 @@ execRemoteGQ' env manager userInfo reqHdrs q rsi opType = do } Tracing.tracedHttpRequest req \req' -> do (time, res) <- withElapsedTime $ liftIO $ try $ HTTP.httpLbs req' manager - resp <- either httpThrow return res + resp <- onLeft res httpThrow pure (time, mkSetCookieHeaders resp, resp ^. Wreq.responseBody) where RemoteSchemaInfo url hdrConf fwdClientHdrs timeout = rsi diff --git a/server/src-lib/Hasura/GraphQL/Schema/Action.hs b/server/src-lib/Hasura/GraphQL/Schema/Action.hs index 6ab7704a2a478..b3ce3f5223ecb 100644 --- a/server/src-lib/Hasura/GraphQL/Schema/Action.hs +++ b/server/src-lib/Hasura/GraphQL/Schema/Action.hs @@ -244,7 +244,7 @@ actionInputArguments nonObjectTypeMap arguments = do -> InputFieldsParser n J.Object inputFieldsToObject inputFields = let mkTuple (name, parser) = fmap (G.unName name,) <$> parser - in fmap (Map.fromList . catMaybes) $ traverse mkTuple inputFields + in Map.fromList . catMaybes <$> traverse mkTuple inputFields argumentParser :: G.Name diff --git a/server/src-lib/Hasura/GraphQL/Schema/Introspect.hs b/server/src-lib/Hasura/GraphQL/Schema/Introspect.hs index 2280220986806..4fd38df83404a 100644 --- a/server/src-lib/Hasura/GraphQL/Schema/Introspect.hs +++ b/server/src-lib/Hasura/GraphQL/Schema/Introspect.hs @@ -244,9 +244,9 @@ typeField = \case SomeType tp -> case tp of P.Nullable (P.TNamed (P.Definition _ _ _ (P.TIObject (P.ObjectInfo fields' _interfaces')))) -> - J.Array $ V.fromList $ fmap (snd includeDeprecated'printer) $ sortOn P.dName fields' + J.Array $ V.fromList $ snd includeDeprecated'printer <$> sortOn P.dName fields' P.Nullable (P.TNamed (P.Definition _ _ _ (P.TIInterface (P.InterfaceInfo fields' _objects')))) -> - J.Array $ V.fromList $ fmap (snd includeDeprecated'printer) $ sortOn P.dName fields' + J.Array $ V.fromList $ snd includeDeprecated'printer <$> sortOn P.dName fields' _ -> J.Null interfaces :: FieldParser n (SomeType -> J.Value) interfaces = do @@ -255,7 +255,7 @@ typeField = \case SomeType tp -> case tp of P.Nullable (P.TNamed (P.Definition _ _ _ (P.TIObject (P.ObjectInfo _fields' interfaces')))) -> - J.Array $ V.fromList $ fmap (printer . SomeType . P.Nullable . P.TNamed . fmap P.TIInterface) $ sortOn P.dName interfaces' + J.Array $ V.fromList $ printer . SomeType . P.Nullable . P.TNamed . fmap P.TIInterface <$> sortOn P.dName interfaces' _ -> J.Null possibleTypes :: FieldParser n (SomeType -> J.Value) possibleTypes = do @@ -264,9 +264,9 @@ typeField = \case SomeType tp -> case tp of P.Nullable (P.TNamed (P.Definition _ _ _ (P.TIInterface (P.InterfaceInfo _fields' objects')))) -> - J.Array $ V.fromList $ fmap (printer . SomeType . P.Nullable . P.TNamed . fmap P.TIObject) $ sortOn P.dName objects' + J.Array $ V.fromList $ printer . SomeType . P.Nullable . P.TNamed . fmap P.TIObject <$> sortOn P.dName objects' P.Nullable (P.TNamed (P.Definition _ _ _ (P.TIUnion (P.UnionInfo objects')))) -> - J.Array $ V.fromList $ fmap (printer . SomeType . P.Nullable . P.TNamed . fmap P.TIObject) $ sortOn P.dName objects' + J.Array $ V.fromList $ printer . SomeType . P.Nullable . P.TNamed . fmap P.TIObject <$> sortOn P.dName objects' _ -> J.Null enumValues :: FieldParser n (SomeType -> J.Value) enumValues = do diff --git a/server/src-lib/Hasura/GraphQL/Schema/Remote.hs b/server/src-lib/Hasura/GraphQL/Schema/Remote.hs index c2f0d873e36cb..90f68873d1e84 100644 --- a/server/src-lib/Hasura/GraphQL/Schema/Remote.hs +++ b/server/src-lib/Hasura/GraphQL/Schema/Remote.hs @@ -95,11 +95,10 @@ remoteSchemaObject schemaDoc defn@(G.ObjectTypeDefinition description name inter -- TODO: also check sub-interfaces, when these are supported in a future graphql spec traverse_ validateImplementsFields interfaceDefs pure $ P.selectionSetObject name description subFieldParsers implements <&> - toList . (OMap.mapWithKey $ \alias -> \case + toList . OMap.mapWithKey (\alias -> \case P.SelectField fld -> fld P.SelectTypename _ -> - G.Field (Just alias) $$(G.litName "__typename") mempty mempty mempty - ) + G.Field (Just alias) $$(G.litName "__typename") mempty mempty mempty) where getInterface :: G.Name -> m (G.InterfaceTypeDefinition [G.Name]) getInterface interfaceName = @@ -302,7 +301,7 @@ remoteSchemaInterface schemaDoc defn@(G.InterfaceTypeDefinition description name G.InlineFragment (Just objName) mempty selSet -- #5 of Note [Querying remote schema interface fields] - in (fmap G.SelectionField commonInterfaceFields) <> nonCommonInterfaceFields + in fmap G.SelectionField commonInterfaceFields <> nonCommonInterfaceFields -- | 'remoteSchemaUnion' returns a output parser for a given 'UnionTypeDefinition'. remoteSchemaUnion @@ -515,7 +514,7 @@ remoteField sdoc fieldName description argsDefn typeDefn = do -- 'rawSelection' is used here to get the alias and args data -- specified to be able to construct the `Field NoFragments G.Name` P.rawSelection fieldName description argsParser outputParser - <&> (\(alias, args, _) -> (G.Field alias fieldName (fmap getName <$> args) mempty [])) + <&> (\(alias, args, _) -> G.Field alias fieldName (fmap getName <$> args) mempty []) mkFieldParserWithSelectionSet :: InputFieldsParser n () @@ -526,7 +525,7 @@ remoteField sdoc fieldName description argsDefn typeDefn = do -- specified to be able to construct the `Field NoFragments G.Name` P.rawSubselection fieldName description argsParser outputParser <&> (\(alias, args, _, selSet) -> - (G.Field alias fieldName (fmap getName <$> args) mempty selSet)) + G.Field alias fieldName (fmap getName <$> args) mempty selSet) remoteFieldScalarParser :: MonadParse n diff --git a/server/src-lib/Hasura/GraphQL/Schema/Select.hs b/server/src-lib/Hasura/GraphQL/Schema/Select.hs index 183d3e822a7d2..462330cb6de08 100644 --- a/server/src-lib/Hasura/GraphQL/Schema/Select.hs +++ b/server/src-lib/Hasura/GraphQL/Schema/Select.hs @@ -831,7 +831,7 @@ tableAggregationFields table selectPermissions = do columns <- maybe (pure Nothing) (P.fieldOptional columnsName Nothing . P.list) columnsEnum pure $ case columns of Nothing -> SQL.CTStar - Just cols -> if fromMaybe False distinct + Just cols -> if Just True == distinct then SQL.CTDistinct cols else SQL.CTSimple cols pure $ RQL.AFCount <$> P.selection $$(G.litName "count") Nothing args P.int diff --git a/server/src-lib/Hasura/GraphQL/Transport/HTTP.hs b/server/src-lib/Hasura/GraphQL/Transport/HTTP.hs index c16fff1515395..fcf2e52dd95f8 100644 --- a/server/src-lib/Hasura/GraphQL/Transport/HTTP.hs +++ b/server/src-lib/Hasura/GraphQL/Transport/HTTP.hs @@ -204,7 +204,7 @@ runGQ env logger reqId userInfo ipAddress reqHeaders queryType reqUnparsed = do ) buildResult _telemType (Left (Right err)) _ = throwError err buildResult telemType (Right results) cacheHeaders = do - let responseData = encodeGQResp $ pure $ encJToLBS $ encJFromInsOrdHashMap $ fmap rfResponse $ OMap.mapKeys G.unName results + let responseData = encodeGQResp $ pure $ encJToLBS $ encJFromInsOrdHashMap $ rfResponse <$> OMap.mapKeys G.unName results pure ( telemType , sum (fmap rfTimeIO results) diff --git a/server/src-lib/Hasura/GraphQL/Transport/WebSocket.hs b/server/src-lib/Hasura/GraphQL/Transport/WebSocket.hs index 1056e133c1cdb..850f9221e8663 100644 --- a/server/src-lib/Hasura/GraphQL/Transport/WebSocket.hs +++ b/server/src-lib/Hasura/GraphQL/Transport/WebSocket.hs @@ -251,7 +251,7 @@ onConn (L.Logger logger) corsPolicy wsId requestHead ipAddress = do case connState of CSNotInitialised _ _ -> STM.retry CSInitError _ -> STM.retry - CSInitialised clientState -> maybe STM.retry return $ wscsTokenExpTime clientState + CSInitialised clientState -> onNothing (wscsTokenExpTime clientState) STM.retry currTime <- TC.getCurrentTime sleep $ convertDuration $ TC.diffUTCTime expTime currTime @@ -348,11 +348,11 @@ onStart env serverEnv wsConn (StartMsg opId q) = catchAndIgnore $ do (sc, scVer) <- liftIO getSchemaCache reqParsedE <- lift $ E.checkGQLExecution userInfo (reqHdrs, ipAddress) enableAL sc q - reqParsed <- either (withComplete . preExecErr requestId) return reqParsedE + reqParsed <- onLeft reqParsedE (withComplete . preExecErr requestId) execPlanE <- runExceptT $ E.getResolvedExecPlan env logger pgExecCtx {- planCache -} userInfo sqlGenCtx sc scVer queryType httpMgr reqHdrs (q, reqParsed) - (telemCacheHit, execPlan) <- either (withComplete . preExecErr requestId) return execPlanE + (telemCacheHit, execPlan) <- onLeft execPlanE (withComplete . preExecErr requestId) let execCtx = E.ExecutionCtx logger sqlGenCtx pgExecCtx {- planCache -} sc scVer httpMgr enableAL case execPlan of @@ -368,7 +368,7 @@ onStart env serverEnv wsConn (StartMsg opId q) = catchAndIgnore $ do conclusion <- runExceptT $ forWithKey queryPlan $ \fieldName -> \case E.ExecStepDB (tx, genSql) -> doQErr $ Tracing.trace "Postgres Query" $ do logQueryLog logger q ((fieldName,) <$> genSql) requestId - (telemTimeIO_DT, (resp)) <- Tracing.interpTraceT id $ withElapsedTime $ + (telemTimeIO_DT, resp) <- Tracing.interpTraceT id $ withElapsedTime $ hoist (runQueryTx pgExecCtx) tx return $ ResultsFragment telemTimeIO_DT Telem.Local resp [] E.ExecStepRemote (rsi, opDef, varValsM) -> do @@ -379,7 +379,7 @@ onStart env serverEnv wsConn (StartMsg opId q) = catchAndIgnore $ do case conclusion of Left _ -> pure () Right results -> - Tracing.interpTraceT id $ cacheStore cacheKey $ encJFromInsOrdHashMap $ fmap rfResponse $ OMap.mapKeys G.unName results + Tracing.interpTraceT id $ cacheStore cacheKey $ encJFromInsOrdHashMap $ rfResponse <$> OMap.mapKeys G.unName results sendCompleted (Just requestId) E.MutationExecutionPlan mutationPlan -> do @@ -723,7 +723,7 @@ createWSServerApp env authMode serverEnv = \ !ipAddress !pendingConn -> -- Mask async exceptions during event processing to help maintain integrity of mutable vars: (\rid rh ip -> mask_ $ onConn (_wseLogger serverEnv) (_wseCorsPolicy serverEnv) rid rh ip) (\conn bs -> mask_ $ onMessage env authMode serverEnv conn bs) - (\conn -> mask_ $ onClose (_wseLogger serverEnv) (_wseLiveQMap serverEnv) conn) + (mask_ . onClose (_wseLogger serverEnv) (_wseLiveQMap serverEnv)) stopWSServerApp :: WSServerEnv -> IO () stopWSServerApp wsEnv = WS.shutdown (_wseServer wsEnv) diff --git a/server/src-lib/Hasura/GraphQL/Transport/WebSocket/Server.hs b/server/src-lib/Hasura/GraphQL/Transport/WebSocket/Server.hs index f5e90b747bc63..37fa66d133e01 100644 --- a/server/src-lib/Hasura/GraphQL/Transport/WebSocket/Server.hs +++ b/server/src-lib/Hasura/GraphQL/Transport/WebSocket/Server.hs @@ -174,7 +174,7 @@ closeConnWithCode wsConn code bs = do -- writes to a queue instead of the raw connection -- so that sendMsg doesn't block sendMsg :: WSConn a -> WSQueueResponse -> IO () -sendMsg wsConn = \ !resp -> do +sendMsg wsConn !resp = do #ifndef PROFILING $assertNFHere resp -- so we don't write thunks to mutable vars #endif diff --git a/server/src-lib/Hasura/GraphQL/Utils.hs b/server/src-lib/Hasura/GraphQL/Utils.hs index ea478cbf595ee..e3e750565e3ca 100644 --- a/server/src-lib/Hasura/GraphQL/Utils.hs +++ b/server/src-lib/Hasura/GraphQL/Utils.hs @@ -26,7 +26,7 @@ getBaseTyWithNestedLevelsCount ty = go ty 0 go gType ctr = case gType of G.TypeNamed _ n -> (n, ctr) - G.TypeList _ gType' -> flip go (ctr + 1) gType' + G.TypeList _ gType' -> go gType' (ctr + 1) groupListWith :: (Eq k, Hashable k, Foldable t, Functor t) diff --git a/server/src-lib/Hasura/Incremental/Internal/Rule.hs b/server/src-lib/Hasura/Incremental/Internal/Rule.hs index 04c430db95fc4..c3885ef2acb8a 100644 --- a/server/src-lib/Hasura/Incremental/Internal/Rule.hs +++ b/server/src-lib/Hasura/Incremental/Internal/Rule.hs @@ -277,7 +277,7 @@ class (Arrow arr) => ArrowDistribute arr where -> arr (e, (HashMap k a, s)) (HashMap k b) instance (Monoid w, ArrowDistribute arr) => ArrowDistribute (WriterA w arr) where - keyed (WriterA f) = WriterA (arr (swap . sequence . fmap swap) . keyed f) + keyed (WriterA f) = WriterA (arr (swap . mapM swap) . keyed f) {-# INLINE keyed #-} -- | Unlike 'traverseA', using 'keyed' preserves incrementalization: if the input rule is diff --git a/server/src-lib/Hasura/Logging.hs b/server/src-lib/Hasura/Logging.hs index bb45583c137d7..ce366dc8b925e 100644 --- a/server/src-lib/Hasura/Logging.hs +++ b/server/src-lib/Hasura/Logging.hs @@ -237,7 +237,7 @@ defaultLoggerSettings isCached = getFormattedTime :: Maybe Time.TimeZone -> IO FormattedTime getFormattedTime tzM = do - tz <- maybe Time.getCurrentTimeZone return tzM + tz <- onNothing tzM Time.getCurrentTimeZone t <- Time.getCurrentTime let zt = Time.utcToZonedTime tz t return $ FormattedTime $ T.pack $ formatTime zt diff --git a/server/src-lib/Hasura/RQL/DDL/ComputedField.hs b/server/src-lib/Hasura/RQL/DDL/ComputedField.hs index c1009a561906d..cf5288bec1a1b 100644 --- a/server/src-lib/Hasura/RQL/DDL/ComputedField.hs +++ b/server/src-lib/Hasura/RQL/DDL/ComputedField.hs @@ -129,7 +129,7 @@ addComputedFieldP2Setup -> Maybe Text -> m (ComputedFieldInfo 'Postgres) addComputedFieldP2Setup trackedTables table computedField definition rawFunctionInfo comment = - either (throw400 NotSupported . showErrors) pure =<< MV.runValidateT (mkComputedFieldInfo) + either (throw400 NotSupported . showErrors) pure =<< MV.runValidateT mkComputedFieldInfo where inputArgNames = rfiInputArgNames rawFunctionInfo ComputedFieldDefinition function maybeTableArg maybeSessionArg = definition @@ -168,7 +168,7 @@ addComputedFieldP2Setup trackedTables table computedField definition rawFunction (rfiInputArgTypes rawFunctionInfo) inputArgNames tableArgument <- case maybeTableArg of Just argName -> - case findWithIndex (maybe False (argName ==) . faName) inputArgs of + case findWithIndex ((Just argName ==) . faName) inputArgs of Just (tableArg, index) -> do let functionTableArg = FTANamed argName index validateTableArgumentType functionTableArg $ faType tableArg @@ -184,7 +184,7 @@ addComputedFieldP2Setup trackedTables table computedField definition rawFunction maybePGSessionArg <- sequence $ do argName <- maybeSessionArg - return $ case findWithIndex (maybe False (argName ==) . faName) inputArgs of + return $ case findWithIndex ((Just argName ==) . faName) inputArgs of Just (sessionArg, index) -> do let functionSessionArg = FunctionSessionArgument argName index validateSessionArgumentType functionSessionArg $ faType sessionArg @@ -217,7 +217,7 @@ addComputedFieldP2Setup trackedTables table computedField definition rawFunction -> QualifiedPGType -> m () validateSessionArgumentType sessionArg qpt = do - when (not . isJSONType . _qptName $ qpt) $ + unless (isJSONType $ _qptName qpt) $ MV.dispute $ pure $ CFVEInvalidSessionArgument $ ISANotJSON sessionArg showErrors :: [ComputedFieldValidateError] -> Text diff --git a/server/src-lib/Hasura/RQL/DDL/Deps.hs b/server/src-lib/Hasura/RQL/DDL/Deps.hs index 6865dcda2ac0a..89634e957bbf3 100644 --- a/server/src-lib/Hasura/RQL/DDL/Deps.hs +++ b/server/src-lib/Hasura/RQL/DDL/Deps.hs @@ -103,5 +103,5 @@ getIndirectDeps initDeps tx = do let (unparsedLines, parsedObjIds) = partitionEithers pgDeps indirectDeps = HS.fromList $ parsedObjIds <> concatMap (getDependentObjs sc) parsedObjIds - newDeps = indirectDeps `HS.difference` (HS.fromList initDeps) + newDeps = indirectDeps `HS.difference` HS.fromList initDeps return (HS.toList newDeps, unparsedLines) diff --git a/server/src-lib/Hasura/RQL/DDL/Metadata.hs b/server/src-lib/Hasura/RQL/DDL/Metadata.hs index 8fc58497bf160..3bce83cf49eed 100644 --- a/server/src-lib/Hasura/RQL/DDL/Metadata.hs +++ b/server/src-lib/Hasura/RQL/DDL/Metadata.hs @@ -489,7 +489,7 @@ runExportMetadata :: (QErrM m, MonadTx m) => ExportMetadata -> m EncJSON runExportMetadata _ = - (AO.toEncJSON . replaceMetadataToOrdJSON) <$> liftTx fetchMetadata + AO.toEncJSON . replaceMetadataToOrdJSON <$> liftTx fetchMetadata runReloadMetadata :: (QErrM m, CacheRWM m) => ReloadMetadata -> m EncJSON runReloadMetadata (ReloadMetadata reloadRemoteSchemas) = do diff --git a/server/src-lib/Hasura/RQL/DDL/Metadata/Types.hs b/server/src-lib/Hasura/RQL/DDL/Metadata/Types.hs index bd37ff592ee14..af57ccc31161d 100644 --- a/server/src-lib/Hasura/RQL/DDL/Metadata/Types.hs +++ b/server/src-lib/Hasura/RQL/DDL/Metadata/Types.hs @@ -465,7 +465,7 @@ replaceMetadataToOrdJSON ( ReplaceMetadata | otherwise = Just retryConfig maybeHeader headerConfig - | headerConfig == [] = Nothing + | null headerConfig = Nothing | otherwise = Just headerConfig customTypesToOrdJSON :: CustomTypes -> AO.Value @@ -504,7 +504,7 @@ replaceMetadataToOrdJSON ( ReplaceMetadata AO.object $ [ ("name", AO.toOrdered fieldName) , ("type", AO.toOrdered ty) ] - <> catMaybes [ (("arguments", ) . AO.toOrdered) <$> argsValM + <> catMaybes [ ("arguments", ) . AO.toOrdered <$> argsValM , maybeDescriptionToMaybeOrdPair fieldDescM ] @@ -552,7 +552,7 @@ replaceMetadataToOrdJSON ( ReplaceMetadata <> catMaybes [ listToMaybeOrdPair "headers" AO.toOrdered headers , listToMaybeOrdPair "arguments" argDefinitionToOrdJSON args] <> typeAndKind - <> (bool [("timeout",AO.toOrdered timeout)] mempty $ timeout == defaultActionTimeoutSecs) + <> bool [("timeout",AO.toOrdered timeout)] mempty (timeout == defaultActionTimeoutSecs) permToOrdJSON :: ActionPermissionMetadata -> AO.Value permToOrdJSON (ActionPermissionMetadata role permComment) = diff --git a/server/src-lib/Hasura/RQL/DDL/Permission.hs b/server/src-lib/Hasura/RQL/DDL/Permission.hs index bc7b3cee5ea4e..955946eae48c8 100644 --- a/server/src-lib/Hasura/RQL/DDL/Permission.hs +++ b/server/src-lib/Hasura/RQL/DDL/Permission.hs @@ -142,9 +142,9 @@ buildInsPermInfo tn fieldInfoMap (PermDef _rn (InsPerm checkCond set mCols mBack insColsWithoutPresets = insCols \\ HM.keys setColsSQL return (InsPermInfo (HS.fromList insColsWithoutPresets) be setColsSQL backendOnly reqHdrs, deps) where - backendOnly = fromMaybe False mBackendOnly + backendOnly = Just True == mBackendOnly allCols = map pgiColumn $ getCols fieldInfoMap - insCols = fromMaybe allCols $ convColSpec fieldInfoMap <$> mCols + insCols = maybe allCols (convColSpec fieldInfoMap) mCols -- TODO this is a dirty hack, hardcoding permissions to postgres. When -- implementing support for other backends, the type family 'PermInfo' probably @@ -389,7 +389,7 @@ fetchPermDef -> PermType -> Q.TxE QErr (Value, Maybe Text) fetchPermDef (QualifiedObject sn tn) rn pt = - (first Q.getAltJ . Q.getRow) <$> Q.withQE defaultTxErrorHandler + first Q.getAltJ . Q.getRow <$> Q.withQE defaultTxErrorHandler [Q.sql| SELECT perm_def::json, comment FROM hdb_catalog.hdb_permission diff --git a/server/src-lib/Hasura/RQL/DDL/QueryCollection.hs b/server/src-lib/Hasura/RQL/DDL/QueryCollection.hs index b3d5321335ec0..12d013023fddb 100644 --- a/server/src-lib/Hasura/RQL/DDL/QueryCollection.hs +++ b/server/src-lib/Hasura/RQL/DDL/QueryCollection.hs @@ -94,7 +94,7 @@ runDropQueryFromCollection runDropQueryFromCollection (DropQueryFromCollection collName queryName) = do CollectionDef qList <- getCollectionDef collName let queryExists = flip any qList $ \q -> _lqName q == queryName - when (not queryExists) $ throw400 NotFound $ "query with name " + unless queryExists $ throw400 NotFound $ "query with name " <> queryName <<> " not found in collection " <>> collName let collDef = CollectionDef $ flip filter qList $ \q -> _lqName q /= queryName diff --git a/server/src-lib/Hasura/RQL/DDL/RemoteRelationship.hs b/server/src-lib/Hasura/RQL/DDL/RemoteRelationship.hs index e68f0aaffb3e0..e0ac268e096f0 100644 --- a/server/src-lib/Hasura/RQL/DDL/RemoteRelationship.hs +++ b/server/src-lib/Hasura/RQL/DDL/RemoteRelationship.hs @@ -50,11 +50,8 @@ resolveRemoteRelationship remoteRelationship let tableDep = SchemaDependency (SOTable table) DRTable columnsDep = map - (\column -> - SchemaDependency - (SOTableObj table $ TOCol column) - DRRemoteRelationship ) $ - map pgiColumn $ HS.toList $ _rfiHasuraFields remoteField + (flip SchemaDependency DRRemoteRelationship . SOTableObj table . TOCol . pgiColumn) + $ HS.toList $ _rfiHasuraFields remoteField remoteSchemaDep = SchemaDependency (SORemoteSchema $ rtrRemoteSchema remoteRelationship) DRRemoteSchema in (tableDep : remoteSchemaDep : columnsDep) @@ -120,7 +117,7 @@ delRemoteRelFromCatalog (QualifiedObject sn tn) (RemoteRelationshipName relName) getRemoteRelDefFromCatalog :: RemoteRelationshipName -> QualifiedTable -> Q.TxE QErr RemoteRelationshipDef getRemoteRelDefFromCatalog relName (QualifiedObject schemaName tableName) = do - (Q.AltJ defn) <- (runIdentity . Q.getRow) <$> Q.withQE defaultTxErrorHandler + (Q.AltJ defn) <- runIdentity . Q.getRow <$> Q.withQE defaultTxErrorHandler [Q.sql| SELECT definition::json FROM hdb_catalog.hdb_remote_relationship diff --git a/server/src-lib/Hasura/RQL/DDL/RemoteRelationship/Validate.hs b/server/src-lib/Hasura/RQL/DDL/RemoteRelationship/Validate.hs index a5a9c8d9acd08..6764ec01c724c 100644 --- a/server/src-lib/Hasura/RQL/DDL/RemoteRelationship/Validate.hs +++ b/server/src-lib/Hasura/RQL/DDL/RemoteRelationship/Validate.hs @@ -91,10 +91,10 @@ validateRemoteRelationship remoteRelationship remoteSchemaMap pgColumns = do hasuraFields <- forM (toList $ rtrHasuraFields remoteRelationship) $ \fieldName -> onNothing (find ((==) fieldName . fromPGCol . pgiColumn) pgColumns) $ throwError $ TableFieldNonexistent table fieldName - pgColumnsVariables <- (mapM (\(k,v) -> do + pgColumnsVariables <- mapM (\(k,v) -> do variableName <- pgColumnToVariable k pure $ (variableName,v) - )) $ (HM.toList $ mapFromL (pgiColumn) pgColumns) + ) $ HM.toList (mapFromL pgiColumn pgColumns) let pgColumnsVariablesMap = HM.fromList pgColumnsVariables (RemoteSchemaCtx rsName introspectionResult rsi _ _) <- onNothing (HM.lookup remoteSchemaName remoteSchemaMap) $ @@ -129,11 +129,11 @@ validateRemoteRelationship remoteRelationship remoteSchemaMap pgColumns = do buildRelationshipTypeInfo pgColumnsVariablesMap schemaDoc (objTyInfo,(_,typeMap)) fieldCall = do objFldDefinition <- lookupField (fcName fieldCall) objTyInfo let providedArguments = getRemoteArguments $ fcArguments fieldCall - (validateRemoteArguments + validateRemoteArguments (mapFromL G._ivdName (G._fldArgumentsDefinition objFldDefinition)) providedArguments pgColumnsVariablesMap - schemaDoc) + schemaDoc let eitherParamAndTypeMap = runStateT (stripInMap @@ -145,7 +145,7 @@ validateRemoteRelationship remoteRelationship remoteSchemaMap pgColumns = do (newParamMap, newTypeMap) <- onLeft eitherParamAndTypeMap $ throwError innerObjTyInfo <- onNothing (getObjTyInfoFromField schemaDoc objFldDefinition) $ bool (throwError $ - (InvalidType (G._fldType objFldDefinition) "only objects or scalar types expected")) + InvalidType (G._fldType objFldDefinition) "only objects or scalar types expected") (pure objTyInfo) (isScalarType schemaDoc objFldDefinition) pure @@ -220,10 +220,7 @@ stripList remoteRelationshipName types originalOuterGType value = case originalOuterGType of G.TypeList nullability innerGType -> do maybeNewInnerGType <- stripValue remoteRelationshipName types innerGType value - pure - (fmap - (\newGType -> G.TypeList nullability newGType) - maybeNewInnerGType) + pure (G.TypeList nullability <$> maybeNewInnerGType) _ -> lift (Left (InvalidGTypeForStripping originalOuterGType)) -- -- | Produce a new type for the given InpValInfo, modified by @@ -339,17 +336,17 @@ validateType permittedVariables value expectedGType schemaDocument = namedType <- columnInfoToNamedType fieldInfo isTypeCoercible (mkGraphQLType namedType) expectedGType G.VInt {} -> do - intScalarGType <- (mkGraphQLType <$> mkScalarTy PGInteger) + intScalarGType <- mkGraphQLType <$> mkScalarTy PGInteger isTypeCoercible intScalarGType expectedGType G.VFloat {} -> do - floatScalarGType <- (mkGraphQLType <$> mkScalarTy PGFloat) + floatScalarGType <- mkGraphQLType <$> mkScalarTy PGFloat isTypeCoercible floatScalarGType expectedGType G.VBoolean {} -> do - boolScalarGType <- (mkGraphQLType <$> mkScalarTy PGBoolean) + boolScalarGType <- mkGraphQLType <$> mkScalarTy PGBoolean isTypeCoercible boolScalarGType expectedGType G.VNull -> throwError NullNotAllowedHere G.VString {} -> do - stringScalarGType <- (mkGraphQLType <$> mkScalarTy PGText) + stringScalarGType <- mkGraphQLType <$> mkScalarTy PGText isTypeCoercible stringScalarGType expectedGType G.VEnum _ -> throwError UnsupportedEnum G.VList values -> do @@ -358,25 +355,23 @@ validateType permittedVariables value expectedGType schemaDocument = [_] -> pure () _ -> throwError UnsupportedMultipleElementLists assertListType expectedGType - (flip - traverse_ - values - (\val -> - validateType permittedVariables val (unwrapGraphQLType expectedGType) schemaDocument)) + for_ + values + (\val -> + validateType permittedVariables val (unwrapGraphQLType expectedGType) schemaDocument) G.VObject values -> - flip - traverse_ + for_ (HM.toList values) (\(name,val) -> let expectedNamedType = G.getBaseType expectedGType in case lookupType schemaDocument expectedNamedType of - Nothing -> throwError $ (TypeNotFound expectedNamedType) + Nothing -> throwError $ TypeNotFound expectedNamedType Just typeInfo -> case typeInfo of G.TypeDefinitionInputObject inpObjTypeInfo -> let objectTypeDefnsMap = - mapFromL G._ivdName $ (G._iotdValueDefinitions inpObjTypeInfo) + mapFromL G._ivdName $ G._iotdValueDefinitions inpObjTypeInfo in case HM.lookup name objectTypeDefnsMap of Nothing -> throwError $ NoSuchArgumentForRemote name @@ -418,8 +413,8 @@ isTypeCoercible actualType expectedType = assertListType :: (MonadError ValidationError m) => G.GType -> m () assertListType actualType = - (when (not $ G.isListType actualType) - (throwError $ InvalidType actualType "is not a list type")) + unless (G.isListType actualType) + (throwError $ InvalidType actualType "is not a list type") -- | Convert a field info to a named type, if possible. columnInfoToNamedType diff --git a/server/src-lib/Hasura/RQL/DDL/ScheduledTrigger.hs b/server/src-lib/Hasura/RQL/DDL/ScheduledTrigger.hs index 748929aa2402e..d001aa2bfa3dd 100644 --- a/server/src-lib/Hasura/RQL/DDL/ScheduledTrigger.hs +++ b/server/src-lib/Hasura/RQL/DDL/ScheduledTrigger.hs @@ -25,14 +25,14 @@ import qualified Database.PG.Query as Q -- be created runCreateCronTrigger :: (CacheRWM m, MonadTx m) => CreateCronTrigger -> m EncJSON runCreateCronTrigger CreateCronTrigger {..} = do - let q = (CronTriggerMetadata cctName + let q = CronTriggerMetadata cctName cctWebhook cctCronSchedule cctPayload cctRetryConf cctHeaders cctIncludeInMetadata - cctComment) + cctComment case cctReplace of True -> updateCronTrigger q False -> do @@ -41,7 +41,7 @@ runCreateCronTrigger CreateCronTrigger {..} = do Nothing -> pure () Just _ -> throw400 AlreadyExists $ "cron trigger with name: " - <> (triggerNameToTxt $ ctName q) + <> triggerNameToTxt (ctName q) <> " already exists" addCronTriggerToCatalog q @@ -152,4 +152,4 @@ checkExists name = do cronTriggersMap <- scCronTriggers <$> askSchemaCache void $ onNothing (Map.lookup name cronTriggersMap) $ throw400 NotExists $ - "cron trigger with name: " <> (triggerNameToTxt name) <> " does not exist" + "cron trigger with name: " <> triggerNameToTxt name <> " does not exist" diff --git a/server/src-lib/Hasura/RQL/DDL/Schema/Cache.hs b/server/src-lib/Hasura/RQL/DDL/Schema/Cache.hs index e44eb2b23a710..795e00b0ea2e2 100644 --- a/server/src-lib/Hasura/RQL/DDL/Schema/Cache.hs +++ b/server/src-lib/Hasura/RQL/DDL/Schema/Cache.hs @@ -132,21 +132,21 @@ buildSchemaCacheRule env = proc (catalogMetadata, invalidationKeys) -> do -- Step 3: Build the GraphQL schema. (gqlContext, gqlSchemaInconsistentObjects) <- runWriterA buildGQLContext -< ( QueryHasura - , (_boTables resolvedOutputs) - , (_boFunctions resolvedOutputs) - , (_boRemoteSchemas resolvedOutputs) - , (_boActions resolvedOutputs) - , (_actNonObjects $ _boCustomTypes resolvedOutputs) + , _boTables resolvedOutputs + , _boFunctions resolvedOutputs + , _boRemoteSchemas resolvedOutputs + , _boActions resolvedOutputs + , _actNonObjects $ _boCustomTypes resolvedOutputs ) -- Step 4: Build the relay GraphQL schema (relayContext, relaySchemaInconsistentObjects) <- runWriterA buildGQLContext -< ( QueryRelay - , (_boTables resolvedOutputs) - , (_boFunctions resolvedOutputs) - , (_boRemoteSchemas resolvedOutputs) - , (_boActions resolvedOutputs) - , (_actNonObjects $ _boCustomTypes resolvedOutputs) + , _boTables resolvedOutputs + , _boFunctions resolvedOutputs + , _boRemoteSchemas resolvedOutputs + , _boActions resolvedOutputs + , _actNonObjects $ _boCustomTypes resolvedOutputs ) returnA -< SchemaCache @@ -446,10 +446,9 @@ withMetadataCheck cascade action = do mapM_ purgeDependentObject indirectDeps -- Purge all dropped functions - let purgedFuncs = flip mapMaybe indirectDeps $ \dep -> - case dep of - SOFunction qf -> Just qf - _ -> Nothing + let purgedFuncs = flip mapMaybe indirectDeps $ \case + SOFunction qf -> Just qf + _ -> Nothing forM_ (droppedFuncs \\ purgedFuncs) $ \qf -> do liftTx $ delFunctionFromCatalog qf diff --git a/server/src-lib/Hasura/RQL/DDL/Schema/Cache/Permission.hs b/server/src-lib/Hasura/RQL/DDL/Schema/Cache/Permission.hs index f771f346830e3..77fef5700ed22 100644 --- a/server/src-lib/Hasura/RQL/DDL/Schema/Cache/Permission.hs +++ b/server/src-lib/Hasura/RQL/DDL/Schema/Cache/Permission.hs @@ -32,7 +32,7 @@ buildTablePermissions , QualifiedTable , FieldInfoMap (FieldInfo 'Postgres) , HashSet CatalogPermission - ) `arr` (RolePermInfoMap 'Postgres) + ) `arr` RolePermInfoMap 'Postgres buildTablePermissions = Inc.cache proc (tableCache, tableName, tableFields, tablePermissions) -> (| Inc.keyed (\_ rolePermissions -> do let (insertPerms, selectPerms, updatePerms, deletePerms) = diff --git a/server/src-lib/Hasura/RQL/DDL/Schema/Function.hs b/server/src-lib/Hasura/RQL/DDL/Schema/Function.hs index c1c05952d7792..d5bcc2f8dac45 100644 --- a/server/src-lib/Hasura/RQL/DDL/Schema/Function.hs +++ b/server/src-lib/Hasura/RQL/DDL/Schema/Function.hs @@ -70,7 +70,7 @@ validateFuncArgs args = <> " are not in compliance with GraphQL spec" where funcArgsText = mapMaybe (fmap getFuncArgNameTxt . faName) args - invalidArgs = filter (not . isJust . G.mkName) funcArgsText + invalidArgs = filter (isNothing . G.mkName) funcArgsText data FunctionIntegrityError = FunctionNameNotGQLCompliant @@ -125,18 +125,18 @@ mkFunctionInfo qf systemDefined config rawFuncInfo = validateFunctionArgNames = do let argNames = mapMaybe faName functionArgs - invalidArgs = filter (not . isJust . G.mkName . getFuncArgNameTxt) argNames - when (not $ null invalidArgs) $ + invalidArgs = filter (isNothing . G.mkName . getFuncArgNameTxt) argNames + unless (null invalidArgs) $ throwValidateError $ FunctionInvalidArgumentNames invalidArgs makeInputArguments = case _fcSessionArgument config of Nothing -> pure $ Seq.fromList $ map IAUserProvided functionArgs Just sessionArgName -> do - when (not $ any (\arg -> (Just sessionArgName) == faName arg) functionArgs) $ + unless (any (\arg -> Just sessionArgName == faName arg) functionArgs) $ throwValidateError $ FunctionInvalidSessionArgument sessionArgName fmap Seq.fromList $ forM functionArgs $ \arg -> - if (Just sessionArgName) == faName arg then do + if Just sessionArgName == faName arg then do let argTy = _qptName $ faType arg if argTy == PGJSON then pure $ IASessionVariables sessionArgName else MV.refute $ pure $ FunctionSessionArgumentNotJSON sessionArgName diff --git a/server/src-lib/Hasura/RQL/DDL/Schema/Rename.hs b/server/src-lib/Hasura/RQL/DDL/Schema/Rename.hs index b633dd737d3c2..ed674f3273365 100644 --- a/server/src-lib/Hasura/RQL/DDL/Schema/Rename.hs +++ b/server/src-lib/Hasura/RQL/DDL/Schema/Rename.hs @@ -273,7 +273,7 @@ updateDelPermFlds refQT rename rn (DelPerm fltr) = do liftTx $ updatePermDefInCatalog PTDelete refQT rn $ DelPerm updFltr updatePreset - :: QualifiedTable -> RenameField -> (ColumnValues Value) -> (ColumnValues Value) + :: QualifiedTable -> RenameField -> ColumnValues Value -> ColumnValues Value updatePreset qt rf obj = case rf of RFCol (RenameItem opQT oCol nCol) -> @@ -319,7 +319,7 @@ updateFieldInBoolExp qt rf be = BoolExp <$> BoolOr exps -> BoolOr <$> procExps exps BoolNot e -> BoolNot <$> updateBoolExp' e BoolExists (GExists refqt wh) -> - (BoolExists . GExists refqt . unBoolExp) + BoolExists . GExists refqt . unBoolExp <$> updateFieldInBoolExp refqt rf (BoolExp wh) BoolFld fld -> BoolFld <$> updateColExp qt rf fld where diff --git a/server/src-lib/Hasura/RQL/DML/RemoteJoin.hs b/server/src-lib/Hasura/RQL/DML/RemoteJoin.hs index 9de20ee69055c..57b56fd4fdb2b 100644 --- a/server/src-lib/Hasura/RQL/DML/RemoteJoin.hs +++ b/server/src-lib/Hasura/RQL/DML/RemoteJoin.hs @@ -421,7 +421,7 @@ fetchRemoteJoinFields env manager reqHdrs userInfo remoteJoins = do let batchList = toList batch gqlReq = fieldsToRequest G.OperationTypeQuery (map _rjfField batchList) - gqlReqUnparsed = (GQLQueryText . G.renderExecutableDoc . G.ExecutableDocument . unGQLExecDoc) <$> gqlReq + gqlReqUnparsed = GQLQueryText . G.renderExecutableDoc . G.ExecutableDocument . unGQLExecDoc <$> gqlReq -- NOTE: discard remote headers (for now): (_, _, respBody) <- execRemoteGQ' env manager userInfo reqHdrs gqlReqUnparsed rsi G.OperationTypeQuery case AO.eitherDecode respBody of diff --git a/server/src-lib/Hasura/RQL/DML/Returning.hs b/server/src-lib/Hasura/RQL/DML/Returning.hs index f2d89ccf55353..223b3693e960b 100644 --- a/server/src-lib/Hasura/RQL/DML/Returning.hs +++ b/server/src-lib/Hasura/RQL/DML/Returning.hs @@ -137,7 +137,7 @@ mkMutationOutputExp qt allCols preCalAffRows cte mutOutput strfyNum = mutationResultAlias = Identifier $ snakeCaseQualifiedObject qt <> "__mutation_result_alias" allColumnsAlias = Identifier $ snakeCaseQualifiedObject qt <> "__all_columns_alias" allColumnsSelect = S.CTESelect $ S.mkSelect - { S.selExtr = map S.mkExtr $ map pgiColumn $ sortCols allCols + { S.selExtr = map (S.mkExtr . pgiColumn) $ sortCols allCols , S.selFrom = Just $ S.mkIdenFromExp mutationResultAlias } diff --git a/server/src-lib/Hasura/RQL/Types/Common.hs b/server/src-lib/Hasura/RQL/Types/Common.hs index 1ad7625d8df23..0b3307af93869 100644 --- a/server/src-lib/Hasura/RQL/Types/Common.hs +++ b/server/src-lib/Hasura/RQL/Types/Common.hs @@ -311,7 +311,7 @@ unsafeNonNegativeInt = NonNegativeInt instance FromJSON NonNegativeInt where parseJSON = withScientific "NonNegativeInt" $ \t -> do - case (t >= 0) of + case t >= 0 of True -> NonNegativeInt <$> maybeInt (toBoundedInteger t) False -> fail "negative value not allowed" where @@ -332,7 +332,7 @@ mkNonNegativeDiffTime x = case x >= 0 of instance FromJSON NonNegativeDiffTime where parseJSON = withScientific "NonNegativeDiffTime" $ \t -> do - case (t >= 0) of + case t >= 0 of True -> return $ NonNegativeDiffTime . realToFrac $ t False -> fail "negative value not allowed" @@ -372,7 +372,7 @@ newtype Timeout = Timeout { unTimeout :: Int } instance FromJSON Timeout where parseJSON = withScientific "Timeout" $ \t -> do timeout <- onNothing (toBoundedInteger t) $ fail (show t <> " is out of bounds") - case (timeout >= 0) of + case timeout >= 0 of True -> return $ Timeout timeout False -> fail "timeout value cannot be negative" diff --git a/server/src-lib/Hasura/RQL/Types/CustomTypes.hs b/server/src-lib/Hasura/RQL/Types/CustomTypes.hs index bdf70a7b5ee83..300466e7919e0 100644 --- a/server/src-lib/Hasura/RQL/Types/CustomTypes.hs +++ b/server/src-lib/Hasura/RQL/Types/CustomTypes.hs @@ -174,7 +174,7 @@ idScalar = $$(G.litName "ID") defaultScalars :: [ScalarTypeDefinition] defaultScalars = - map (flip ScalarTypeDefinition Nothing) + map (`ScalarTypeDefinition` Nothing) [intScalar, floatScalar, stringScalar, boolScalar, idScalar] newtype EnumTypeName @@ -230,7 +230,7 @@ instance J.ToJSON AnnotatedScalarType where toJSON (ASTReusedScalar name st) = J.object ["name" J..= name, "type" J..= st] data NonObjectCustomType - = NOCTScalar !(AnnotatedScalarType) + = NOCTScalar !AnnotatedScalarType | NOCTEnum !EnumTypeDefinition | NOCTInputObject !InputObjectTypeDefinition deriving (Generic) diff --git a/server/src-lib/Hasura/RQL/Types/Error.hs b/server/src-lib/Hasura/RQL/Types/Error.hs index 67eb69f868a6c..00fab75884a73 100644 --- a/server/src-lib/Hasura/RQL/Types/Error.hs +++ b/server/src-lib/Hasura/RQL/Types/Error.hs @@ -210,7 +210,7 @@ encodeJSONPath = format "$" specialChars [] = True -- first char must not be number specialChars (c:xs) = notElem c (alphabet ++ "_") || - any (flip notElem (alphaNumerics ++ "_-")) xs + any (`notElem` (alphaNumerics ++ "_-")) xs instance Q.FromPGConnErr QErr where fromPGConnErr c = diff --git a/server/src-lib/Hasura/RQL/Types/RemoteRelationship.hs b/server/src-lib/Hasura/RQL/Types/RemoteRelationship.hs index b9aca9f27b9cd..54ec0d0661684 100644 --- a/server/src-lib/Hasura/RQL/Types/RemoteRelationship.hs +++ b/server/src-lib/Hasura/RQL/Types/RemoteRelationship.hs @@ -1,4 +1,3 @@ -{-# LANGUAGE DisambiguateRecordFields #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE RecordWildCards #-} @@ -116,7 +115,7 @@ instance ToJSON (RemoteFieldInfo 'Postgres) where -- over (brought into scope, e.g. in 'rtrHasuraFields'. newtype RemoteArguments = RemoteArguments - { getRemoteArguments :: (HashMap G.Name (G.Value G.Name)) + { getRemoteArguments :: HashMap G.Name (G.Value G.Name) } deriving (Show, Eq, Lift, Cacheable, NFData) instance ToJSON RemoteArguments where diff --git a/server/src-lib/Hasura/RQL/Types/RemoteSchema.hs b/server/src-lib/Hasura/RQL/Types/RemoteSchema.hs index dbf090d771e67..2e12a47e3a751 100644 --- a/server/src-lib/Hasura/RQL/Types/RemoteSchema.hs +++ b/server/src-lib/Hasura/RQL/Types/RemoteSchema.hs @@ -81,8 +81,8 @@ $(J.deriveJSON (J.aesonDrop 5 J.snakeCase) ''RemoteSchemaNameQuery) getUrlFromEnv :: (MonadIO m, MonadError QErr m) => Env.Environment -> Text -> m N.URI getUrlFromEnv env urlFromEnv = do let mEnv = Env.lookupEnv env $ T.unpack urlFromEnv - uri <- maybe (throw400 InvalidParams $ envNotFoundMsg urlFromEnv) return mEnv - maybe (throw400 InvalidParams $ invalidUri uri) return $ N.parseURI uri + uri <- onNothing mEnv (throw400 InvalidParams $ envNotFoundMsg urlFromEnv) + onNothing (N.parseURI uri) (throw400 InvalidParams $ invalidUri uri) where invalidUri x = "not a valid URI: " <> T.pack x envNotFoundMsg e = "environment variable '" <> e <> "' not set" diff --git a/server/src-lib/Hasura/RQL/Types/ScheduledTrigger.hs b/server/src-lib/Hasura/RQL/Types/ScheduledTrigger.hs index caf4e17245ee0..cf058154efa65 100644 --- a/server/src-lib/Hasura/RQL/Types/ScheduledTrigger.hs +++ b/server/src-lib/Hasura/RQL/Types/ScheduledTrigger.hs @@ -51,11 +51,11 @@ instance FromJSON STRetryConf where parseJSON = withObject "STRetryConf" \o -> do numRetries' <- o .:? "num_retries" .!= 0 retryInterval <- - o .:? "retry_interval_seconds" .!= (unsafeNonNegativeDiffTime $ seconds 10) + o .:? "retry_interval_seconds" .!= unsafeNonNegativeDiffTime (seconds 10) timeout <- - o .:? "timeout_seconds" .!= (unsafeNonNegativeDiffTime $ seconds 60) + o .:? "timeout_seconds" .!= unsafeNonNegativeDiffTime (seconds 60) tolerance <- - o .:? "tolerance_seconds" .!= (unsafeNonNegativeDiffTime $ hours 6) + o .:? "tolerance_seconds" .!= unsafeNonNegativeDiffTime (hours 6) if numRetries' < 0 then fail "num_retries cannot be a negative value" else pure $ STRetryConf numRetries' retryInterval timeout tolerance diff --git a/server/src-lib/Hasura/RQL/Types/SchemaCache.hs b/server/src-lib/Hasura/RQL/Types/SchemaCache.hs index 46631b6653f37..ec75c65812f20 100644 --- a/server/src-lib/Hasura/RQL/Types/SchemaCache.hs +++ b/server/src-lib/Hasura/RQL/Types/SchemaCache.hs @@ -311,7 +311,7 @@ askFunctionInfo => QualifiedFunction -> m FunctionInfo askFunctionInfo qf = do sc <- askSchemaCache - maybe throwNoFn return $ M.lookup qf $ scFunctions sc + onNothing (M.lookup qf $ scFunctions sc) throwNoFn where throwNoFn = throw400 NotExists $ "function not found in cache " <>> qf diff --git a/server/src-lib/Hasura/RQL/Types/Table.hs b/server/src-lib/Hasura/RQL/Types/Table.hs index 3498bfa4f4603..9f6c520400950 100644 --- a/server/src-lib/Hasura/RQL/Types/Table.hs +++ b/server/src-lib/Hasura/RQL/Types/Table.hs @@ -439,7 +439,7 @@ tciUniqueOrPrimaryKeyConstraints info = NE.nonEmpty $ data TableInfo (b :: Backend) = TableInfo - { _tiCoreInfo :: (TableCoreInfo b) + { _tiCoreInfo :: TableCoreInfo b , _tiRolePermInfoMap :: !(RolePermInfoMap b) , _tiEventTriggerInfoMap :: !EventTriggerInfoMap } deriving (Generic) diff --git a/server/src-lib/Hasura/Server/API/PGDump.hs b/server/src-lib/Hasura/Server/API/PGDump.hs index bd072179a276b..f39215c2f02e7 100644 --- a/server/src-lib/Hasura/Server/API/PGDump.hs +++ b/server/src-lib/Hasura/Server/API/PGDump.hs @@ -34,7 +34,7 @@ execPGDump -> m BL.ByteString execPGDump b ci = do eOutput <- liftIO $ try execProcess - output <- either throwException return eOutput + output <- onLeft eOutput throwException case output of Left err -> RTE.throw500 $ "error while executing pg_dump: " <> err @@ -53,7 +53,7 @@ execPGDump b ci = do opts = connString : "--encoding=utf8" : prbOpts b clean str - | fromMaybe False (prbCleanOutput b) = + | Just True == prbCleanOutput b = unlines $ filter (not . shouldDropLine) (lines str) | otherwise = str diff --git a/server/src-lib/Hasura/Server/API/Query.hs b/server/src-lib/Hasura/Server/API/Query.hs index 66022de291710..507de541a548d 100644 --- a/server/src-lib/Hasura/Server/API/Query.hs +++ b/server/src-lib/Hasura/Server/API/Query.hs @@ -313,7 +313,7 @@ queryModifiesSchemaCache (RQV2 qi) = case qi of RQV2TrackFunction _ -> True getQueryAccessMode :: (MonadError QErr m) => RQLQuery -> m Q.TxAccess -getQueryAccessMode q = (fromMaybe Q.ReadOnly) <$> getQueryAccessMode' q +getQueryAccessMode q = fromMaybe Q.ReadOnly <$> getQueryAccessMode' q where getQueryAccessMode' :: (MonadError QErr m) => RQLQuery -> m (Maybe Q.TxAccess) @@ -331,12 +331,12 @@ getQueryAccessMode q = (fromMaybe Q.ReadOnly) <$> getQueryAccessMode' q throw400 BadRequest $ "incompatible access mode requirements in bulk query, " <> "expected access mode: " <> - (T.pack $ maybe "ANY" show expectedMode) <> + T.pack (maybe "ANY" show expectedMode) <> " but " <> "$.args[" <> - (T.pack $ show i) <> + T.pack (show i) <> "] forces " <> - (T.pack $ show errMode) + T.pack (show errMode) getQueryAccessMode' (RQV2 _) = pure $ Just Q.ReadWrite -- | onRight, return reconciled access mode. onLeft, return conflicting access mode diff --git a/server/src-lib/Hasura/Server/App.hs b/server/src-lib/Hasura/Server/App.hs index 26f1498ed6a2a..2cb88726d605d 100644 --- a/server/src-lib/Hasura/Server/App.hs +++ b/server/src-lib/Hasura/Server/App.hs @@ -237,7 +237,7 @@ mapActionT => (m (MTC.StT (Spock.ActionCtxT ()) a) -> n (MTC.StT (Spock.ActionCtxT ()) a)) -> Spock.ActionT m a -> Spock.ActionT n a -mapActionT f tma = MTC.restoreT . pure =<< (MTC.liftWith $ \run -> f (run tma)) +mapActionT f tma = MTC.restoreT . pure =<< MTC.liftWith (\run -> f (run tma)) mkSpockAction @@ -280,8 +280,7 @@ mkSpockAction serverCtx qErrEncoder qErrModifier apiHandler = do lift $ Tracing.attachMetadata [("request_id", unRequestId requestId)] userInfoE <- fmap fst <$> lift (resolveUserInfo logger manager headers authMode) - userInfo <- either (logErrorAndResp Nothing requestId req (reqBody, Nothing) False headers . qErrModifier) - return userInfoE + userInfo <- onLeft userInfoE (logErrorAndResp Nothing requestId req (reqBody, Nothing) False headers . qErrModifier) let handlerState = HandlerCtx serverCtx userInfo headers requestId ipAddress includeInternal = shouldIncludeInternal (_uiRole userInfo) $ @@ -293,8 +292,7 @@ mkSpockAction serverCtx qErrEncoder qErrModifier apiHandler = do return (res, Nothing) AHPost handler -> do parsedReqE <- runExceptT $ parseBody reqBody - parsedReq <- either (logErrorAndResp (Just userInfo) requestId req (reqBody, Nothing) includeInternal headers . qErrModifier) - return parsedReqE + parsedReq <- onLeft parsedReqE (logErrorAndResp (Just userInfo) requestId req (reqBody, Nothing) includeInternal headers . qErrModifier) res <- lift $ runReaderT (runExceptT $ handler parsedReq) handlerState return (res, Just parsedReq) @@ -657,7 +655,7 @@ mkWaiApp env isoLevel logger sqlGenCtx enableAL pool pgExecCtxCustom ci httpMana cacheLock <- liftIO $ newMVar () cacheCell <- liftIO $ newIORef (schemaCache, initSchemaCacheVer) -- planCache <- liftIO $ E.initPlanCache planCacheOptions - let cacheRef = SchemaCacheRef cacheLock cacheCell (E.clearPlanCache {- planCache -}) + let cacheRef = SchemaCacheRef cacheLock cacheCell E.clearPlanCache -- pure (planCache, cacheRef) pure cacheRef @@ -699,9 +697,9 @@ httpApp corsCfg serverCtx enableConsole consoleAssetsDir enableTelemetry = do sc <- getSCFromRef $ scCacheRef serverCtx dbOk <- liftIO $ _pecCheckHealth $ scPGExecCtx serverCtx if dbOk - then Spock.setStatus HTTP.status200 >> (Spock.text $ if null (scInconsistentObjs sc) - then "OK" - else "WARN: inconsistent objects in schema") + then Spock.setStatus HTTP.status200 >> Spock.text (if null (scInconsistentObjs sc) + then "OK" + else "WARN: inconsistent objects in schema") else Spock.setStatus HTTP.status500 >> Spock.text "ERROR" Spock.get "v1/version" $ do diff --git a/server/src-lib/Hasura/Server/Auth/JWT.hs b/server/src-lib/Hasura/Server/Auth/JWT.hs index dcc9900f1b81c..bbd3e164fe40d 100644 --- a/server/src-lib/Hasura/Server/Auth/JWT.hs +++ b/server/src-lib/Hasura/Server/Auth/JWT.hs @@ -225,7 +225,7 @@ jwkRefreshCtrl logger manager url ref time = do liftIO $ C.sleep time forever $ Tracing.runTraceT "jwk refresh" do res <- runExceptT $ updateJwkRef logger manager url ref - mTime <- either (const $ logNotice >> return Nothing) return res + mTime <- onLeft res (const $ logNotice >> return Nothing) -- if can't parse time from header, defaults to 1 min -- let delay = maybe (minutes 1) fromUnits mTime let delay = maybe (minutes 1) convertDuration mTime @@ -257,7 +257,7 @@ updateJwkRef (Logger logger) manager url jwkRef = do let req = initReq { HTTP.requestHeaders = addDefaultHeaders (HTTP.requestHeaders initReq) } Tracing.tracedHttpRequest req \req' -> do liftIO $ HTTP.httpLbs req' manager - resp <- either logAndThrowHttp return res + resp <- onLeft res logAndThrowHttp let status = resp ^. Wreq.responseStatus respBody = resp ^. Wreq.responseBody statusCode = status ^. Wreq.statusCode @@ -268,7 +268,7 @@ updateJwkRef (Logger logger) manager url jwkRef = do logAndThrow err let parseErr e = JFEJwkParseError (T.pack e) $ "Error parsing JWK from url: " <> urlT - !jwkset <- either (logAndThrow . parseErr) return $ J.eitherDecode' respBody + !jwkset <- onLeft (J.eitherDecode' respBody) (logAndThrow . parseErr) liftIO $ do #ifndef PROFILING $assertNFHere jwkset -- so we don't write thunks to mutable vars @@ -371,7 +371,7 @@ processJwt_ processAuthZHeader_ jwtCtx headers mUnAuthRole = pure (userInfo, expTimeM) withoutAuthZHeader = do - unAuthRole <- maybe missingAuthzHeader return mUnAuthRole + unAuthRole <- onNothing mUnAuthRole missingAuthzHeader userInfo <- mkUserInfo (URBPreDetermined unAuthRole) UAdminSecretNotSent $ mkSessionVariablesHeaders headers pure (userInfo, Nothing) @@ -413,7 +413,7 @@ processAuthZHeader jwtCtx authzHeader = do liftJWTError :: (MonadError e' m) => (e -> e') -> ExceptT e m a -> m a liftJWTError ef action = do res <- runExceptT action - either (throwError . ef) return res + onLeft res (throwError . ef) invalidJWTError e = err400 JWTInvalid $ "Could not verify JWT: " <> T.pack (show e) @@ -497,8 +497,7 @@ parseClaimsMap unregisteredClaims jcxClaims = parseObjectFromString namespace claimsFmt jVal = case (claimsFmt, jVal) of (JCFStringifiedJson, J.String v) -> - either (const $ claimsErr $ strngfyErr v) return - $ J.eitherDecodeStrict $ T.encodeUtf8 v + onLeft (J.eitherDecodeStrict $ T.encodeUtf8 v) (const $ claimsErr $ strngfyErr v) (JCFStringifiedJson, _) -> claimsErr "expecting a string when claims_format is stringified_json" (JCFJson, J.Object o) -> return o @@ -622,7 +621,7 @@ parseHasuraClaims claimsMap = do where parseClaim :: J.FromJSON a => SessionVariable -> Text -> m a parseClaim claim hint = do - claimV <- maybe missingClaim return $ Map.lookup claim claimsMap + claimV <- onNothing (Map.lookup claim claimsMap) missingClaim parseJwtClaim claimV $ "invalid " <> claimText <> "; " <> hint where missingClaim = throw400 JWTRoleClaimMissing $ "JWT claim does not contain " <> claimText diff --git a/server/src-lib/Hasura/Server/CheckUpdates.hs b/server/src-lib/Hasura/Server/CheckUpdates.hs index 4b8351180c541..6af9f78cf835a 100644 --- a/server/src-lib/Hasura/Server/CheckUpdates.hs +++ b/server/src-lib/Hasura/Server/CheckUpdates.hs @@ -30,7 +30,7 @@ newtype UpdateInfo $(A.deriveJSON (A.aesonDrop 2 A.snakeCase) ''UpdateInfo) -checkForUpdates :: (HasVersion) => LoggerCtx a -> H.Manager -> IO void +checkForUpdates :: HasVersion => LoggerCtx a -> H.Manager -> IO void checkForUpdates (LoggerCtx loggerSet _ _ _) manager = do let options = wreqOptions manager [] url <- getUrl diff --git a/server/src-lib/Hasura/Server/Init.hs b/server/src-lib/Hasura/Server/Init.hs index 918cdfe0806f1..381d220d4b6e2 100644 --- a/server/src-lib/Hasura/Server/Init.hs +++ b/server/src-lib/Hasura/Server/Init.hs @@ -100,7 +100,7 @@ withEnvBool bVal envVar = where considerEnv' = do mEnvVal <- considerEnv envVar - maybe (return False) return mEnvVal + return $ Just True == mEnvVal withEnvJwtConf :: Maybe JWTConfig -> String -> WithEnv (Maybe JWTConfig) withEnvJwtConf jVal envVar = @@ -154,7 +154,7 @@ mkServeOptions rso = do withEnv (rsoEnabledAPIs rso) (fst enabledAPIsEnv) lqOpts <- mkLQOpts enableAL <- withEnvBool (rsoEnableAllowlist rso) $ fst enableAllowlistEnv - enabledLogs <- maybe L.defaultEnabledLogTypes (Set.fromList) <$> + enabledLogs <- maybe L.defaultEnabledLogTypes Set.fromList <$> withEnv (rsoEnabledLogTypes rso) (fst enabledLogsEnv) serverLogLevel <- fromMaybe L.LevelInfo <$> withEnv (rsoLogLevel rso) (fst logLevelEnv) planCacheOptions <- E.PlanCacheOptions . fromMaybe 4000 <$> @@ -206,7 +206,7 @@ mkServeOptions rso = do mkAuthHook (AuthHookG mUrl mType) = do mUrlEnv <- withEnv mUrl $ fst authHookEnv authModeM <- withEnv mType (fst authHookModeEnv) - ty <- maybe (authHookTyEnv mType) return authModeM + ty <- onNothing authModeM (authHookTyEnv mType) return (flip AuthHookG ty <$> mUrlEnv) -- Also support HASURA_GRAPHQL_AUTH_HOOK_TYPE diff --git a/server/src-lib/Hasura/Server/Migrate.hs b/server/src-lib/Hasura/Server/Migrate.hs index 1653965a18b41..aa745941bd9cf 100644 --- a/server/src-lib/Hasura/Server/Migrate.hs +++ b/server/src-lib/Hasura/Server/Migrate.hs @@ -171,21 +171,21 @@ migrateCatalog env migrationTime = do view _2 <$> runCacheRWT schemaCache recreateSystemMetadata doesSchemaExist schemaName = - liftTx $ (runIdentity . Q.getRow) <$> Q.withQE defaultTxErrorHandler [Q.sql| + liftTx $ runIdentity . Q.getRow <$> Q.withQE defaultTxErrorHandler [Q.sql| SELECT EXISTS ( SELECT 1 FROM information_schema.schemata WHERE schema_name = $1 ) |] (Identity schemaName) False doesTableExist schemaName tableName = - liftTx $ (runIdentity . Q.getRow) <$> Q.withQE defaultTxErrorHandler [Q.sql| + liftTx $ runIdentity . Q.getRow <$> Q.withQE defaultTxErrorHandler [Q.sql| SELECT EXISTS ( SELECT 1 FROM pg_tables WHERE schemaname = $1 AND tablename = $2 ) |] (schemaName, tableName) False isExtensionAvailable schemaName = - liftTx $ (runIdentity . Q.getRow) <$> Q.withQE defaultTxErrorHandler [Q.sql| + liftTx $ runIdentity . Q.getRow <$> Q.withQE defaultTxErrorHandler [Q.sql| SELECT EXISTS ( SELECT 1 FROM pg_catalog.pg_available_extensions WHERE name = $1 @@ -284,9 +284,9 @@ migrations dryRun = ) |] in TH.listE -- version 0.8 is the only non-integral catalog version - $ [| ("0.8", (MigrationPair $(migrationFromFile "08" "1") Nothing)) |] + $ [| ("0.8", MigrationPair $(migrationFromFile "08" "1") Nothing) |] : migrationsFromFile [2..3] - ++ [| ("3", (MigrationPair from3To4 Nothing)) |] + ++ [| ("3", MigrationPair from3To4 Nothing) |] : migrationsFromFile [5..latestCatalogVersion]) where runTxOrPrint :: Q.Query -> m () diff --git a/server/src-lib/Hasura/Server/SchemaUpdate.hs b/server/src-lib/Hasura/Server/SchemaUpdate.hs index 03eb21e6bd934..63e16f109a125 100644 --- a/server/src-lib/Hasura/Server/SchemaUpdate.hs +++ b/server/src-lib/Hasura/Server/SchemaUpdate.hs @@ -134,7 +134,7 @@ listener sqlGenCtx pool logger httpMgr updateEventRef forever $ do listenResE <- liftIO $ runExceptT $ PG.listen pool pgChannel notifyHandler - either onError return listenResE + onLeft listenResE onError logWarn C.sleep $ seconds 1 where diff --git a/server/src-lib/Hasura/Server/Version.hs b/server/src-lib/Hasura/Server/Version.hs index 59da03bf662f4..759ee77bee0b0 100644 --- a/server/src-lib/Hasura/Server/Version.hs +++ b/server/src-lib/Hasura/Server/Version.hs @@ -88,7 +88,7 @@ consoleAssetsVersion = case currentVersion of Nothing -> Nothing Just r -> if | T.null r -> Nothing - | otherwise -> T.pack <$> (getChannelFromPreRelease $ T.unpack r) + | otherwise -> T.pack <$> getChannelFromPreRelease (T.unpack r) getChannelFromPreRelease :: String -> Maybe String getChannelFromPreRelease sv = sv =~~ ("^([a-z]+)"::String) diff --git a/server/src-lib/Network/URI/Extended.hs b/server/src-lib/Network/URI/Extended.hs index 5202691143523..ff435e89da764 100644 --- a/server/src-lib/Network/URI/Extended.hs +++ b/server/src-lib/Network/URI/Extended.hs @@ -16,7 +16,7 @@ import qualified Data.Text as T instance {-# INCOHERENT #-} FromJSON URI where parseJSON (String uri) = do let mUrl = parseURI $ T.unpack uri - maybe (fail "not a valid URI") return mUrl + onNothing mUrl (fail "not a valid URI") parseJSON _ = fail "not a valid URI" instance {-# INCOHERENT #-} ToJSON URI where diff --git a/server/src-lib/Network/Wai/Handler/WebSockets/Custom.hs b/server/src-lib/Network/Wai/Handler/WebSockets/Custom.hs index cb1986bc273d1..1a25e4e612732 100644 --- a/server/src-lib/Network/Wai/Handler/WebSockets/Custom.hs +++ b/server/src-lib/Network/Wai/Handler/WebSockets/Custom.hs @@ -116,7 +116,7 @@ runWebSockets opts req ipAddress app src sink = bracket mkStream ensureClose (ap (do bs <- src return $ if BC.null bs then Nothing else Just bs) - (\mbBl -> case mbBl of + (\case Nothing -> return () Just bl -> mapM_ sink (BL.toChunks bl)) diff --git a/server/src-test/Data/NonNegativeIntSpec.hs b/server/src-test/Data/NonNegativeIntSpec.hs index 128693a34591a..89c7bfc533962 100644 --- a/server/src-test/Data/NonNegativeIntSpec.hs +++ b/server/src-test/Data/NonNegativeIntSpec.hs @@ -15,7 +15,7 @@ nonNegIntSpec :: Spec nonNegIntSpec = describe "non negative integer type" $ do it "only validates non negative integers" $ do - (mkNonNegativeInt 23) `shouldBe` (Just 23) - (mkNonNegativeInt (-23)) `shouldBe` Nothing + mkNonNegativeInt 23 `shouldBe` Just 23 + mkNonNegativeInt (-23) `shouldBe` Nothing - -- TODO: add spec for fromJSON for NonNegativeInt type \ No newline at end of file + -- TODO: add spec for fromJSON for NonNegativeInt type diff --git a/server/src-test/Data/Parser/JSONPathSpec.hs b/server/src-test/Data/Parser/JSONPathSpec.hs index 6f4f61586c745..8de1ca392310e 100644 --- a/server/src-test/Data/Parser/JSONPathSpec.hs +++ b/server/src-test/Data/Parser/JSONPathSpec.hs @@ -45,4 +45,4 @@ generateJSONPath = map (either id id) <$> listOf1 genPathElementEither keyRight <- Right <$> genKey elements [indexLeft, keyRight] genIndex = Index <$> choose (0, 100) - genKey = (Key . T.pack) <$> listOf1 (elements $ alphaNumerics ++ ".,!@#$%^&*_-?:;|/\"") + genKey = Key . T.pack <$> listOf1 (elements $ alphaNumerics ++ ".,!@#$%^&*_-?:;|/\"") diff --git a/server/src-test/Hasura/Server/AuthSpec.hs b/server/src-test/Hasura/Server/AuthSpec.hs index f9d8ebbff3804..70745bf8b7cfc 100644 --- a/server/src-test/Hasura/Server/AuthSpec.hs +++ b/server/src-test/Hasura/Server/AuthSpec.hs @@ -344,7 +344,7 @@ setupAuthModeTests = describe "setupAuthMode" $ do -- These are all various error cases, except for the AMNoAuth mode: it "with no admin secret provided" $ do setupAuthMode' Nothing Nothing Nothing Nothing - `shouldReturn` (Right AMNoAuth) + `shouldReturn` Right AMNoAuth -- We insist on an admin secret in order to use webhook or JWT auth: setupAuthMode' Nothing Nothing (Just fakeJWTConfig) Nothing `shouldReturn` Left () @@ -419,7 +419,7 @@ parseClaimsMapTests = describe "parseClaimMapTests" $ do [ "x-hasura-allowed-roles" .= (["user","editor"] :: [Text]) , "x-hasura-default-role" .= ("user" :: Text) ] - let obj = (unObject $ ["claims_map" .= claimsObj]) + let obj = unObject $ ["claims_map" .= claimsObj] parseClaimsMap_ obj (JCNamespace (ClaimNs "claims_map") defaultClaimsFormat) `shouldReturn` Right defaultClaimsMap @@ -429,7 +429,7 @@ parseClaimsMapTests = describe "parseClaimMapTests" $ do [ "x-hasura-allowed-roles" .= (["user","editor"] :: [Text]) , "x-hasura-default-role" .= ("user" :: Text) ] - let obj = (unObject $ ["claims_map" .= claimsObj]) + let obj = unObject $ ["claims_map" .= claimsObj] parseClaimsMap_ obj (JCNamespace (ClaimNs "wrong_claims_map") defaultClaimsFormat) `shouldReturn` Left JWTInvalidClaims @@ -475,7 +475,7 @@ parseClaimsMapTests = describe "parseClaimMapTests" $ do let customDefRoleClaim = mkCustomDefaultRoleClaim (Just "$.roles.default") Nothing customAllowedRolesClaim = mkCustomAllowedRoleClaim (Just "$.roles.allowed") Nothing otherClaims = Map.fromList - [(userIdClaim, (mkCustomOtherClaim (Just "$.user.id") Nothing))] + [(userIdClaim, mkCustomOtherClaim (Just "$.user.id") Nothing)] customClaimsMap = JWTCustomClaimsMap customDefRoleClaim customAllowedRolesClaim otherClaims parseClaimsMap_ obj (JCMap customClaimsMap) @@ -521,17 +521,17 @@ parseClaimsMapTests = describe "parseClaimMapTests" $ do , (defaultRoleClaim, J.toJSON (mkRoleNameE "editor")) ]) -mkCustomDefaultRoleClaim :: (Maybe Text) -> (Maybe Text) -> JWTCustomClaimsMapDefaultRole +mkCustomDefaultRoleClaim :: Maybe Text -> Maybe Text -> JWTCustomClaimsMapDefaultRole mkCustomDefaultRoleClaim claimPath defVal = -- check if claimPath is provided, if not then use the default value -- as the literal value by removing the `Maybe` of defVal case claimPath of Just path -> JWTCustomClaimsMapJSONPath (mkJSONPathE path) $ defRoleName - Nothing -> JWTCustomClaimsMapStatic $ maybe (mkRoleNameE "user") id defRoleName + Nothing -> JWTCustomClaimsMapStatic $ fromMaybe (mkRoleNameE "user") defRoleName where defRoleName = mkRoleNameE <$> defVal -mkCustomAllowedRoleClaim :: (Maybe Text) -> (Maybe [Text]) -> JWTCustomClaimsMapAllowedRoles +mkCustomAllowedRoleClaim :: Maybe Text -> Maybe [Text] -> JWTCustomClaimsMapAllowedRoles mkCustomAllowedRoleClaim claimPath defVal = -- check if claimPath is provided, if not then use the default value -- as the literal value by removing the `Maybe` of defVal @@ -539,18 +539,18 @@ mkCustomAllowedRoleClaim claimPath defVal = Just path -> JWTCustomClaimsMapJSONPath (mkJSONPathE path) $ defAllowedRoles Nothing -> JWTCustomClaimsMapStatic $ - maybe (fmap mkRoleNameE $ ["user", "editor"]) id defAllowedRoles + fromMaybe (mkRoleNameE <$> ["user", "editor"]) defAllowedRoles where defAllowedRoles = fmap mkRoleNameE <$> defVal -- use for claims other than `x-hasura-default-role` and `x-hasura-allowed-roles` -mkCustomOtherClaim :: (Maybe Text) -> (Maybe Text) -> JWTCustomClaimsMapValue +mkCustomOtherClaim :: Maybe Text -> Maybe Text -> JWTCustomClaimsMapValue mkCustomOtherClaim claimPath defVal = -- check if claimPath is provided, if not then use the default value -- as the literal value by removing the `Maybe` of defVal case claimPath of Just path -> JWTCustomClaimsMapJSONPath (mkJSONPathE path) $ defVal - Nothing -> JWTCustomClaimsMapStatic $ maybe "default claim value" id defVal + Nothing -> JWTCustomClaimsMapStatic $ fromMaybe "default claim value" defVal fakeJWTConfig :: JWTConfig fakeJWTConfig = diff --git a/server/src-test/Hasura/Server/MigrateSpec.hs b/server/src-test/Hasura/Server/MigrateSpec.hs index 202e8f9215d23..3b605bc1cfa28 100644 --- a/server/src-test/Hasura/Server/MigrateSpec.hs +++ b/server/src-test/Hasura/Server/MigrateSpec.hs @@ -72,7 +72,7 @@ spec pgConnInfo = do it "initializes the catalog" $ singleTransaction do env <- liftIO Env.getEnvironment time <- liftIO getCurrentTime - (dropAndInit env time) `shouldReturn` MRInitialized + dropAndInit env time `shouldReturn` MRInitialized it "is idempotent" \(NT transact) -> do let dumpSchema = execPGDump (PGDumpReqBody ["--schema-only"] (Just False)) pgConnInfo @@ -116,7 +116,7 @@ spec pgConnInfo = do it "is idempotent" \(NT transact) -> do env <- Env.getEnvironment time <- getCurrentTime - (transact $ dropAndInit env time) `shouldReturn` MRInitialized + transact (dropAndInit env time) `shouldReturn` MRInitialized firstDump <- transact dumpMetadata transact recreateSystemMetadata secondDump <- transact dumpMetadata @@ -125,7 +125,7 @@ spec pgConnInfo = do it "does not create any objects affected by ClearMetadata" \(NT transact) -> do env <- Env.getEnvironment time <- getCurrentTime - (transact $ dropAndInit env time) `shouldReturn` MRInitialized + transact (dropAndInit env time) `shouldReturn` MRInitialized firstDump <- transact dumpMetadata transact (runClearMetadata ClearMetadata) `shouldReturn` successMsg secondDump <- transact dumpMetadata diff --git a/server/src-test/Main.hs b/server/src-test/Main.hs index 444e3e7c303aa..a3342a0b8ccfa 100644 --- a/server/src-test/Main.hs +++ b/server/src-test/Main.hs @@ -72,7 +72,7 @@ unitSpecs = do describe "Hasura.Server.Auth" AuthSpec.spec describe "Hasura.Cache.Bounded" CacheBoundedSpec.spec -buildPostgresSpecs :: (HasVersion) => RawConnInfo -> IO Spec +buildPostgresSpecs :: HasVersion => RawConnInfo -> IO Spec buildPostgresSpecs pgConnOptions = do env <- getEnvironment