Skip to content

Commit 2e8246b

Browse files
committed
start working way through test to check conversion correct
1 parent fa2056e commit 2e8246b

Some content is hidden

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

47 files changed

+2871
-1127
lines changed

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

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -207,7 +207,7 @@ startDBSync env = do
207207
Just _a -> error "db-sync already running"
208208
Nothing -> do
209209
let appliedRunDbSync = partialRunDbSync env (dbSyncParams env) (dbSyncConfig env)
210-
-- we async the fully applied runDbSync here ad put it into the thread
210+
-- we async the fully applied runDbSync here and put it into the thread
211211
asyncApplied <- async appliedRunDbSync
212212
void . atomically $ tryPutTMVar (dbSyncThreadVar env) asyncApplied
213213

@@ -225,7 +225,8 @@ getDBSyncPGPass :: DBSyncEnv -> DB.PGPassSource
225225
getDBSyncPGPass = enpPGPassSource . dbSyncParams
226226

227227
queryDBSync :: DBSyncEnv -> DB.DbAction (NoLoggingT IO) a -> IO a
228-
queryDBSync env = DB.runWithConnectionNoLogging (getDBSyncPGPass env)
228+
queryDBSync env = do
229+
DB.runWithConnectionNoLogging (getDBSyncPGPass env)
229230

230231
getPoolLayer :: DBSyncEnv -> IO PoolDataLayer
231232
getPoolLayer env = do
@@ -557,7 +558,7 @@ withFullConfig' WithConfigArgs {..} cmdLineArgs mSyncNodeConfig configFilePath t
557558
then configureLogging syncNodeConfig "db-sync-node"
558559
else pure nullTracer
559560
-- runDbSync is partially applied so we can pass in syncNodeParams at call site / within tests
560-
let partialDbSyncRun params cfg' = runDbSync emptyMetricsSetters migr iom trce params cfg' True
561+
let partialDbSyncRun params cfg' = runDbSync emptyMetricsSetters iom trce params cfg' True
561562
initSt = Consensus.pInfoInitLedger $ protocolInfo cfg
562563

563564
withInterpreter (protocolInfoForging cfg) (protocolInfoForger cfg) nullTracer fingerFile $ \interpreter -> do
@@ -578,6 +579,14 @@ withFullConfig' WithConfigArgs {..} cmdLineArgs mSyncNodeConfig configFilePath t
578579
if null tableNames || shouldDropDB
579580
then void . hSilence [stderr] $ DB.recreateDB pgPass
580581
else void . hSilence [stderr] $ DB.truncateTables pgPass tableNames
582+
583+
-- Run migrations synchronously first
584+
runMigrationsOnly
585+
migr
586+
trce
587+
(syncNodeParams cfg)
588+
syncNodeConfig
589+
581590
action interpreter mockServer dbSyncEnv
582591
where
583592
mutableDir = mkMutableDir testLabelFilePath

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

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@ configRemoveJsonbFromSchemaEnabled :: IOManager -> [(Text, Text)] -> Assertion
2020
configRemoveJsonbFromSchemaEnabled = do
2121
withCustomConfigAndDropDB args (Just configRemoveJsonFromSchema) cfgDir testLabel $ \_interpreter _mockServer dbSync -> do
2222
startDBSync dbSync
23-
threadDelay 7_000_000
2423
assertEqQuery
2524
dbSync
2625
DB.queryJsonbInSchemaExistsTest
@@ -38,7 +37,6 @@ configRemoveJsonbFromSchemaDisabled = do
3837
withCustomConfigAndDropDB args (Just configRemoveJsonFromSchemaFalse) cfgDir testLabel $
3938
\_interpreter _mockServer dbSync -> do
4039
startDBSync dbSync
41-
threadDelay 7_000_000
4240
assertEqQuery
4341
dbSync
4442
DB.queryJsonbInSchemaExistsTest
@@ -54,7 +52,6 @@ configJsonbInSchemaShouldRemoveThenAdd :: IOManager -> [(Text, Text)] -> Asserti
5452
configJsonbInSchemaShouldRemoveThenAdd =
5553
withCustomConfigAndDropDB args (Just configRemoveJsonFromSchema) cfgDir testLabel $ \_interpreter _mockServer dbSyncEnv -> do
5654
startDBSync dbSyncEnv
57-
threadDelay 7_000_000
5855
assertEqQuery
5956
dbSyncEnv
6057
DB.queryJsonbInSchemaExistsTest
@@ -72,7 +69,6 @@ configJsonbInSchemaShouldRemoveThenAdd =
7269
}
7370
}
7471
startDBSync newDbSyncEnv
75-
threadDelay 7_000_000
7672
assertEqQuery
7773
dbSyncEnv
7874
DB.queryJsonbInSchemaExistsTest

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,7 @@ performPruneWithSimpleRollback useTxOutAddress =
106106
atomically $ addBlock mockServer blk0
107107

108108
startDBSync dbSync
109+
109110
atomically $ addBlock mockServer blk1
110111

111112
-- Create some payment transactions

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

Lines changed: 47 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ module Cardano.DbSync (
1717
SocketPath (..),
1818
Db.MigrationDir (..),
1919
runDbSyncNode,
20+
runMigrationsOnly,
2021
runDbSync,
2122
-- For testing and debugging
2223
OffChainFetchError (..),
@@ -67,19 +68,19 @@ runDbSyncNode metricsSetters knownMigrations params syncNodeConfigFromFile =
6768
abortOnPanic <- hasAbortOnPanicEnv
6869
startupReport trce abortOnPanic params
6970

70-
runDbSync metricsSetters knownMigrations iomgr trce params syncNodeConfigFromFile abortOnPanic
71+
-- Run initial migrations synchronously first
72+
runMigrationsOnly knownMigrations trce params syncNodeConfigFromFile
7173

72-
runDbSync ::
73-
MetricSetters ->
74+
runDbSync metricsSetters iomgr trce params syncNodeConfigFromFile abortOnPanic
75+
76+
-- Extract just the initial migration logic (no indexes)
77+
runMigrationsOnly ::
7478
[(Text, Text)] ->
75-
IOManager ->
7679
Trace IO Text ->
7780
SyncNodeParams ->
7881
SyncNodeConfig ->
79-
-- Should abort on panic
80-
Bool ->
8182
IO ()
82-
runDbSync metricsSetters knownMigrations iomgr trce params syncNodeConfigFromFile abortOnPanic = do
83+
runMigrationsOnly knownMigrations trce params syncNodeConfigFromFile = do
8384
logInfo trce $ textShow syncOpts
8485

8586
-- Read the PG connection info
@@ -97,9 +98,11 @@ runDbSync metricsSetters knownMigrations iomgr trce params syncNodeConfigFromFil
9798
msg <- Db.getMaintenancePsqlConf pgConfig
9899
logInfo trce $ "Running database migrations in mode " <> textShow mode
99100
logInfo trce msg
100-
when (mode `elem` [Db.Indexes, Db.Full]) $ logWarning trce indexesMsg
101+
-- No index warning here - runMigrationsOnly never runs indexes
101102
Db.runMigrations pgConfig True dbMigrationDir (Just $ Db.LogFileDir "/tmp") mode (txOutConfigToTableType txOutConfig)
102-
(ranMigrations, unofficial) <- if enpForceIndexes params then runMigration Db.Full else runMigration Db.Initial
103+
104+
-- Always run Initial mode only - never indexes
105+
(ranMigrations, unofficial) <- runMigration Db.Initial
103106
unless (null unofficial) $
104107
logWarning trce $
105108
"Unofficial migration scripts found: "
@@ -109,9 +112,27 @@ runDbSync metricsSetters knownMigrations iomgr trce params syncNodeConfigFromFil
109112
then logInfo trce "All migrations were executed"
110113
else logInfo trce "Some migrations were not executed. They need to run when syncing has started."
111114

112-
if enpForceIndexes params
113-
then logInfo trce "All user indexes were created"
114-
else logInfo trce "New user indexes were not created. They may be created later if necessary."
115+
logInfo trce "New user indexes were not created. They may be created later if necessary."
116+
where
117+
dbMigrationDir :: Db.MigrationDir
118+
dbMigrationDir = enpMigrationDir params
119+
syncOpts = extractSyncOptions params False syncNodeConfigFromFile
120+
txOutConfig = sioTxOut $ dncInsertOptions syncNodeConfigFromFile
121+
122+
runDbSync ::
123+
MetricSetters ->
124+
IOManager ->
125+
Trace IO Text ->
126+
SyncNodeParams ->
127+
SyncNodeConfig ->
128+
-- Should abort on panic
129+
Bool ->
130+
IO ()
131+
runDbSync metricsSetters iomgr trce params syncNodeConfigFromFile abortOnPanic = do
132+
logInfo trce $ textShow syncOpts
133+
134+
-- Read the PG connection info
135+
pgConfig <- runOrThrowIO (Db.readPGPass $ enpPGPassSource params)
115136

116137
dbConnectionSetting <- case Db.toConnectionSetting pgConfig of
117138
Left err -> do
@@ -123,20 +144,30 @@ runDbSync metricsSetters knownMigrations iomgr trce params syncNodeConfigFromFil
123144
-- For testing and debugging.
124145
whenJust (enpMaybeRollback params) $ \slotNo ->
125146
void $ unsafeRollback trce (txOutConfigToTableType txOutConfig) pgConfig slotNo
147+
148+
-- This runMigration is ONLY for delayed migrations during sync (like indexes)
149+
let runDelayedMigration mode = do
150+
msg <- Db.getMaintenancePsqlConf pgConfig
151+
logInfo trce $ "Running database migrations in mode " <> textShow mode
152+
logInfo trce msg
153+
when (mode `elem` [Db.Indexes, Db.Full]) $ logWarning trce indexesMsg
154+
Db.runMigrations pgConfig True dbMigrationDir (Just $ Db.LogFileDir "/tmp") mode (txOutConfigToTableType txOutConfig)
155+
126156
runSyncNode
127157
metricsSetters
128158
trce
129159
iomgr
130160
dbConnectionSetting
131-
(void . runMigration)
161+
(void . runDelayedMigration)
132162
syncNodeConfigFromFile
133163
params
134164
syncOpts
135165
where
136166
dbMigrationDir :: Db.MigrationDir
137167
dbMigrationDir = enpMigrationDir params
168+
syncOpts = extractSyncOptions params abortOnPanic syncNodeConfigFromFile
169+
txOutConfig = sioTxOut $ dncInsertOptions syncNodeConfigFromFile
138170

139-
indexesMsg :: Text
140171
indexesMsg =
141172
mconcat
142173
[ "Creating Indexes. This may require an extended period of time to perform."
@@ -146,10 +177,6 @@ runDbSync metricsSetters knownMigrations iomgr trce params syncNodeConfigFromFil
146177
, " in the schema directory and restart it."
147178
]
148179

149-
syncOpts = extractSyncOptions params abortOnPanic syncNodeConfigFromFile
150-
151-
txOutConfig = sioTxOut $ dncInsertOptions syncNodeConfigFromFile
152-
153180
runSyncNode ::
154181
MetricSetters ->
155182
Trace IO Text ->
@@ -162,7 +189,7 @@ runSyncNode ::
162189
SyncNodeParams ->
163190
SyncOptions ->
164191
IO ()
165-
runSyncNode metricsSetters trce iomgr dbConnSetting runMigrationFnc syncNodeConfigFromFile syncNodeParams syncOptions = do
192+
runSyncNode metricsSetters trce iomgr dbConnSetting runDelayedMigrationFnc syncNodeConfigFromFile syncNodeParams syncOptions = do
166193
whenJust maybeLedgerDir $
167194
\enpLedgerStateDir -> do
168195
createDirectoryIfMissing True (unLedgerStateDir enpLedgerStateDir)
@@ -190,12 +217,11 @@ runSyncNode metricsSetters trce iomgr dbConnSetting runMigrationFnc syncNodeConf
190217
mkSyncEnvFromConfig
191218
trce
192219
dbEnv
193-
-- dbConnString
194220
syncOptions
195221
genCfg
196222
syncNodeConfigFromFile
197223
syncNodeParams
198-
runMigrationFnc
224+
runDelayedMigrationFnc
199225

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

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

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -315,7 +315,7 @@ mkSyncEnvFromConfig ::
315315
-- | run migration function
316316
RunMigration ->
317317
IO (Either SyncNodeError SyncEnv)
318-
mkSyncEnvFromConfig trce dbEnv syncOptions genCfg syncNodeConfigFromFile syncNodeParams runMigrationFnc =
318+
mkSyncEnvFromConfig trce dbEnv syncOptions genCfg syncNodeConfigFromFile syncNodeParams runDelayedMigrationFnc =
319319
case genCfg of
320320
GenesisCardano _ bCfg sCfg _ _
321321
| unProtocolMagicId (Byron.configProtocolMagicId bCfg) /= Shelley.sgNetworkMagic (scConfig sCfg) ->
@@ -350,7 +350,7 @@ mkSyncEnvFromConfig trce dbEnv syncOptions genCfg syncNodeConfigFromFile syncNod
350350
(SystemStart . Byron.gdStartTime $ Byron.configGenesisData bCfg)
351351
syncNodeConfigFromFile
352352
syncNodeParams
353-
runMigrationFnc
353+
runDelayedMigrationFnc
354354

355355
mkSyncEnv ::
356356
Trace IO Text ->
@@ -364,7 +364,7 @@ mkSyncEnv ::
364364
SyncNodeParams ->
365365
RunMigration ->
366366
IO SyncEnv
367-
mkSyncEnv trce dbEnv syncOptions protoInfo nw nwMagic systemStart syncNodeConfigFromFile syncNP runMigrationFnc = do
367+
mkSyncEnv trce dbEnv syncOptions protoInfo nw nwMagic systemStart syncNodeConfigFromFile syncNP runDelayedMigrationFnc = do
368368
dbCNamesVar <- newTVarIO =<< DB.runDbActionIO dbEnv DB.queryRewardAndEpochStakeConstraints
369369
cache <-
370370
if soptCache syncOptions
@@ -426,7 +426,7 @@ mkSyncEnv trce dbEnv syncOptions protoInfo nw nwMagic systemStart syncNodeConfig
426426
, envOffChainVoteResultQueue = oarq
427427
, envOffChainVoteWorkQueue = oawq
428428
, envOptions = syncOptions
429-
, envRunDelayedMigration = runMigrationFnc
429+
, envRunDelayedMigration = runDelayedMigrationFnc
430430
, envSyncNodeConfig = syncNodeConfigFromFile
431431
, envSystemStart = systemStart
432432
}

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

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ module Cardano.DbSync.Cache (
2020
insertAddressUsingCache,
2121
insertStakeAddress,
2222
queryStakeAddrWithCache,
23+
queryTxIdWithCacheEither,
2324
queryTxIdWithCache,
2425
rollbackCache,
2526
optimiseCaches,
@@ -224,7 +225,7 @@ queryPoolKeyWithCache cache cacheUA hsh =
224225
NoCache -> do
225226
mPhId <- DB.queryPoolHashId (Generic.unKeyHashRaw hsh)
226227
case mPhId of
227-
Nothing -> pure $ Left $ DB.DbError DB.mkCallSite "queryPoolKeyWithCache: NoCache queryPoolHashId" Nothing
228+
Nothing -> pure $ Left $ DB.DbError (DB.mkDbCallStack "queryPoolKeyWithCache") "NoCache queryPoolHashId" Nothing
228229
Just phId -> pure $ Right phId
229230
ActiveCache ci -> do
230231
mp <- liftIO $ readTVarIO (cPools ci)
@@ -242,7 +243,7 @@ queryPoolKeyWithCache cache cacheUA hsh =
242243
liftIO $ missPools (cStats ci)
243244
mPhId <- DB.queryPoolHashId (Generic.unKeyHashRaw hsh)
244245
case mPhId of
245-
Nothing -> throwError $ DB.DbError DB.mkCallSite "queryPoolKeyWithCache: ActiveCache queryPoolHashId" Nothing
246+
Nothing -> throwError $ DB.DbError (DB.mkDbCallStack "queryPoolKeyWithCache") "ActiveCache queryPoolHashId" Nothing
246247
Just phId -> do
247248
-- missed so we can't evict even with 'EvictAndReturn'
248249
when (shouldCache cacheUA) $
@@ -407,6 +408,16 @@ queryMAWithCache cache policyId asset =
407408
let !assetNameBs = Generic.unAssetName asset
408409
maybe (Left (policyBs, assetNameBs)) Right <$> DB.queryMultiAssetId policyBs assetNameBs
409410

411+
queryTxIdWithCacheEither ::
412+
MonadIO m =>
413+
CacheStatus ->
414+
Ledger.TxId StandardCrypto ->
415+
DB.DbAction m (Either DB.DbError DB.TxId)
416+
queryTxIdWithCacheEither cache txIdLedger = do
417+
catchError
418+
(Right <$> queryTxIdWithCache cache txIdLedger)
419+
(pure . Left)
420+
410421
queryPrevBlockWithCache ::
411422
MonadIO m =>
412423
CacheStatus ->

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

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ writeEpochBlockDiffToCache ::
6969
DB.DbAction m ()
7070
writeEpochBlockDiffToCache cache epCurrent =
7171
case cache of
72-
NoCache -> throwError $ DB.DbError DB.mkCallSite "writeEpochBlockDiffToCache: Cache is NoCache" Nothing
72+
NoCache -> throwError $ DB.DbError (DB.mkDbCallStack "writeEpochBlockDiffToCache") "Cache is NoCache" Nothing
7373
ActiveCache ci -> do
7474
cE <- liftIO $ readTVarIO (cEpoch ci)
7575
case (ceMapEpoch cE, ceEpochBlockDiff cE) of
@@ -91,12 +91,12 @@ writeToMapEpochCache syncEnv cache latestEpoch = do
9191
HasLedger hle -> getSecurityParameter $ leProtocolInfo hle
9292
NoLedger nle -> getSecurityParameter $ nleProtocolInfo nle
9393
case cache of
94-
NoCache -> throwError $ DB.DbError DB.mkCallSite "writeToMapEpochCache: Cache is NoCache" Nothing
94+
NoCache -> throwError $ DB.DbError (DB.mkDbCallStack "writeToMapEpochCache") "Cache is NoCache" Nothing
9595
ActiveCache ci -> do
9696
-- get EpochBlockDiff so we can use the BlockId we stored when inserting blocks
9797
epochInternalCE <- readEpochBlockDiffFromCache cache
9898
case epochInternalCE of
99-
Nothing -> throwError $ DB.DbError DB.mkCallSite "writeToMapEpochCache: No epochInternalEpochCache" Nothing
99+
Nothing -> throwError $ DB.DbError (DB.mkDbCallStack "writeToMapEpochCache") "No epochInternalEpochCache" Nothing
100100
Just ei -> do
101101
cE <- liftIO $ readTVarIO (cEpoch ci)
102102
let currentBlockId = ebdBlockId ei

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,7 @@ textShowStats (ActiveCache ic) = do
144144
address <- readTVarIO (cAddress ic)
145145
pure $
146146
mconcat
147-
[ "\nCache Statistics:"
147+
[ "\n----------------------- Cache Statistics: -----------------------"
148148
, "\n Caches Optimised: " <> textShow isCacheOptimised
149149
, textCacheSection "Stake Addresses" (scLruCache stakeHashRaws) (scStableCache stakeHashRaws) (credsHits stats) (credsQueries stats)
150150
, textMapSection "Pools" pools (poolsHits stats) (poolsQueries stats)

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

Lines changed: 2 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,8 @@ runDbThread syncEnv metricsSetters queue = do
6767
-- Process a list of actions
6868
processActions :: [DbEvent] -> IO ()
6969
processActions actions = do
70-
result <- runExceptT $ runActions syncEnv actions -- runActions is where we start inserting information we recieve from the node.
70+
-- runActions is where we start inserting information we recieve from the node.
71+
result <- runExceptT $ runActions syncEnv actions
7172

7273
-- Update metrics with the latest block information
7374
updateBlockMetrics
@@ -96,46 +97,6 @@ runDbThread syncEnv metricsSetters queue = do
9697
setDbBlockHeight metricsSetters $ bBlockNo block
9798
setDbSlotHeight metricsSetters $ bSlotNo block
9899

99-
-- runDbThread ::
100-
-- SyncEnv ->
101-
-- MetricSetters ->
102-
-- ThreadChannels ->
103-
-- IO ()
104-
-- runDbThread syncEnv metricsSetters queue = do
105-
-- logInfo trce "Running DB thread"
106-
-- logException trce "runDBThread: " loop
107-
-- logInfo trce "Shutting down DB thread"
108-
-- where
109-
-- trce = getTrace syncEnv
110-
-- loop = do
111-
-- xs <- blockingFlushDbEventQueue queue
112-
113-
-- when (length xs > 1) $ do
114-
-- logDebug trce $ "runDbThread: " <> textShow (length xs) <> " blocks"
115-
116-
-- case hasRestart xs of
117-
-- Nothing -> do
118-
-- eNextState <- runExceptT $ runActions syncEnv xs
119-
120-
-- mBlock <- getDbLatestBlockInfo (envDbEnv syncEnv)
121-
-- whenJust mBlock $ \block -> do
122-
-- setDbBlockHeight metricsSetters $ bBlockNo block
123-
-- setDbSlotHeight metricsSetters $ bSlotNo block
124-
125-
-- case eNextState of
126-
-- Left err -> logError trce $ show err
127-
-- Right Continue -> loop
128-
-- Right Done -> pure ()
129-
-- Just resultVar -> do
130-
-- -- In this case the syncing thread has restarted, so ignore all blocks that are not
131-
-- -- inserted yet.
132-
-- logInfo trce "Chain Sync client thread has restarted"
133-
-- latestPoints <- getLatestPoints syncEnv
134-
-- currentTip <- getCurrentTipBlockNo syncEnv
135-
-- logDbState syncEnv
136-
-- atomically $ putTMVar resultVar (latestPoints, currentTip)
137-
-- loop
138-
139100
-- | Run the list of 'DbEvent's. Block are applied in a single set (as a transaction)
140101
-- and other operations are applied one-by-one.
141102
runActions ::

0 commit comments

Comments
 (0)