From bb7fdfd8edfe436c90b2765a38072b7553b4abec Mon Sep 17 00:00:00 2001 From: Jesse Lee Date: Thu, 2 Nov 2023 17:19:54 -0400 Subject: [PATCH] implement cap blocks --- cmd/monitor/monitor.go | 32 ++++++++++++++++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/cmd/monitor/monitor.go b/cmd/monitor/monitor.go index 621ca437e..53defddfc 100644 --- a/cmd/monitor/monitor.go +++ b/cmd/monitor/monitor.go @@ -419,17 +419,45 @@ func updateAllBlocks(ms *monitorStatus) []rpctypes.PolyBlock { // default blocks := make([]rpctypes.PolyBlock, 0) - ms.BlocksLock.RLock() + ms.BlocksLock.Lock() + defer ms.BlocksLock.Unlock() + + // ensure the cap is maintained each time you read out the blocks. + capBlocks(ms) for _, b := range ms.Blocks { blocks = append(blocks, b) } - ms.BlocksLock.RUnlock() + // ms.BlocksLock.RUnlock() allBlocks := metrics.SortableBlocks(blocks) return allBlocks } +// Define a maximum number of blocks to keep in memory +const maxBlocksInMemory = 1000 + +// Function to manage the capping of blocks +func capBlocks(ms *monitorStatus) { + ms.BlocksLock.Lock() + defer ms.BlocksLock.Unlock() + + currentBlockCount := len(ms.Blocks) + if currentBlockCount > maxBlocksInMemory { + // Delete blocks that exceed the maxBlocksInMemory + // Assuming blocks are sorted by some identifier (e.g., block height) + // Here you'd need to figure out the correct logic to remove the oldest blocks + // depending on how your ms.Blocks is structured. + for key, _ := range ms.Blocks { + if currentBlockCount <= maxBlocksInMemory { + break + } + delete(ms.Blocks, key) + currentBlockCount-- + } + } +} + func renderMonitorUI(ctx context.Context, ec *ethclient.Client, ms *monitorStatus, rpc *ethrpc.Client) error { if err := ui.Init(); err != nil { return err