Skip to content

Commit 2a89ecb

Browse files
committed
logstore: factor out HardState writing
Epic: none Release note: none
1 parent f12bac3 commit 2a89ecb

File tree

1 file changed

+23
-13
lines changed

1 file changed

+23
-13
lines changed

pkg/kv/kvserver/logstore/logstore.go

Lines changed: 23 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -205,20 +205,10 @@ func (s *LogStore) storeEntriesAndCommitBatch(
205205
stats.End = crtime.NowMono()
206206
}
207207

208-
if hs := m.HardState; !raft.IsEmptyHardState(hs) {
209-
// NB: Note that without additional safeguards, it's incorrect to write
210-
// the HardState before appending m.Entries. When catching up, a follower
211-
// will receive Entries that are immediately Committed in the same
212-
// Ready. If we persist the HardState but happen to lose the Entries,
213-
// assertions can be tripped.
214-
//
215-
// We have both in the same batch, so there's no problem. If that ever
216-
// changes, we must write and sync the Entries before the HardState.
217-
if err := s.StateLoader.SetHardState(ctx, batch, hs); err != nil {
218-
const expl = "during setHardState"
219-
return RaftState{}, errors.Wrap(err, expl)
220-
}
208+
if err := storeHardState(ctx, batch, s.StateLoader, m.HardState); err != nil {
209+
return RaftState{}, err
221210
}
211+
222212
// Synchronously commit the batch with the Raft log entries and Raft hard
223213
// state as we're promising not to lose this data.
224214
//
@@ -376,6 +366,26 @@ var logAppendPool = sync.Pool{
376366
},
377367
}
378368

369+
func storeHardState(
370+
ctx context.Context, w storage.Writer, sl StateLoader, hs raftpb.HardState,
371+
) error {
372+
if raft.IsEmptyHardState(hs) {
373+
return nil
374+
}
375+
// NB: Note that without additional safeguards, it's incorrect to write the
376+
// HardState before appending m.Entries. When catching up, a follower will
377+
// receive Entries that are immediately Committed in the same Ready. If we
378+
// persist the HardState but happen to lose the Entries, assertions can be
379+
// tripped.
380+
//
381+
// We have both in the same batch, so there's no problem. If that ever
382+
// changes, we must write and sync the Entries before the HardState.
383+
if err := sl.SetHardState(ctx, w, hs); err != nil {
384+
return errors.Wrap(err, "during SetHardState")
385+
}
386+
return nil
387+
}
388+
379389
// logAppend adds the given entries to the raft log. Takes the previous log
380390
// state, and returns the updated state. It's the caller's responsibility to
381391
// maintain exclusive access to the raft log for the duration of the method

0 commit comments

Comments
 (0)