Skip to content

Commit 5322c54

Browse files
committed
Replace panic with exceptions
1 parent c73f53f commit 5322c54

File tree

13 files changed

+134
-62
lines changed

13 files changed

+134
-62
lines changed

cardano-chain-gen/test/Test/Cardano/Db/Mock/Config.hs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -196,7 +196,7 @@ queryDBSync env = Db.runWithConnectionNoLogging (getDBSyncPGPass env)
196196

197197
getPoolLayer :: DBSyncEnv -> IO PoolDataLayer
198198
getPoolLayer env = do
199-
pgconfig <- orDie Db.renderPGPassError $ newExceptT $ Db.readPGPass (enpPGPassSource $ dbSyncParams env)
199+
pgconfig <- runOrThrowIO $ Db.readPGPass (enpPGPassSource $ dbSyncParams env)
200200
pool <- runNoLoggingT $ createPostgresqlPool (Db.toConnectionString pgconfig) 1 -- Pool size of 1 for tests
201201
pure $
202202
postgresqlPoolDataLayer
@@ -230,8 +230,8 @@ mkShelleyCredentials bulkFile = do
230230

231231
-- | staticDir can be shared by tests running in parallel. mutableDir not.
232232
mkSyncNodeParams :: FilePath -> FilePath -> CommandLineArgs -> IO SyncNodeParams
233-
mkSyncNodeParams staticDir mutableDir CommandLineArgs {..} = do
234-
pgconfig <- orDie Db.renderPGPassError $ newExceptT Db.readPGPassDefault
233+
mkSyncNodeParams staticDir mutableDir CommandLineArgs{..} = do
234+
pgconfig <- runOrThrowIO Db.readPGPassDefault
235235
pure $
236236
SyncNodeParams
237237
{ enpConfigFile = ConfigFile $ staticDir </> (if claHasConfigFile then "test-db-sync-config.json" else "")

cardano-db-sync/src/Cardano/DbSync.hs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ import Cardano.DbSync.Era.Shelley.Offline.Http (
5555
renderFetchError,
5656
spodJson,
5757
)
58-
import Cardano.DbSync.Error
58+
import Cardano.DbSync.Error ( renderSyncNodeError, runOrThrowExcept, SyncNodeError )
5959
import Cardano.DbSync.Ledger.State
6060
import Cardano.DbSync.Rollback (unsafeRollback)
6161
import Cardano.DbSync.Sync (runSyncNodeClient)
@@ -66,8 +66,6 @@ import Cardano.Prelude hiding (Nat, (%))
6666
import Cardano.Slotting.Slot (EpochNo (..))
6767
import Control.Concurrent.Async
6868
import Control.Monad.Extra (whenJust)
69-
import Control.Monad.Trans.Except.Exit (orDie)
70-
import Control.Monad.Trans.Except.Extra (newExceptT)
7169
import qualified Data.Text as Text
7270
import Data.Version (showVersion)
7371
import Database.Persist.Postgresql (ConnectionString, withPostgresqlConn)
@@ -87,6 +85,8 @@ runDbSyncNode metricsSetters knownMigrations params =
8785

8886
runDbSync metricsSetters knownMigrations iomgr trce params aop
8987

88+
89+
9090
runDbSync ::
9191
MetricSetters ->
9292
[(Text, Text)] ->
@@ -97,7 +97,7 @@ runDbSync ::
9797
IO ()
9898
runDbSync metricsSetters knownMigrations iomgr trce params aop = do
9999
-- Read the PG connection info
100-
pgConfig <- orDie Db.renderPGPassError $ newExceptT (Db.readPGPass $ enpPGPassSource params)
100+
pgConfig <- runOrThrowIO (Db.readPGPass $ enpPGPassSource params)
101101

102102
mErrors <- liftIO $ Db.validateMigrations dbMigrationDir knownMigrations
103103
whenJust mErrors $ \(unknown, stage4orNewStage3) ->
@@ -106,7 +106,7 @@ runDbSync metricsSetters knownMigrations iomgr trce params aop = do
106106
else do
107107
let msg = Db.renderMigrationValidateError unknown
108108
logError trce msg
109-
panic msg
109+
throwIO unknown
110110

111111
logInfo trce "Schema migration files validated"
112112

cardano-db-sync/src/Cardano/DbSync/Error.hs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
{-# LANGUAGE OverloadedStrings #-}
22
{-# LANGUAGE NoImplicitPrelude #-}
3+
{-# LANGUAGE RankNTypes #-}
34

45
module Cardano.DbSync.Error (
56
SyncInvariant (..),
@@ -10,6 +11,7 @@ module Cardano.DbSync.Error (
1011
dbSyncInvariant,
1112
renderSyncInvariant,
1213
renderSyncNodeError,
14+
runOrThrowIO
1315
) where
1416

1517
import qualified Cardano.Chain.Genesis as Byron
@@ -118,3 +120,10 @@ bsBase16Encode bs =
118120
case Text.decodeUtf8' (Base16.encode bs) of
119121
Left _ -> Text.pack $ "UTF-8 decode failed for " ++ show bs
120122
Right txt -> txt
123+
124+
runOrThrowIO :: forall e a. Exception e => IO (Either e a) -> IO a
125+
runOrThrowIO ioEither = do
126+
either <- ioEither
127+
case either of
128+
Left err -> throwIO err
129+
Right a -> pure a

cardano-db-sync/src/Cardano/DbSync/Ledger/State.hs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -190,7 +190,7 @@ readStateUnsafe :: HasLedgerEnv -> STM LedgerDB
190190
readStateUnsafe env = do
191191
mState <- readTVar $ leStateVar env
192192
case mState of
193-
Strict.Nothing -> panic "LedgerState.readStateUnsafe: Ledger state is not found"
193+
Strict.Nothing -> throwSTM $ userError "LedgerState.readStateUnsafe: Ledger state is not found"
194194
Strict.Just st -> pure st
195195

196196
applyBlockAndSnapshot :: HasLedgerEnv -> CardanoBlock -> Bool -> IO (ApplyResult, Bool)

cardano-db-sync/src/Cardano/DbSync/Sync.hs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,13 +50,13 @@ import Data.Functor.Contravariant (contramap)
5050
import qualified Data.List as List
5151
import qualified Data.Text as Text
5252
import Database.Persist.Postgresql (SqlBackend)
53+
import GHC.Base (error)
5354
import Network.Mux (MuxTrace, WithMuxBearer)
5455
import Network.Mux.Types (MuxMode (..))
5556
import Network.TypedProtocol.Pipelined (N (..), Nat (Succ, Zero))
5657
import Ouroboros.Consensus.Block.Abstract (CodecConfig)
5758
import Ouroboros.Consensus.Byron.Node ()
5859
import Ouroboros.Consensus.Cardano.Node ()
59-
6060
import Ouroboros.Consensus.Config (configCodec)
6161
import Ouroboros.Consensus.Network.NodeToClient (
6262
Codecs' (..),
@@ -241,7 +241,7 @@ dbSyncProtocols syncEnv metricsSetters tc codecConfig version bversion _connecti
241241
( Client.chainSyncClientPeer $
242242
chainSyncClientFixScripts backend tracer ls
243243
)
244-
when onlyFix $ panic "All Good! This error is only thrown to exit db-sync" -- TODO fix.
244+
when onlyFix $ error "All Good! This error is only thrown to exit db-sync"
245245
setIsFixed syncEnv AllFixRan
246246
pure False
247247
else do

cardano-db-tool/app/cardano-db-tool.hs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ runCommand cmd =
5454
CmdReport report -> runReport report
5555
CmdRollback slotNo -> runRollback slotNo
5656
CmdRunMigrations mdir forceIndexes mockFix mldir -> do
57-
pgConfig <- orDie renderPGPassError $ newExceptT (readPGPass PGPassDefaultEnv)
57+
pgConfig <- runOrThrowIO (readPGPass PGPassDefaultEnv)
5858
unofficial <- snd <$> runMigrations pgConfig False mdir mldir Initial
5959
unless (null unofficial) $
6060
putStrLn $

cardano-db/src/Cardano/Db/Error.hs

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,22 @@
11
{-# LANGUAGE DeriveGeneric #-}
2+
{-# LANGUAGE LambdaCase #-}
23
{-# LANGUAGE OverloadedStrings #-}
4+
{-# LANGUAGE RankNTypes #-}
35

46
module Cardano.Db.Error (
57
LookupFail (..),
68
renderLookupFail,
9+
runOrThrowIO,
710
) where
811

12+
import Control.Exception (Exception, throwIO)
913
import qualified Data.ByteString.Base16 as Base16
1014
import Data.ByteString.Char8 (ByteString)
1115
import Data.Text (Text)
1216
import qualified Data.Text as Text
1317
import qualified Data.Text.Encoding as Text
1418
import Data.Word (Word16, Word64)
15-
import GHC.Generics
19+
import GHC.Generics (Generic)
1620

1721
data LookupFail
1822
= DbLookupBlockHash !ByteString
@@ -25,7 +29,24 @@ data LookupFail
2529
| DbMetaEmpty
2630
| DbMetaMultipleRows
2731
| DBMultipleGenesis
28-
deriving (Eq, Show, Generic)
32+
deriving (Eq, Generic)
33+
34+
instance Exception LookupFail
35+
36+
instance Show LookupFail where
37+
show =
38+
\case
39+
DbLookupBlockHash h -> "The block hash " <> show (base16encode h) <> " is missing from the DB."
40+
DbLookupBlockId blkid -> "block id " <> show blkid
41+
DbLookupMessage txt -> show txt
42+
DbLookupTxHash h -> "tx hash " <> show (base16encode h)
43+
DbLookupTxOutPair h i -> concat ["tx out pair (", show $ base16encode h, ", ", show i, ")"]
44+
DbLookupEpochNo e -> "epoch number " ++ show e
45+
DbLookupSlotNo s -> "slot number " ++ show s
46+
DbMetaEmpty -> "Meta table is empty"
47+
DbMetaMultipleRows -> "Multiple rows in Meta table which should only contain one"
48+
DBMultipleGenesis ->
49+
"Multiple Genesis blocks found. These are blocks without an EpochNo"
2950

3051
renderLookupFail :: LookupFail -> Text
3152
renderLookupFail lf =
@@ -50,3 +71,10 @@ base16encode = Text.decodeUtf8 . Base16.encode
5071

5172
textShow :: Show a => a -> Text
5273
textShow = Text.pack . show
74+
75+
runOrThrowIO :: forall e a. Exception e => IO (Either e a) -> IO a
76+
runOrThrowIO ioEither = do
77+
et <- ioEither
78+
case et of
79+
Left err -> throwIO err
80+
Right a -> pure a

cardano-db/src/Cardano/Db/Migration.hs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,8 @@ import System.IO (
7474
withFile,
7575
)
7676
import Text.Read (readMaybe)
77+
import Control.Exception (Exception)
78+
import Cardano.Prelude (Typeable)
7779

7880
newtype MigrationDir
7981
= MigrationDir FilePath
@@ -92,7 +94,9 @@ data MigrationValidateError = UnknownMigrationsFound
9294
{ missingMigrations :: [MigrationValidate]
9395
, extraMigrations :: [MigrationValidate]
9496
}
95-
deriving (Eq, Show)
97+
deriving (Eq, Show, Typeable)
98+
99+
instance Exception MigrationValidateError
96100

97101
data MigrationToRun = Initial | Full | Fix | Indexes
98102
deriving (Show, Eq)

cardano-db/src/Cardano/Db/PGConfig.hs

Lines changed: 45 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -12,16 +12,13 @@ module Cardano.Db.PGConfig (
1212
readPGPassFileEnv,
1313
readPGPassFile,
1414
readPGPassFileExit,
15-
renderPGPassError,
1615
toConnectionString,
1716
) where
1817

19-
import Cardano.Db.Text
2018
import Control.Exception (IOException)
2119
import qualified Control.Exception as Exception
2220
import Data.ByteString.Char8 (ByteString)
2321
import qualified Data.ByteString.Char8 as BS
24-
import Data.Text (Text)
2522
import qualified Data.Text as Text
2623
import Database.Persist.Postgresql (ConnectionString)
2724
import System.Environment (lookupEnv, setEnv)
@@ -132,24 +129,48 @@ data PGPassError
132129
| FailedToReadPGPassFile FilePath IOException
133130
| FailedToParsePGPassConfig ByteString
134131

135-
renderPGPassError :: PGPassError -> Text
136-
renderPGPassError pge =
137-
case pge of
138-
EnvVarableNotSet str ->
139-
mconcat ["Environment variable '", Text.pack str, " not set."]
140-
UserFailed err ->
141-
mconcat
142-
[ "readPGPassFile: User in pgpass file was specified as '*' but "
143-
, "getEffectiveUserName failed with "
144-
, textShow err
145-
]
146-
FailedToReadPGPassFile fpath err ->
147-
mconcat
148-
[ "Not able to read PGPassFile at "
149-
, textShow fpath
150-
, "."
151-
, "Failed with "
152-
, textShow err
153-
]
154-
FailedToParsePGPassConfig bs ->
155-
"Failed to parse config from " <> textShow bs
132+
instance Exception.Exception PGPassError
133+
134+
instance Show PGPassError where
135+
show e =
136+
case e of
137+
EnvVarableNotSet str ->
138+
mconcat ["Environment variable '", show str, " not set."]
139+
UserFailed err ->
140+
mconcat
141+
[ "readPGPassFile: User in pgpass file was specified as '*' but "
142+
, "getEffectiveUserName failed with "
143+
, show err
144+
]
145+
FailedToReadPGPassFile fpath err ->
146+
mconcat
147+
[ "Not able to read PGPassFile at "
148+
, show $ Text.pack fpath
149+
, "."
150+
, "Failed with "
151+
, show err
152+
]
153+
FailedToParsePGPassConfig bs ->
154+
"Failed to parse config from " <> show bs
155+
156+
-- renderPGPassError :: PGPassError -> Text
157+
-- renderPGPassError pge =
158+
-- case pge of
159+
-- EnvVarableNotSet str ->
160+
-- mconcat ["Environment variable '", Text.pack str, " not set."]
161+
-- UserFailed err ->
162+
-- mconcat
163+
-- [ "readPGPassFile: User in pgpass file was specified as '*' but "
164+
-- , "getEffectiveUserName failed with "
165+
-- , textShow err
166+
-- ]
167+
-- FailedToReadPGPassFile fpath err ->
168+
-- mconcat
169+
-- [ "Not able to read PGPassFile at "
170+
-- , textShow fpath
171+
-- , "."
172+
-- , "Failed with "
173+
-- , textShow err
174+
-- ]
175+
-- FailedToParsePGPassConfig bs ->
176+
-- "Failed to parse config from " <> textShow bs

cardano-db/src/Cardano/Db/Query.hs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,6 @@ module Cardano.Db.Query (
103103
isJust,
104104
listToMaybe,
105105
maybeToEither,
106-
renderLookupFail,
107106
unBlockId,
108107
unTxId,
109108
unTxInId,

0 commit comments

Comments
 (0)