Propose a new entry (leader only). Returns the log index.
(&mut self, data: Vec<u8>)
| 239 | |
| 240 | /// Propose a new entry (leader only). Returns the log index. |
| 241 | pub fn propose(&mut self, data: Vec<u8>) -> Result<u64> { |
| 242 | if self.role != NodeRole::Leader { |
| 243 | return Err(RaftError::NotLeader { |
| 244 | leader_hint: if self.leader_id != 0 { |
| 245 | Some(self.leader_id) |
| 246 | } else { |
| 247 | None |
| 248 | }, |
| 249 | }); |
| 250 | } |
| 251 | |
| 252 | let index = self.log.last_index() + 1; |
| 253 | let entry = LogEntry { |
| 254 | term: self.hard_state.current_term, |
| 255 | index, |
| 256 | data, |
| 257 | }; |
| 258 | |
| 259 | self.log.append(entry)?; |
| 260 | self.replicate_to_all(); |
| 261 | |
| 262 | // Single-voter cluster: commit immediately. Learners do not count. |
| 263 | if self.config.cluster_size() == 1 { |
| 264 | self.volatile.commit_index = index; |
| 265 | self.collect_committed_entries(); |
| 266 | } |
| 267 | |
| 268 | Ok(index) |
| 269 | } |
| 270 | } |
| 271 | |
| 272 | #[cfg(test)] |