Skip to content

Commit 87c8789

Browse files
committed
change DbAction monad to not have ExceptT
1 parent 19ba860 commit 87c8789

File tree

48 files changed

+967
-768
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

48 files changed

+967
-768
lines changed

cardano-db-sync/cardano-db-sync.cabal

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -188,7 +188,6 @@ library
188188
, memory
189189
, microlens
190190
, monad-control
191-
, monad-logger
192191
, network-mux
193192
, ouroboros-consensus
194193
, ouroboros-consensus-cardano

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

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -145,19 +145,19 @@ runDbSync metricsSetters iomgr trce params syncNodeConfigFromFile abortOnPanic =
145145
void $ unsafeRollback trce (txOutConfigToTableType txOutConfig) pgConfig slotNo
146146

147147
-- This runMigration is ONLY for delayed migrations during sync (like indexes)
148-
let runIndexesMigration mode = do
148+
let runNearTipMigration mode = do
149149
msg <- DB.getMaintenancePsqlConf pgConfig
150-
logInfo trce $ "Running database migrations in mode " <> textShow mode
150+
logInfo trce $ "Running NearTip database migrations in mode " <> textShow mode
151151
logInfo trce msg
152-
when (mode `elem` [DB.Indexes, DB.Full]) $ logWarning trce indexesMsg
152+
when (mode `elem` [DB.NearTip, DB.Full]) $ logWarning trce indexesMsg
153153
DB.runMigrations pgConfig True dbMigrationDir (Just $ DB.LogFileDir "/tmp") mode (txOutConfigToTableType txOutConfig)
154154

155155
runSyncNode
156156
metricsSetters
157157
trce
158158
iomgr
159159
dbConnectionSetting
160-
(void . runIndexesMigration)
160+
(void . runNearTipMigration)
161161
syncNodeConfigFromFile
162162
params
163163
syncOpts
@@ -188,7 +188,7 @@ runSyncNode ::
188188
SyncNodeParams ->
189189
SyncOptions ->
190190
IO ()
191-
runSyncNode metricsSetters trce iomgr dbConnSetting runIndexesMigrationFnc syncNodeConfigFromFile syncNodeParams syncOptions = do
191+
runSyncNode metricsSetters trce iomgr dbConnSetting runNearTipMigrationFnc syncNodeConfigFromFile syncNodeParams syncOptions = do
192192
whenJust maybeLedgerDir $
193193
\enpLedgerStateDir -> do
194194
createDirectoryIfMissing True (unLedgerStateDir enpLedgerStateDir)
@@ -222,7 +222,7 @@ runSyncNode metricsSetters trce iomgr dbConnSetting runIndexesMigrationFnc syncN
222222
genCfg
223223
syncNodeConfigFromFile
224224
syncNodeParams
225-
runIndexesMigrationFnc
225+
runNearTipMigrationFnc
226226

227227
-- Warn the user that jsonb datatypes are being removed from the database schema.
228228
when (isJsonbInSchema && removeJsonbFromSchemaConfig) $ do

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

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ module Cardano.DbSync.Api (
1414
isConsistent,
1515
getDisableInOutState,
1616
getRanIndexes,
17-
runIndexesMigrations,
17+
runNearTipMigrations,
1818
initPruneConsumeMigration,
1919
runConsumedTxOutMigrationsMaybe,
2020
runAddJsonbToSchema,
@@ -120,12 +120,12 @@ getRanIndexes :: SyncEnv -> IO Bool
120120
getRanIndexes env = do
121121
readTVarIO $ envIndexes env
122122

123-
runIndexesMigrations :: SyncEnv -> IO ()
124-
runIndexesMigrations env = do
123+
runNearTipMigrations :: SyncEnv -> IO ()
124+
runNearTipMigrations env = do
125125
haveRan <- readTVarIO $ envIndexes env
126126
unless haveRan $ do
127-
envRunIndexesMigration env DB.Indexes
128-
logInfo (getTrace env) "Indexes were created"
127+
envRunNearTipMigration env DB.NearTip
128+
logInfo (getTrace env) "NearTip migrations were ran successfully."
129129
atomically $ writeTVar (envIndexes env) True
130130

131131
initPruneConsumeMigration :: Bool -> Bool -> Bool -> Bool -> DB.PruneConsumeMigration
@@ -307,7 +307,7 @@ mkSyncEnvFromConfig ::
307307
-- | run migration function
308308
RunMigration ->
309309
IO (Either SyncNodeError SyncEnv)
310-
mkSyncEnvFromConfig trce dbEnv syncOptions genCfg syncNodeConfigFromFile syncNodeParams runIndexesMigrationFnc =
310+
mkSyncEnvFromConfig trce dbEnv syncOptions genCfg syncNodeConfigFromFile syncNodeParams runNearTipMigrationFnc =
311311
case genCfg of
312312
GenesisCardano _ bCfg sCfg _ _
313313
| unProtocolMagicId (Byron.configProtocolMagicId bCfg) /= Shelley.sgNetworkMagic (scConfig sCfg) ->
@@ -342,7 +342,7 @@ mkSyncEnvFromConfig trce dbEnv syncOptions genCfg syncNodeConfigFromFile syncNod
342342
(SystemStart . Byron.gdStartTime $ Byron.configGenesisData bCfg)
343343
syncNodeConfigFromFile
344344
syncNodeParams
345-
runIndexesMigrationFnc
345+
runNearTipMigrationFnc
346346

347347
mkSyncEnv ::
348348
Trace IO Text ->
@@ -356,7 +356,7 @@ mkSyncEnv ::
356356
SyncNodeParams ->
357357
RunMigration ->
358358
IO SyncEnv
359-
mkSyncEnv trce dbEnv syncOptions protoInfo nw nwMagic systemStart syncNodeConfigFromFile syncNP runIndexesMigrationFnc = do
359+
mkSyncEnv trce dbEnv syncOptions protoInfo nw nwMagic systemStart syncNodeConfigFromFile syncNP runNearTipMigrationFnc = do
360360
dbCNamesVar <- newTVarIO =<< DB.runDbActionIO dbEnv DB.queryRewardAndEpochStakeConstraints
361361
cache <-
362362
if soptCache syncOptions
@@ -418,7 +418,7 @@ mkSyncEnv trce dbEnv syncOptions protoInfo nw nwMagic systemStart syncNodeConfig
418418
, envOffChainVoteResultQueue = oarq
419419
, envOffChainVoteWorkQueue = oawq
420420
, envOptions = syncOptions
421-
, envRunIndexesMigration = runIndexesMigrationFnc
421+
, envRunNearTipMigration = runNearTipMigrationFnc
422422
, envSyncNodeConfig = syncNodeConfigFromFile
423423
, envSystemStart = systemStart
424424
}

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

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -6,16 +6,6 @@
66

77
module Cardano.DbSync.Api.Ledger where
88

9-
import Control.Concurrent.Class.MonadSTM.Strict (atomically, readTVarIO, writeTVar)
10-
import Control.Monad.Extra
11-
import Control.Monad.IO.Class (MonadIO, liftIO)
12-
import Data.List.Extra
13-
import Data.Map (Map)
14-
import qualified Data.Map.Strict as Map
15-
import qualified Data.Text as Text
16-
import Lens.Micro
17-
import Numeric
18-
199
import Cardano.BM.Trace (logError, logInfo, logWarning)
2010
import Cardano.Ledger.Allegra.Scripts (Timelock)
2111
import Cardano.Ledger.Alonzo.Scripts
@@ -26,7 +16,16 @@ import Cardano.Ledger.Core (Value)
2616
import Cardano.Ledger.Mary.Value
2717
import Cardano.Ledger.Shelley.LedgerState
2818
import Cardano.Ledger.TxIn
29-
import Cardano.Prelude (MonadError (..), textShow)
19+
import Cardano.Prelude (textShow, throwIO)
20+
import Control.Concurrent.Class.MonadSTM.Strict (atomically, readTVarIO, writeTVar)
21+
import Control.Monad.Extra
22+
import Control.Monad.IO.Class (MonadIO, liftIO)
23+
import Data.List.Extra
24+
import Data.Map (Map)
25+
import qualified Data.Map.Strict as Map
26+
import qualified Data.Text as Text
27+
import Lens.Micro
28+
import Numeric
3029
import Ouroboros.Consensus.Cardano.Block hiding (CardanoBlock)
3130
import Ouroboros.Consensus.Ledger.Extended (ExtLedgerState, ledgerState)
3231
import qualified Ouroboros.Consensus.Shelley.Ledger.Ledger as Consensus
@@ -158,7 +157,7 @@ prepareTxOut syncEnv (TxIn txIntxId (TxIx index), txOut) = do
158157
let genTxOut = fromTxOut (fromIntegral index) txOut
159158
eTxId <- queryTxIdWithCache syncEnv txIntxId
160159
txId <- case eTxId of
161-
Left err -> throwError err
160+
Left err -> liftIO $ throwIO err
162161
Right tid -> pure tid
163162
insertTxOut syncEnv iopts (txId, txHashByteString) genTxOut
164163
where

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ data SyncEnv = SyncEnv
5757
, envOffChainVoteWorkQueue :: !(StrictTBQueue IO OffChainVoteWorkQueue)
5858
, envOptions :: !SyncOptions
5959
, envSyncNodeConfig :: !SyncNodeConfig
60-
, envRunIndexesMigration :: RunMigration
60+
, envRunNearTipMigration :: RunMigration
6161
, envSystemStart :: !SystemStart
6262
}
6363

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

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
{-# LANGUAGE FlexibleContexts #-}
12
{-# LANGUAGE OverloadedStrings #-}
23
{-# LANGUAGE NoImplicitPrelude #-}
34

@@ -62,7 +63,7 @@ writeEpochBlockDiffToCache ::
6263
DB.DbAction m ()
6364
writeEpochBlockDiffToCache cache epCurrent =
6465
case cache of
65-
NoCache -> throwError $ DB.DbError (DB.mkDbCallStack "writeEpochBlockDiffToCache") "Cache is NoCache" Nothing
66+
NoCache -> liftIO $ throwIO $ DB.DbError (DB.mkDbCallStack "writeEpochBlockDiffToCache") "Cache is NoCache" Nothing
6667
ActiveCache ci -> do
6768
cE <- liftIO $ readTVarIO (cEpoch ci)
6869
case (ceMapEpoch cE, ceEpochBlockDiff cE) of
@@ -84,12 +85,12 @@ writeToMapEpochCache syncEnv cache latestEpoch = do
8485
HasLedger hle -> getSecurityParameter $ leProtocolInfo hle
8586
NoLedger nle -> getSecurityParameter $ nleProtocolInfo nle
8687
case cache of
87-
NoCache -> throwError $ DB.DbError (DB.mkDbCallStack "writeToMapEpochCache") "Cache is NoCache" Nothing
88+
NoCache -> liftIO $ throwIO $ DB.DbError (DB.mkDbCallStack "writeToMapEpochCache") "Cache is NoCache" Nothing
8889
ActiveCache ci -> do
8990
-- get EpochBlockDiff so we can use the BlockId we stored when inserting blocks
9091
epochInternalCE <- readEpochBlockDiffFromCache cache
9192
case epochInternalCE of
92-
Nothing -> throwError $ DB.DbError (DB.mkDbCallStack "writeToMapEpochCache") "No epochInternalEpochCache" Nothing
93+
Nothing -> liftIO $ throwIO $ DB.DbError (DB.mkDbCallStack "writeToMapEpochCache") "No epochInternalEpochCache" Nothing
9394
Just ei -> do
9495
cE <- liftIO $ readTVarIO (cEpoch ci)
9596
let currentBlockId = ebdBlockId ei

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

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ module Cardano.DbSync.Database (
88
) where
99

1010
import Cardano.BM.Trace (logDebug, logError, logInfo)
11+
import qualified Cardano.Db as DB
1112
import Cardano.DbSync.Api
1213
import Cardano.DbSync.Api.Types (ConsistentLevel (..), SyncEnv (..))
1314
import Cardano.DbSync.DbEvent
@@ -19,10 +20,10 @@ import Cardano.DbSync.Rollback
1920
import Cardano.DbSync.Types
2021
import Cardano.DbSync.Util
2122
import Cardano.Prelude hiding (atomically)
22-
import Cardano.Slotting.Slot (WithOrigin (..))
23+
import Cardano.Slotting.Slot (SlotNo (..), WithOrigin (..))
2324
import Control.Concurrent.Class.MonadSTM.Strict
2425
import Control.Monad.Extra (whenJust)
25-
import Ouroboros.Network.Block (BlockNo, Point (..))
26+
import Ouroboros.Network.Block (BlockNo (..), Point (..))
2627
import Ouroboros.Network.Point (blockPointHash, blockPointSlot)
2728

2829
data NextState
@@ -80,14 +81,16 @@ runDbThread syncEnv metricsSetters queue = do
8081
logDbState syncEnv
8182
atomically $ putTMVar resultVar (latestPoints, currentTip)
8283
processQueue -- Continue processing
83-
84-
-- Update block and slot height metrics
8584
updateBlockMetrics :: IO ()
8685
updateBlockMetrics = do
87-
mBlock <- getDbLatestBlockInfo (envDbEnv syncEnv)
88-
whenJust mBlock $ \block -> do
89-
setDbBlockHeight metricsSetters $ bBlockNo block
90-
setDbSlotHeight metricsSetters $ bSlotNo block
86+
-- Fire-and-forget async metrics update
87+
void $ async $ DB.runPoolDbAction (envDbEnv syncEnv) $ do
88+
mBlock <- DB.queryLatestBlock
89+
liftIO $ whenJust mBlock $ \block -> do
90+
let blockNo = BlockNo $ fromMaybe 0 $ DB.blockBlockNo block
91+
slotNo = SlotNo $ fromMaybe 0 $ DB.blockSlotNo block
92+
setDbBlockHeight metricsSetters blockNo
93+
setDbSlotHeight metricsSetters slotNo
9194

9295
-- | Run the list of 'DbEvent's. Block are applied in a single set (as a transaction)
9396
-- and other operations are applied one-by-one.

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

Lines changed: 18 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,14 @@
44
{-# LANGUAGE FlexibleContexts #-}
55
{-# LANGUAGE OverloadedStrings #-}
66
{-# LANGUAGE RankNTypes #-}
7+
{-# LANGUAGE ScopedTypeVariables #-}
78
{-# LANGUAGE NoImplicitPrelude #-}
89
{-# OPTIONS_GHC -Wno-unused-matches #-}
910

1011
module Cardano.DbSync.Default (
1112
insertListBlocks,
1213
) where
1314

14-
import Control.Monad.Logger (LoggingT)
1515
import qualified Data.ByteString.Short as SBS
1616
import qualified Data.Set as Set
1717
import qualified Data.Strict.Maybe as Strict
@@ -50,28 +50,30 @@ insertListBlocks ::
5050
[CardanoBlock] ->
5151
IO (Either SyncNodeError ())
5252
insertListBlocks syncEnv blocks = do
53-
result <- DB.runDbIohkLoggingEither tracer (envDbEnv syncEnv) $ do
54-
runExceptT $ traverse_ (applyAndInsertBlockMaybe syncEnv tracer) blocks
53+
result <-
54+
try $
55+
DB.runDbIohkLogging tracer (envDbEnv syncEnv) $
56+
traverse_ (applyAndInsertBlockMaybe syncEnv tracer) blocks
5557
case result of
56-
Left dbErr -> pure $ Left $ SNErrDatabase dbErr
57-
Right (Left syncErr) -> pure $ Left syncErr
58-
Right (Right _) -> pure $ Right ()
58+
Left (dbErr :: DB.DbError) -> pure $ Left $ SNErrDatabase dbErr
59+
Right val -> pure $ Right val
5960
where
6061
tracer = getTrace syncEnv
6162

6263
applyAndInsertBlockMaybe ::
64+
MonadIO m =>
6365
SyncEnv ->
6466
Trace IO Text ->
6567
CardanoBlock ->
66-
ExceptT SyncNodeError (DB.DbAction (LoggingT IO)) ()
68+
DB.DbAction m ()
6769
applyAndInsertBlockMaybe syncEnv tracer cblk = do
6870
bl <- liftIO $ isConsistent syncEnv
6971
(!applyRes, !tookSnapshot) <- liftIO (mkApplyResult bl)
7072
if bl
7173
then -- In the usual case it will be consistent so we don't need to do any queries. Just insert the block
72-
lift $ insertBlock syncEnv cblk applyRes False tookSnapshot
74+
insertBlock syncEnv cblk applyRes False tookSnapshot
7375
else do
74-
eiBlockInDbAlreadyId <- lift $ DB.queryBlockIdEither (SBS.fromShort . Consensus.getOneEraHash $ blockHash cblk) ""
76+
eiBlockInDbAlreadyId <- DB.queryBlockIdEither (SBS.fromShort . Consensus.getOneEraHash $ blockHash cblk) ""
7577
-- If the block is already in db, do nothing. If not, delete all blocks with greater 'BlockNo' or
7678
-- equal, insert the block and restore consistency between ledger and db.
7779
case eiBlockInDbAlreadyId of
@@ -82,11 +84,11 @@ applyAndInsertBlockMaybe syncEnv tracer cblk = do
8284
, textShow (getHeaderFields cblk)
8385
, ". Time to restore consistency."
8486
]
85-
lift $ rollbackFromBlockNo syncEnv (blockNo cblk)
86-
lift $ insertBlock syncEnv cblk applyRes True tookSnapshot
87+
rollbackFromBlockNo syncEnv (blockNo cblk)
88+
insertBlock syncEnv cblk applyRes True tookSnapshot
8789
liftIO $ setConsistentLevel syncEnv Consistent
8890
Right blockId | Just (adaPots, slotNo, epochNo) <- getAdaPots applyRes -> do
89-
replaced <- lift $ DB.replaceAdaPots blockId $ mkAdaPots blockId slotNo epochNo adaPots
91+
replaced <- DB.replaceAdaPots blockId $ mkAdaPots blockId slotNo epochNo adaPots
9092
if replaced
9193
then liftIO $ logInfo tracer $ "Fixed AdaPots for " <> textShow epochNo
9294
else liftIO $ logInfo tracer $ "Reached " <> textShow epochNo
@@ -114,14 +116,15 @@ applyAndInsertBlockMaybe syncEnv tracer cblk = do
114116
Generic.neEpoch <$> maybeFromStrict (apNewEpoch appRes)
115117

116118
insertBlock ::
119+
MonadIO m =>
117120
SyncEnv ->
118121
CardanoBlock ->
119122
ApplyResult ->
120123
-- is first Block after rollback
121124
Bool ->
122125
-- has snapshot been taken
123126
Bool ->
124-
DB.DbAction (LoggingT IO) ()
127+
DB.DbAction m ()
125128
insertBlock syncEnv cblk applyRes firstAfterRollback tookSnapshot = do
126129
!epochEvents <- liftIO $ atomically $ generateNewEpochEvents syncEnv (apSlotDetails applyRes)
127130
let !applyResult = applyRes {apEvents = sort $ epochEvents <> apEvents applyRes}
@@ -195,7 +198,7 @@ insertBlock syncEnv cblk applyRes firstAfterRollback tookSnapshot = do
195198
Strict.Nothing | hasLedgerState syncEnv -> Just $ Ledger.Prices minBound minBound
196199
Strict.Nothing -> Nothing
197200

198-
commitOrIndexes :: Bool -> Bool -> DB.DbAction (LoggingT IO) ()
201+
commitOrIndexes :: MonadIO m => Bool -> Bool -> DB.DbAction m ()
199202
commitOrIndexes withinTwoMin withinHalfHour = do
200203
commited <-
201204
if withinTwoMin || tookSnapshot
@@ -209,7 +212,7 @@ insertBlock syncEnv cblk applyRes firstAfterRollback tookSnapshot = do
209212
unless ranIndexes $ do
210213
-- We need to commit the transaction as we are going to run indexes migrations
211214
DB.commitCurrentTransaction
212-
liftIO $ runIndexesMigrations syncEnv
215+
liftIO $ runNearTipMigrations syncEnv
213216

214217
blkNo = headerFieldBlockNo $ getHeaderFields cblk
215218

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

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,6 @@ import Cardano.DbSync.Types (
2222
import Cardano.DbSync.Util
2323
import Cardano.Prelude hiding (from, on, replace)
2424
import Cardano.Slotting.Slot (unEpochNo)
25-
import Control.Monad.Logger (LoggingT)
2625
import Ouroboros.Consensus.Byron.Ledger (ByronBlock (..))
2726
import Ouroboros.Consensus.Cardano.Block (HardForkBlock (..))
2827

@@ -33,12 +32,13 @@ import Ouroboros.Consensus.Cardano.Block (HardForkBlock (..))
3332
-- updated on each new block.
3433

3534
epochHandler ::
35+
MonadIO m =>
3636
SyncEnv ->
3737
Trace IO Text ->
3838
CacheStatus ->
3939
Bool ->
4040
BlockDetails ->
41-
DB.DbAction (LoggingT IO) ()
41+
DB.DbAction m ()
4242
epochHandler syncEnv trce cache isNewEpochEvent (BlockDetails cblk details) =
4343
case cblk of
4444
BlockByron bblk ->
@@ -57,7 +57,7 @@ epochHandler syncEnv trce cache isNewEpochEvent (BlockDetails cblk details) =
5757
BlockConway {} -> epochSlotTimecheck
5858
where
5959
-- What we do here is completely independent of Shelley/Allegra/Mary eras.
60-
epochSlotTimecheck :: DB.DbAction (LoggingT IO) ()
60+
epochSlotTimecheck :: MonadIO m => DB.DbAction m ()
6161
epochSlotTimecheck = do
6262
when (sdSlotTime details > sdCurrentTime details)
6363
$ liftIO
@@ -67,12 +67,13 @@ epochHandler syncEnv trce cache isNewEpochEvent (BlockDetails cblk details) =
6767
updateEpochStart syncEnv cache details isNewEpochEvent False
6868

6969
updateEpochStart ::
70+
MonadIO m =>
7071
SyncEnv ->
7172
CacheStatus ->
7273
SlotDetails ->
7374
Bool ->
7475
Bool ->
75-
DB.DbAction (LoggingT IO) ()
76+
DB.DbAction m ()
7677
updateEpochStart syncEnv cache slotDetails isNewEpochEvent isBoundaryBlock = do
7778
mLastMapEpochFromCache <- liftIO $ readLastMapEpochFromCache cache
7879
mEpochBlockDiff <- liftIO $ readEpochBlockDiffFromCache cache
@@ -225,7 +226,7 @@ handleEpochCachingWhenSyncing syncEnv cache newestEpochFromMap epochBlockDiffCac
225226
newEpoch <- DB.queryCalcEpochEntry $ ebdEpochNo currentEpC
226227
writeToMapEpochCache syncEnv cache newEpoch
227228
-- There will always be a EpochBlockDiff at this point in time
228-
(_, _) -> throwError $ DB.DbError (DB.mkDbCallStack "handleEpochCachingWhenSyncing") "No caches available to update cache" Nothing
229+
(_, _) -> liftIO $ throwIO $ DB.DbError (DB.mkDbCallStack "handleEpochCachingWhenSyncing") "No caches available to update cache" Nothing
229230

230231
-----------------------------------------------------------------------------------------------------
231232
-- Helper functions

0 commit comments

Comments
 (0)