From dbc4f2b63b6b3bb5b57e392f01248cfad43b3589 Mon Sep 17 00:00:00 2001 From: Philip O'Toole Date: Tue, 6 Feb 2024 02:56:19 -0500 Subject: [PATCH] Small refactor of Stale Reads check --- CHANGELOG.md | 1 + store/store.go | 17 ++++++++++------- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1da5612f..30607f9c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ### Implementation changes and bug fixes - [PR #1670](https://github.com/rqlite/rqlite/pull/1670): Improve error message when query on remote node fails. - [PR #1671](https://github.com/rqlite/rqlite/pull/1670): Minor optimizations to Unified Request processing. +- [PR #1674](https://github.com/rqlite/rqlite/pull/1674): Small refactor of _Stale Reads_ check. ## 8.19.0 (February 3rd 2024) This release allows you to set a maximum amount of a time a query will run. If the query does not complete within the set time, an error will be returned. diff --git a/store/store.go b/store/store.go index fb2dfbd5..6b9db35c 100644 --- a/store/store.go +++ b/store/store.go @@ -1138,8 +1138,7 @@ func (s *Store) Query(qr *proto.QueryRequest) ([]*proto.QueryRows, error) { return nil, ErrNotLeader } - if s.raft.State() != raft.Leader && qr.Level == proto.QueryRequest_QUERY_REQUEST_LEVEL_NONE && - qr.Freshness > 0 && time.Since(s.raft.LastContact()).Nanoseconds() > qr.Freshness { + if qr.Level == proto.QueryRequest_QUERY_REQUEST_LEVEL_NONE && s.isStaleRead(qr.Freshness) { return nil, ErrStaleRead } @@ -1179,11 +1178,8 @@ func (s *Store) Request(eqr *proto.ExecuteQueryRequest) ([]*proto.ExecuteQueryRe } return resp } - if eqr.Level == proto.QueryRequest_QUERY_REQUEST_LEVEL_NONE { - if !isLeader && eqr.Freshness > 0 && - time.Since(s.raft.LastContact()).Nanoseconds() > eqr.Freshness { - return nil, ErrStaleRead - } + if eqr.Level == proto.QueryRequest_QUERY_REQUEST_LEVEL_NONE && s.isStaleRead(eqr.Freshness) { + return nil, ErrStaleRead } else if eqr.Level == proto.QueryRequest_QUERY_REQUEST_LEVEL_WEAK { if !isLeader { return nil, ErrNotLeader @@ -1806,6 +1802,13 @@ func (s *Store) updateAppliedIndex() chan struct{} { return done } +func (s *Store) isStaleRead(freshness int64) bool { + if freshness == 0 || s.raft.State() == raft.Leader { + return false + } + return time.Since(s.raft.LastContact()).Nanoseconds() > freshness +} + type fsmExecuteResponse struct { results []*proto.ExecuteResult error error