Skip to main content

common_meta/election/object_store/
head.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use serde::{Deserialize, Deserializer, Serialize};
16use snafu::{OptionExt, ResultExt};
17use uuid::Uuid;
18
19use crate::error::{self, Result};
20
21/// Persisted Authority Head format supported by this reader and writer.
22pub const HEAD_FORMAT_VERSION: u32 = 1;
23
24/// A process identity, generated once at startup and retained by the caller.
25#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
26pub struct NodeIdentity {
27    pub addr: String,
28    pub incarnation_id: Uuid,
29}
30
31impl NodeIdentity {
32    /// Creates a fresh process incarnation, even when the address is reused.
33    pub fn new(addr: String) -> Self {
34        Self {
35            addr,
36            incarnation_id: Uuid::new_v4(),
37        }
38    }
39}
40
41/// Version-one persisted authority payload. Lease deadline is diagnostic only.
42#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
43pub struct AuthorityHead {
44    pub format_version: u32,
45    // Serde normally treats a missing Option as None. The design requires owner to
46    // be present while still allowing its value to be null.
47    #[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    /// Empty Head for explicit initialization of a new namespace.
62    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    /// Validates the format and encodes compact deterministic JSON.
73    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    /// Decodes required fields and rejects unknown protocol versions.
81    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    /// Returns the logical epoch in this payload.
100    pub fn epoch(&self) -> u64 {
101        self.epoch
102    }
103
104    /// Returns the write sequence in this payload.
105    pub fn write_seq(&self) -> u64 {
106        self.write_seq
107    }
108
109    /// Returns a payload with its epoch advanced, rejecting overflow before mutation.
110    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    /// Returns a payload with its write sequence advanced, rejecting overflow.
119    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}