diff --git a/db/db.go b/db/db.go index 9ca297c989..2217eb7f8c 100644 --- a/db/db.go +++ b/db/db.go @@ -989,6 +989,8 @@ func SaveValidators(epoch uint64, validators []*types.Validator, client rpc.Clie return fmt.Errorf("error preparing insert validator statement: %w", err) } + validatorStatusCounts := make(map[string]int) + updates := 0 for _, v := range validators { @@ -1031,6 +1033,7 @@ func SaveValidators(epoch uint64, validators []*types.Validator, client rpc.Clie if err != nil { logger.Errorf("error saving new validator %v: %v", v.Index, err) } + validatorStatusCounts[v.Status]++ } else { // status = // CASE @@ -1071,6 +1074,7 @@ func SaveValidators(epoch uint64, validators []*types.Validator, client rpc.Clie v.Status = "active_online" } + validatorStatusCounts[v.Status]++ if c.Status != v.Status { logger.Tracef("Status changed for validator %v from %v to %v", v.Index, c.Status, v.Status) // logger.Tracef("v.ActivationEpoch %v, latestEpoch %v, lastAttestationSlots[v.Index] %v, thresholdSlot %v", v.ActivationEpoch, latestEpoch, lastAttestationSlots[v.Index], thresholdSlot) @@ -1199,6 +1203,20 @@ func SaveValidators(epoch uint64, validators []*types.Validator, client rpc.Clie logger.Infof("updating validator activation epoch balance completed, took %v", time.Since(s)) + logger.Infof("updating validator status counts") + s = time.Now() + _, err = tx.Exec("TRUNCATE TABLE validators_status_counts;") + if err != nil { + return fmt.Errorf("error truncating validators_status_counts table: %w", err) + } + for status, count := range validatorStatusCounts { + _, err = tx.Exec("INSERT INTO validators_status_counts (status, validator_count) VALUES ($1, $2);", status, count) + if err != nil { + return fmt.Errorf("error updating validator status counts: %w", err) + } + } + logger.Infof("updating validator status counts completed, took %v", time.Since(s)) + s = time.Now() _, err = tx.Exec("ANALYZE (SKIP_LOCKED) validators;") if err != nil { diff --git a/db/migrations/20241003062452_validator_status_counts.sql b/db/migrations/20241003062452_validator_status_counts.sql new file mode 100644 index 0000000000..dbb6d2ebc3 --- /dev/null +++ b/db/migrations/20241003062452_validator_status_counts.sql @@ -0,0 +1,11 @@ +-- +goose Up +-- +goose StatementBegin +SELECT 'up SQL query'; +CREATE TABLE IF NOT EXISTS validators_status_counts (status varchar(20) primary key, validator_count int not null); +-- +goose StatementEnd + +-- +goose Down +-- +goose StatementBegin +SELECT 'down SQL query'; +DROP TABLE IF EXISTS validators_status_counts; +-- +goose StatementEnd