From 014b3cde09335d29ff78a43dde4d26d443e4553d Mon Sep 17 00:00:00 2001 From: Artem Poltorzhitskiy Date: Tue, 17 Dec 2024 18:38:48 +0100 Subject: [PATCH] Fix: division by zero in stats (#324) --- internal/storage/postgres/stats.go | 8 ++++---- internal/storage/postgres/stats_test.go | 12 ++++++++++++ 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/internal/storage/postgres/stats.go b/internal/storage/postgres/stats.go index eb1bd901..0828a01b 100644 --- a/internal/storage/postgres/stats.go +++ b/internal/storage/postgres/stats.go @@ -121,10 +121,10 @@ func (s Stats) Change24hBlockStats(ctx context.Context) (response storage.Change With("s", second). TableExpr("f, s"). ColumnExpr(` - (f.tx_count - s.tx_count)/s.tx_count as tx_count_24h, - (f.bytes_in_block - s.bytes_in_block)/s.bytes_in_block as bytes_in_block_24h, - (f.blobs_size - s.blobs_size)/s.blobs_size as blobs_size_24h, - (f.fee - s.fee)/s.fee as fee_24h + case when s.tx_count > 0 then (f.tx_count - s.tx_count)/s.tx_count when f.tx_count > 0 then 1 else 0 end as tx_count_24h, + case when s.bytes_in_block > 0 then (f.bytes_in_block - s.bytes_in_block)/s.bytes_in_block when f.bytes_in_block > 0 then 1 else 0 end as bytes_in_block_24h, + case when s.blobs_size > 0 then (f.blobs_size - s.blobs_size)/s.blobs_size when f.blobs_size > 0 then 1 else 0 end as blobs_size_24h, + case when s.fee > 0 then (f.fee - s.fee)/s.fee when f.fee > 0 then 1 else 0 end as fee_24h `). Scan(ctx, &response) return diff --git a/internal/storage/postgres/stats_test.go b/internal/storage/postgres/stats_test.go index 6b3b79c9..7281a4fb 100644 --- a/internal/storage/postgres/stats_test.go +++ b/internal/storage/postgres/stats_test.go @@ -305,6 +305,18 @@ func (s *StatsTestSuite) TestMessagesCount24h() { s.Require().Len(items, 0) } +func (s *StatsTestSuite) TestChange24hBlockStats() { + ctx, ctxCancel := context.WithTimeout(context.Background(), 5*time.Second) + defer ctxCancel() + + stats, err := s.storage.Stats.Change24hBlockStats(ctx) + s.Require().NoError(err) + s.Require().Equal(stats.BlobsSize, 0.0) + s.Require().Equal(stats.BytesInBlock, 0.0) + s.Require().Equal(stats.Fee, 0.0) + s.Require().Equal(stats.TxCount, 0.0) +} + func TestSuiteStats_Run(t *testing.T) { suite.Run(t, new(StatsTestSuite)) }