openraft 0.10.2

Advanced Raft consensus
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
use std::fmt;
use std::fmt::Debug;

use display_more::DisplayOptionExt;
use display_more::DisplayResultExt;
use display_more::DisplaySliceExt;

use crate::OptionalSend;
use crate::RaftTypeConfig;
use crate::async_runtime::OneshotSender;
use crate::core::sm;
use crate::engine::CommandKind;
use crate::engine::CommandName;
use crate::engine::replication_progress::TargetProgress;
use crate::errors::InitializeError;
use crate::progress::inflight_id::InflightId;
use crate::raft::AppendResult;
use crate::raft::SnapshotResponse;
use crate::raft::VoteRequest;
use crate::raft::VoteResponse;
use crate::raft::message::TransferLeaderRequest;
use crate::raft_state::IOId;
use crate::raft_state::IOState;
use crate::replication::ReplicationSessionId;
use crate::replication::replicate::Replicate;
use crate::storage::RaftStateMachine;
use crate::type_config::alias::BatchOf;
use crate::type_config::alias::CommittedVoteOf;
use crate::type_config::alias::LogIdOf;
use crate::type_config::alias::OneshotSenderOf;
use crate::type_config::alias::VoteOf;

/// Commands to send to `RaftRuntime` to execute, to update the application state.
pub(crate) enum Command<C, SM = ()>
where
    C: RaftTypeConfig,
    SM: RaftStateMachine<C>,
{
    /// No actual IO is submitted but need to update io progress.
    ///
    /// For example, when Leader-1 appends log Log-2, then Leader-2 appends log Log-2 again,
    /// the second append does not need to submit to the log store,
    /// but it needs to update the IO progress from `Leader-1,Log-2` to `Leader-2,Log-2`.
    UpdateIOProgress {
        /// This command is not submitted to [`RaftLogStorage`],
        /// thus it cannot be queued in the log store.
        /// Therefore, we need to specify the condition to wait for to run it.
        /// Usually the condition is when the previous log is flushed to disk.
        ///
        /// [`RaftLogStorage`]: crate::storage::RaftLogStorage
        when: Option<Condition<C>>,
        io_id: IOId<C>,
    },

    /// Append a `range` of entries.
    AppendEntries {
        /// The vote of the leader that submits the entries to write.
        ///
        /// The leader could be a local leader that appends entries to the local log store
        /// or a remote leader that replicates entries to this follower.
        ///
        /// The leader id is used to generate a monotonic increasing IO id, such as [`LogIOId`].
        /// Where [`LogIOId`] is `(leader_id, log_id)`.
        ///
        /// [`LogIOId`]: crate::raft_state::io_state::io_id::IOId
        committed_vote: CommittedVoteOf<C>,

        entries: BatchOf<C, C::Entry>,
    },

    /// Send `committed` to other nodes as `leader_commit`, the log ID they may apply up to.
    ///
    /// The producer decides the value: with relaxed reads it is bounded by the leader's applied
    /// log ID. See `RaftState::follower_apply_bound()`.
    ReplicateCommitted { committed: Option<LogIdOf<C>> },

    /// Broadcast heartbeat to all other nodes.
    BroadcastHeartbeat {
        session_id: ReplicationSessionId<C>,
        bypass_min_interval: bool,
    },

    /// Save the committed log id `upto` to [`RaftLogStorage`].
    ///
    /// Upon startup, the saved committed log ids will be re-applied to the state machine to restore
    /// the latest state.
    ///
    /// Apply log entries from `already_applied`, exclusive up to `upto`, inclusive.
    ///
    /// To `commit` logs, [`RaftLogStorage::save_committed()`] is called. And then committed logs
    /// will be applied to the state machine by calling [`RaftStateMachine::apply()`].
    ///
    /// And if it is a leader, send the applied result to the client that proposed the entry once
    /// Apply is done.
    ///
    ///
    /// [`RaftLogStorage`]: crate::storage::RaftLogStorage
    /// [`RaftLogStorage::save_committed()`]: crate::storage::RaftLogStorage::save_committed
    /// [`RaftStateMachine::apply()`]: crate::storage::RaftStateMachine::apply
    SaveCommittedAndApply {
        already_applied: Option<LogIdOf<C>>,
        upto: LogIdOf<C>,
    },

    /// Replicate log entries to a target.
    Replicate { target: C::NodeId, req: Replicate<C> },

    /// Tell the replication task of `target` that the leader dropped the log plan it runs, and ask
    /// it to confirm, with `inflight_id`, that it no longer reads the log for that plan.
    ///
    /// The task answers with [`Notification::ReplicateCleared`] once the stream session that runs
    /// the plan has ended and no read for the plan is running or can start. Until then the
    /// progress entry of `target` holds back the [`Command::PurgeLog`] of the logs the plan could
    /// read, see [`Inflight::Clear`], so the task never reads a purged log.
    ///
    /// [`Notification::ReplicateCleared`]: crate::core::notification::Notification::ReplicateCleared
    /// [`Inflight::Clear`]: crate::progress::Inflight::Clear
    ClearReplicate { target: C::NodeId, inflight_id: InflightId },

    /// Replicate snapshot to a target.
    ReplicateSnapshot {
        leader_vote: CommittedVoteOf<C>,
        target: C::NodeId,
        inflight_id: InflightId,
    },

    /// Broadcast transfer Leader message to all other nodes.
    BroadcastTransferLeader { req: TransferLeaderRequest<C> },

    /// Close replication streams and heartbeat streams.
    CloseReplicationStreams,

    /// Fail all pending linearizable reads after losing leadership.
    FailPendingReads,

    /// Bring the replication streams and heartbeat workers in line with `targets`, after the
    /// leader's vote or its membership changed.
    ///
    /// The runtime keeps a heartbeat worker for each target, and a replication stream for each
    /// target that receives logs; it closes those of every other target, such as one that left the
    /// membership. The stream and the worker of a target that stays are reused, unless
    /// `close_old_streams` is set or the target has a new stream id, which the engine gives it when
    /// its node metadata changes: then they are closed and new ones start from the target's
    /// progress.
    RebuildReplicationStreams {
        leader_vote: CommittedVoteOf<C>,

        /// Targets to replicate to.
        targets: Vec<TargetProgress<C>>,

        /// Whether to replace the stream and the worker of every target instead of reusing them.
        ///
        /// The engine sets it when a leader is established, and drops the requests in flight of
        /// every target: the streams of an earlier vote must not serve this one. A membership
        /// change leaves it unset, so the streams of targets that stay keep running.
        close_old_streams: bool,
    },

    /// Save vote to storage
    SaveVote { vote: VoteOf<C> },

    /// Send vote to all other members
    SendVote { vote_req: VoteRequest<C> },

    /// Send a Pre-Vote request to all other members.
    ///
    /// Unlike [`SendVote`](Command::SendVote), this does not persist a vote or bump the term; it
    /// only probes whether a quorum would grant a vote at the hypothetical next term.
    SendPreVote { vote_req: VoteRequest<C> },

    /// Purge log from the beginning to `upto`, inclusive.
    ///
    /// It runs once the snapshot covers `upto`, and once no replication task that RaftCore closed
    /// may still read the log; until then it waits at the front of the queue. See
    /// [`RaftCore::lingering_replications`].
    ///
    /// [`RaftCore::lingering_replications`]: crate::core::RaftCore::lingering_replications
    PurgeLog { upto: LogIdOf<C> },

    /// Delete logs that have conflicted with the leader from a follower/learner after log id
    /// `after`, exclusive.
    TruncateLog { after: Option<LogIdOf<C>> },

    /// A command sent to state machine worker [`sm::worker::Worker`].
    ///
    /// The runtime(`RaftCore`) will just forward this command to [`sm::worker::Worker`].
    ///
    /// The worker reports a completion to `RaftCore` with a [`Notification::StateMachine`]: when it
    /// has applied entries, installed a snapshot, or finished or deferred a snapshot build.
    /// `GetSnapshot` answers its caller directly instead, and what an `ExternalFunc` reports is up
    /// to its callback.
    ///
    /// [`Notification::StateMachine`]: crate::core::notification::Notification::StateMachine
    StateMachine { command: sm::Command<C, SM> },

    /// Send result to caller
    Respond {
        when: Option<Condition<C>>,
        resp: Respond<C>,
    },
}

impl<C, SM> Debug for Command<C, SM>
where
    C: RaftTypeConfig,
    SM: RaftStateMachine<C>,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(self, f)
    }
}

impl<C, SM> fmt::Display for Command<C, SM>
where
    C: RaftTypeConfig,
    SM: RaftStateMachine<C>,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Command::UpdateIOProgress { when, io_id } => {
                write!(f, "UpdateIOProgress: when: {}, io_id: {}", when.display(), io_id)
            }
            Command::AppendEntries {
                committed_vote: vote,
                entries,
            } => {
                write!(
                    f,
                    "AppendEntries: vote: {}, entries: {}",
                    vote,
                    entries.as_ref().display()
                )
            }
            Command::ReplicateCommitted { committed } => {
                write!(f, "ReplicateCommitted: {}", committed.display())
            }
            Command::BroadcastHeartbeat {
                session_id,
                bypass_min_interval,
            } => {
                write!(
                    f,
                    "BroadcastHeartbeat: session_id:{}, bypass_min_interval:{}",
                    session_id, bypass_min_interval
                )
            }
            Command::SaveCommittedAndApply {
                already_applied: already_committed,
                upto,
            } => write!(f, "SaveCommittedAndApply: ({}, {}]", already_committed.display(), upto),
            Command::Replicate { target, req } => {
                write!(f, "Replicate: target={}, req: {}", target, req)
            }
            Command::ClearReplicate { target, inflight_id } => {
                write!(f, "ClearReplicate: target={}, inflight_id: {}", target, inflight_id)
            }
            Command::ReplicateSnapshot {
                leader_vote,
                target,
                inflight_id,
            } => {
                write!(
                    f,
                    "ReplicateSnapshot: leader_vote: {}, target={}, inflight_id: {}",
                    leader_vote, target, inflight_id
                )
            }
            Command::BroadcastTransferLeader { req } => write!(f, "TransferLeader: {}", req),
            Command::CloseReplicationStreams => write!(f, "CloseReplicationStreams"),
            Command::FailPendingReads => write!(f, "FailPendingReads"),
            Command::RebuildReplicationStreams {
                leader_vote,
                targets,
                close_old_streams,
            } => {
                write!(
                    f,
                    "RebuildReplicationStreams: leader_vote: {}, targets: {}; close_old: {}",
                    leader_vote,
                    targets.display_n(10),
                    close_old_streams
                )
            }
            Command::SaveVote { vote } => write!(f, "SaveVote: {}", vote),
            Command::SendVote { vote_req } => write!(f, "SendVote: {}", vote_req),
            Command::SendPreVote { vote_req } => write!(f, "SendPreVote: {}", vote_req),
            Command::PurgeLog { upto } => write!(f, "PurgeLog: upto: {}", upto),
            Command::TruncateLog { after } => write!(f, "TruncateLog: after: {}", after.display()),
            Command::StateMachine { command } => write!(f, "StateMachine: command: {}", command),
            Command::Respond { when, resp } => write!(f, "Respond: when: {}, resp: {}", when.display(), resp),
        }
    }
}

impl<C, SM> From<sm::Command<C, SM>> for Command<C, SM>
where
    C: RaftTypeConfig,
    SM: RaftStateMachine<C>,
{
    fn from(cmd: sm::Command<C, SM>) -> Self {
        Self::StateMachine { command: cmd }
    }
}

/// For unit testing
impl<C, SM> PartialEq for Command<C, SM>
where
    C: RaftTypeConfig,
    SM: RaftStateMachine<C>,
    C::Entry: PartialEq,
    BatchOf<C, C::Entry>: PartialEq,
{
    #[rustfmt::skip]
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Command::UpdateIOProgress { when, io_id },        Command::UpdateIOProgress { when: wb, io_id: ab }, )                  => when == wb && io_id == ab,
            (Command::AppendEntries { committed_vote: vote, entries },    Command::AppendEntries { committed_vote: vb, entries: b }, )               => vote == vb && entries == b,
            (Command::ReplicateCommitted { committed },        Command::ReplicateCommitted { committed: b }, )                       =>  committed == b,
            (Command::BroadcastHeartbeat { session_id, bypass_min_interval },       Command::BroadcastHeartbeat { session_id: sb, bypass_min_interval: ib }, ) => session_id == sb && bypass_min_interval == ib,
            (Command::SaveCommittedAndApply { already_applied: already_committed, upto, },      Command::SaveCommittedAndApply { already_applied: b_committed, upto: b_upto, }, )  => already_committed == b_committed && upto == b_upto,
            (Command::Replicate { target, req },               Command::Replicate { target: b_target, req: other_req, }, )           => target == b_target && req == other_req,
            (Command::ClearReplicate { target, inflight_id },  Command::ClearReplicate { target: b, inflight_id: ib })               => target == b && inflight_id == ib,
            (Command::BroadcastTransferLeader { req },         Command::BroadcastTransferLeader { req: b, }, )                       => req == b,
            (Command::RebuildReplicationStreams { leader_vote, targets, close_old_streams },   Command::RebuildReplicationStreams { leader_vote: lb, targets: b, close_old_streams: cb }, ) => leader_vote == lb && targets == b && close_old_streams == cb,
            (Command::SaveVote { vote },                       Command::SaveVote { vote: b })                                        => vote == b,
            (Command::SendVote { vote_req },                   Command::SendVote { vote_req: b }, )                                  => vote_req == b,
            (Command::SendPreVote { vote_req },                Command::SendPreVote { vote_req: b }, )                               => vote_req == b,
            (Command::PurgeLog { upto },                       Command::PurgeLog { upto: b })                                        => upto == b,
            (Command::TruncateLog { after },                   Command::TruncateLog { after: b }, )                                  => after == b,
            (Command::Respond { when, resp: send },            Command::Respond { when: b_when, resp: b })                           => send == b && when == b_when,
            (Command::StateMachine { command },                Command::StateMachine { command: b })                                 => command == b,
            (Command::CloseReplicationStreams,                 Command::CloseReplicationStreams)                                     => true,
            (Command::FailPendingReads,                        Command::FailPendingReads)                                            => true,
            (Command::ReplicateSnapshot { leader_vote, target, inflight_id }, Command::ReplicateSnapshot { leader_vote: lb, target: tb, inflight_id: ib }) => leader_vote == lb && target == tb && inflight_id == ib,

            // Two different commands are never equal. These arms are spelled out per variant
            // instead of one `_ => false`, so that a newly added variant leaves the match
            // non-exhaustive and fails to compile until it gets a comparison arm above. A
            // catch-all would instead make the new variant silently unequal to itself.
            (Command::UpdateIOProgress { .. },          _) => false,
            (Command::AppendEntries { .. },             _) => false,
            (Command::ReplicateCommitted { .. },        _) => false,
            (Command::BroadcastHeartbeat { .. },        _) => false,
            (Command::SaveCommittedAndApply { .. },     _) => false,
            (Command::Replicate { .. },                 _) => false,
            (Command::ClearReplicate { .. },            _) => false,
            (Command::ReplicateSnapshot { .. },         _) => false,
            (Command::BroadcastTransferLeader { .. },   _) => false,
            (Command::CloseReplicationStreams,          _) => false,
            (Command::FailPendingReads,                 _) => false,
            (Command::RebuildReplicationStreams { .. }, _) => false,
            (Command::SaveVote { .. },                  _) => false,
            (Command::SendVote { .. },                  _) => false,
            (Command::SendPreVote { .. },               _) => false,
            (Command::PurgeLog { .. },                  _) => false,
            (Command::TruncateLog { .. },               _) => false,
            (Command::StateMachine { .. },              _) => false,
            (Command::Respond { .. },                   _) => false,
        }
    }
}

impl<C, SM> Command<C, SM>
where
    C: RaftTypeConfig,
    SM: RaftStateMachine<C>,
{
    #[allow(dead_code)]
    #[rustfmt::skip]
    pub(crate) fn name(&self) -> CommandName {
        match self {
            Command::UpdateIOProgress { .. }          => CommandName::UpdateIOProgress,
            Command::AppendEntries { .. }             => CommandName::AppendEntries,
            Command::ReplicateCommitted { .. }        => CommandName::ReplicateCommitted,
            Command::BroadcastHeartbeat { .. }        => CommandName::BroadcastHeartbeat,
            Command::SaveCommittedAndApply { .. }     => CommandName::SaveCommittedAndApply,
            Command::Replicate { .. }                 => CommandName::Replicate,
            Command::ClearReplicate { .. }            => CommandName::ClearReplicate,
            Command::ReplicateSnapshot { .. }         => CommandName::ReplicateSnapshot,
            Command::BroadcastTransferLeader { .. }   => CommandName::BroadcastTransferLeader,
            Command::CloseReplicationStreams          => CommandName::CloseReplicationStreams,
            Command::FailPendingReads                 => CommandName::FailPendingReads,
            Command::RebuildReplicationStreams { .. } => CommandName::RebuildReplicationStreams,
            Command::SaveVote { .. }                  => CommandName::SaveVote,
            Command::SendVote { .. }                  => CommandName::SendVote,
            Command::SendPreVote { .. }               => CommandName::SendPreVote,
            Command::PurgeLog { .. }                  => CommandName::PurgeLog,
            Command::TruncateLog { .. }               => CommandName::TruncateLog,
            Command::StateMachine { command }          => CommandName::StateMachine(command.name()),
            Command::Respond { .. }                   => CommandName::Respond,
        }
    }

    #[allow(dead_code)]
    #[rustfmt::skip]
    pub(crate) fn kind(&self) -> CommandKind {
        match self {
            Command::CloseReplicationStreams          => CommandKind::Main,
            Command::FailPendingReads                 => CommandKind::Main,
            Command::RebuildReplicationStreams { .. } => CommandKind::Main,
            Command::Respond { .. }                   => CommandKind::Respond,
            // Apply is firstly handled by RaftCore, then forwarded to state machine worker.

            Command::UpdateIOProgress { .. }          => CommandKind::Log,
            Command::AppendEntries { .. }             => CommandKind::Log,
            Command::SaveVote { .. }                  => CommandKind::Log,
            Command::TruncateLog { .. }               => CommandKind::Log,

            Command::PurgeLog { .. }                  => CommandKind::Log,

            Command::ReplicateCommitted { .. }        => CommandKind::Network,
            Command::BroadcastHeartbeat { .. }        => CommandKind::Network,
            Command::Replicate { .. }                 => CommandKind::Network,
            Command::ClearReplicate { .. }            => CommandKind::Network,
            Command::ReplicateSnapshot { .. }         => CommandKind::Network,
            Command::BroadcastTransferLeader { .. }   => CommandKind::Network,
            Command::SendVote { .. }                  => CommandKind::Network,
            Command::SendPreVote { .. }               => CommandKind::Network,

            Command::SaveCommittedAndApply { .. }     => CommandKind::StateMachine,
            Command::StateMachine { .. }              => CommandKind::StateMachine,
        }
    }

    /// Return the condition the command waits for if any.
    #[rustfmt::skip]
    pub(crate) fn condition(&self) -> Option<Condition<C>> {
        match self {
            Command::CloseReplicationStreams          => None,
            Command::FailPendingReads                 => None,
            Command::RebuildReplicationStreams { .. } => None,
            Command::Respond { when, .. }             => when.clone(),

            Command::UpdateIOProgress { when, .. }    => when.clone(),
            Command::AppendEntries { .. }             => None,
            Command::SaveVote { .. }                  => None,
            Command::TruncateLog { .. }               => None,

            Command::PurgeLog { upto }                => Some(Condition::Snapshot { log_id: upto.clone() }),

            Command::ReplicateCommitted { .. }        => None,
            Command::BroadcastHeartbeat { .. }        => None,
            Command::Replicate { .. }                 => None,
            Command::ClearReplicate { .. }            => None,
            Command::ReplicateSnapshot { .. }         => None,
            Command::BroadcastTransferLeader { .. }   => None,
            Command::SendVote { .. }                  => None,
            Command::SendPreVote { .. }               => None,

            Command::SaveCommittedAndApply { .. }                     => None,
            Command::StateMachine { .. }              => None,
        }
    }
}

/// A condition to wait for before executing a command or sending a respond.
#[derive(Debug, Clone)]
#[derive(PartialEq, Eq)]
pub(crate) enum Condition<C>
where C: RaftTypeConfig
{
    /// Wait for log IO to be flushed to storage.
    ///
    /// A log IO is uniquely identified by `(leader_id, log_id)`, not just `log_id`,
    /// since the same log index can be written multiple times by different leaders.
    IOFlushed { io_id: IOId<C> },

    /// Wait for log entry to be flushed to storage (without specific leader).
    #[allow(dead_code)]
    LogFlushed { log_id: LogIdOf<C> },

    /// Wait for log entry to be applied to state machine.
    #[allow(dead_code)]
    Applied { log_id: LogIdOf<C> },

    /// Wait for snapshot to be built that includes this log entry.
    Snapshot { log_id: LogIdOf<C> },
}

impl<C> fmt::Display for Condition<C>
where C: RaftTypeConfig
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Condition::IOFlushed { io_id } => {
                write!(f, "IOFlushed >= {}", io_id)
            }
            Condition::LogFlushed { log_id } => {
                write!(f, "LogFlushed >= {}", log_id)
            }
            Condition::Applied { log_id } => write!(f, "Applied >= {}", log_id),
            Condition::Snapshot { log_id } => write!(f, "Snapshot >= {}", log_id),
        }
    }
}

impl<C> Condition<C>
where C: RaftTypeConfig
{
    /// Check if the condition is satisfied by the current IO state.
    pub(crate) fn is_met(&self, io_state: &IOState<C>) -> bool {
        match self {
            Condition::IOFlushed { io_id } => self.is_satisfied_by(io_id, io_state.log_progress.flushed()),
            Condition::LogFlushed { log_id } => self.is_satisfied_by(
                log_id,
                io_state.log_progress.flushed().and_then(|io_id| io_id.last_log_id()),
            ),
            Condition::Applied { log_id } => self.is_satisfied_by(log_id, io_state.apply_progress.flushed()),
            Condition::Snapshot { log_id } => self.is_satisfied_by(log_id, io_state.snapshot.flushed()),
        }
    }

    /// Check if actual value satisfies the expected threshold.
    fn is_satisfied_by<T>(&self, expected: &T, actual: Option<&T>) -> bool
    where T: PartialOrd + fmt::Display {
        let Some(actual) = actual else {
            tracing::debug!("{} is not met: actual: None", self);
            return false;
        };

        if actual >= expected {
            tracing::debug!("{} is met: actual: {}", self, actual);
            true
        } else {
            tracing::debug!("{} is not met: actual: {}", self, actual);
            false
        }
    }
}

/// A command to send return value to the caller via a `oneshot::Sender`.
#[derive(Debug, PartialEq, Eq)]
#[derive(derive_more::From)]
pub(crate) enum Respond<C>
where C: RaftTypeConfig
{
    Vote(ValueSender<C, VoteResponse<C>>),
    AppendEntries(ValueSender<C, AppendResult<C>>),
    InstallFullSnapshot(ValueSender<C, SnapshotResponse<C>>),
    Initialize(ValueSender<C, Result<(), InitializeError<C>>>),
}

impl<C> fmt::Display for Respond<C>
where C: RaftTypeConfig
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Respond::Vote(vs) => write!(f, "Vote {}", vs.value()),
            Respond::AppendEntries(vs) => match vs.value() {
                Ok(log_id) => write!(f, "AppendEntries Ok({})", log_id.display()),
                Err(e) => write!(f, "AppendEntries Err({})", e),
            },
            Respond::InstallFullSnapshot(vs) => write!(f, "InstallFullSnapshot {}", vs.value()),
            Respond::Initialize(vs) => write!(f, "Initialize {}", vs.value().as_ref().map(|_x| "()").display()),
        }
    }
}

impl<C> Respond<C>
where C: RaftTypeConfig
{
    pub(crate) fn new<T>(res: T, tx: OneshotSenderOf<C, T>) -> Self
    where
        T: Debug + PartialEq + Eq + OptionalSend,
        Self: From<ValueSender<C, T>>,
    {
        Respond::from(ValueSender::new(res, tx))
    }

    pub(crate) fn send(self) {
        match self {
            Respond::Vote(x) => x.send(),
            Respond::AppendEntries(x) => x.send(),
            Respond::InstallFullSnapshot(x) => x.send(),
            Respond::Initialize(x) => x.send(),
        }
    }
}

pub(crate) struct ValueSender<C, T>
where
    T: Debug + PartialEq + Eq + OptionalSend,
    C: RaftTypeConfig,
{
    value: T,
    tx: OneshotSenderOf<C, T>,
}

impl<C, T> Debug for ValueSender<C, T>
where
    T: Debug + PartialEq + Eq + OptionalSend,
    C: RaftTypeConfig,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ValueSender").field("value", &self.value).finish()
    }
}

impl<C, T> PartialEq for ValueSender<C, T>
where
    T: Debug + PartialEq + Eq + OptionalSend,
    C: RaftTypeConfig,
{
    fn eq(&self, other: &Self) -> bool {
        self.value == other.value
    }
}

impl<C, T> Eq for ValueSender<C, T>
where
    T: Debug + PartialEq + Eq + OptionalSend,
    C: RaftTypeConfig,
{
}

impl<C, T> ValueSender<C, T>
where
    T: Debug + PartialEq + Eq + OptionalSend,
    C: RaftTypeConfig,
{
    pub(crate) fn new(res: T, tx: OneshotSenderOf<C, T>) -> Self {
        Self { value: res, tx }
    }

    pub(crate) fn value(&self) -> &T {
        &self.value
    }

    pub(crate) fn send(self) {
        self.tx.send(self.value).ok();
    }
}

#[cfg(test)]
mod tests {
    use crate::engine::Command;
    use crate::engine::testing::UTConfig;
    use crate::engine::testing::log_id;

    /// `TruncateLog` names its boundary `after`: the log at it is kept, and the logs after it are
    /// deleted. `Debug` shows the same text as `Display`.
    #[test]
    fn test_truncate_log_display() {
        let cmd = Command::<UTConfig>::TruncateLog {
            after: Some(log_id(2, 1, 3)),
        };
        assert_eq!("TruncateLog: after: T2-N1.3", cmd.to_string());
        assert_eq!(cmd.to_string(), format!("{:?}", cmd));

        let cmd = Command::<UTConfig>::TruncateLog { after: None };
        assert_eq!("TruncateLog: after: None", cmd.to_string());
        assert_eq!(cmd.to_string(), format!("{:?}", cmd));
    }
}