common_meta/election/object_store/
head.rs1use serde::{Deserialize, Deserializer, Serialize};
16use snafu::{OptionExt, ResultExt};
17use uuid::Uuid;
18
19use crate::error::{self, Result};
20
21pub const HEAD_FORMAT_VERSION: u32 = 1;
23
24#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
26pub struct NodeIdentity {
27 pub addr: String,
28 pub incarnation_id: Uuid,
29}
30
31impl NodeIdentity {
32 pub fn new(addr: String) -> Self {
34 Self {
35 addr,
36 incarnation_id: Uuid::new_v4(),
37 }
38 }
39}
40
41#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
43pub struct AuthorityHead {
44 pub format_version: u32,
45 #[serde(deserialize_with = "required_owner")]
48 pub owner: Option<NodeIdentity>,
49 epoch: u64,
50 pub lease_deadline_ms: u64,
51 write_seq: u64,
52}
53
54fn required_owner<'de, D: Deserializer<'de>>(
55 deserializer: D,
56) -> std::result::Result<Option<NodeIdentity>, D::Error> {
57 Option::deserialize(deserializer)
58}
59
60impl AuthorityHead {
61 pub fn initial() -> Self {
63 Self {
64 format_version: HEAD_FORMAT_VERSION,
65 owner: None,
66 epoch: 0,
67 lease_deadline_ms: 0,
68 write_seq: 0,
69 }
70 }
71
72 pub fn encode(&self) -> Result<Vec<u8>> {
74 self.validate()?;
75 serde_json::to_vec(self).context(error::AuthorityFormatSnafu {
76 operation: "encode",
77 })
78 }
79
80 pub fn decode(bytes: &[u8]) -> Result<Self> {
82 let head: Self = serde_json::from_slice(bytes).context(error::AuthorityFormatSnafu {
83 operation: "decode",
84 })?;
85 head.validate()?;
86 Ok(head)
87 }
88
89 fn validate(&self) -> Result<()> {
90 if self.format_version != HEAD_FORMAT_VERSION {
91 return error::AuthorityVersionSnafu {
92 version: self.format_version,
93 }
94 .fail();
95 }
96 Ok(())
97 }
98
99 pub fn epoch(&self) -> u64 {
101 self.epoch
102 }
103
104 pub fn write_seq(&self) -> u64 {
106 self.write_seq
107 }
108
109 pub fn with_next_epoch(mut self) -> Result<Self> {
111 self.epoch = self
112 .epoch
113 .checked_add(1)
114 .context(error::AuthorityOverflowSnafu { counter: "epoch" })?;
115 Ok(self)
116 }
117
118 pub fn with_next_write_seq(mut self) -> Result<Self> {
120 self.write_seq = self
121 .write_seq
122 .checked_add(1)
123 .context(error::AuthorityOverflowSnafu {
124 counter: "write_seq",
125 })?;
126 Ok(self)
127 }
128}