Skip to main content

common_wal/config/
object_store.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 std::time::Duration;
16
17use common_base::readable_size::ReadableSize;
18use serde::{Deserialize, Serialize};
19
20/// Fixed directory generation used by standalone and distributed WAL stores.
21///
22/// The directory remains stable across process restarts. This is distinct from
23/// both the heartbeat node epoch and the store epoch carried in object headers.
24pub const FIXED_DIRECTORY_GENERATION: u64 = 0;
25
26/// Plugin marker allowing metasrv and its datanodes to use object-store WAL.
27///
28/// OSS does not register this marker. Cluster integration registers it only after
29/// the distributed WAL prerequisites, including handoff and takeover, are available.
30/// It does not itself configure storage or implement region failover.
31#[derive(Debug, Clone, Copy)]
32pub struct EnableObjectStoreWal;
33
34/// When an append to the object store WAL returns.
35#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
36#[serde(rename_all = "snake_case")]
37pub enum AckMode {
38    /// An append returns after the object holding its entries is durable.
39    #[default]
40    Durable,
41    /// An append returns once its entries are admitted and their ids are
42    /// assigned; the object is created in the background.
43    Enqueued,
44}
45
46/// What a read does with a segment that still does not decode after a
47/// second fetch, because its checksum does not match or its content
48/// disagrees with its footer entry.
49#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
50#[serde(rename_all = "snake_case")]
51pub enum CorruptedSegmentAction {
52    /// The segment is skipped and recorded as a hole of its region; the other
53    /// regions of the object are unaffected.
54    #[default]
55    Skip,
56    /// The read fails.
57    Fail,
58}
59
60/// Object store wal configurations for datanode.
61#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
62#[serde(default)]
63pub struct ObjectStoreWalConfig {
64    /// Name of the storage provider that holds the WAL objects.
65    /// An empty name selects the default object store.
66    pub storage_provider: String,
67    /// Path prefix of the WAL objects inside the storage provider.
68    /// In distributed mode, metasrv and all datanodes must use the same public
69    /// root prefix and shared object storage. A mismatched prefix prevents regions
70    /// from opening.
71    ///
72    /// The store runs under a node prefix derived from it, see
73    /// [`node_prefix`](Self::node_prefix).
74    pub prefix: String,
75    /// Interval of flushing buffered entries to the object store, at least
76    /// 10ms, defaults to 100ms.
77    #[serde(with = "humantime_serde")]
78    pub flush_interval: Duration,
79    /// The max size of a single batch object, defaults to 8MiB.
80    pub max_batch_bytes: ReadableSize,
81    /// When an append returns, defaults to `durable`.
82    pub ack_mode: AckMode,
83    /// Size of the unpersisted backlog at which appends stall until an
84    /// upload completes in `enqueued` mode, defaults to 64MiB.
85    pub max_unpersisted_bytes: ReadableSize,
86    /// Age of the oldest unpersisted entry at which appends stall until an
87    /// upload completes in `enqueued` mode, defaults to 8s.
88    #[serde(with = "humantime_serde")]
89    pub max_unpersisted_age: Duration,
90    /// What a read does with a segment that still does not decode after a
91    /// second fetch, because its checksum does not match or its content
92    /// disagrees with its footer entry, defaults to `skip`.
93    pub on_corrupted_segment: CorruptedSegmentAction,
94    /// Whether a region whose WAL history the configured location does not
95    /// hold opens anyway, with its writes that were not flushed lost, instead
96    /// of failing to open, defaults to false. Meant for one start after the
97    /// old WAL location is lost.
98    pub accept_missing_history: bool,
99}
100
101impl Default for ObjectStoreWalConfig {
102    fn default() -> Self {
103        Self {
104            storage_provider: String::new(),
105            prefix: "wal".to_string(),
106            flush_interval: Duration::from_millis(100),
107            max_batch_bytes: ReadableSize::mb(8),
108            ack_mode: AckMode::Durable,
109            max_unpersisted_bytes: ReadableSize::mb(64),
110            max_unpersisted_age: Duration::from_secs(8),
111            on_corrupted_segment: CorruptedSegmentAction::Skip,
112            accept_missing_history: false,
113        }
114    }
115}
116
117impl ObjectStoreWalConfig {
118    /// Validates the public root prefix without changing its stored identity.
119    /// Other WAL settings are irrelevant to metasrv and validated by the datanode.
120    pub fn validate_prefix(&self) -> Result<(), &'static str> {
121        let prefix = self.prefix.trim();
122        if prefix.is_empty() {
123            return Err("must not be empty");
124        }
125        if prefix.starts_with('/') {
126            return Err("must be a relative path");
127        }
128        if prefix
129            .split('/')
130            .any(|component| component.is_empty() || component == "..")
131        {
132            return Err("must not contain empty or `..` components");
133        }
134        // The node suffix preserves trailing whitespace in the root's last component.
135        if self
136            .prefix
137            .trim_start()
138            .split('/')
139            .any(|component| component == ".")
140        {
141            return Err("must not contain `.` components");
142        }
143        Ok(())
144    }
145
146    /// Returns the prefix the store of `node_id` runs under in `generation`:
147    /// `<prefix>/datanodes/<node_id>/epochs/<generation>`.
148    ///
149    /// Writers and remote readers derive concrete node directories here.
150    /// Distributed region metadata retains the public root instead; standalone
151    /// WAL options retain this concrete prefix for compatibility.
152    pub fn node_prefix(&self, node_id: u64, generation: u64) -> String {
153        format!("{}/datanodes/{node_id}/epochs/{generation}", self.prefix)
154    }
155}
156
157#[cfg(test)]
158mod tests {
159    use super::*;
160
161    #[test]
162    fn test_validate_prefix() {
163        for prefix in [
164            "", "   ", "/wal", "wal/", "wal//a", "wal/../a", ".", "wal/./a",
165        ] {
166            let config = ObjectStoreWalConfig {
167                prefix: prefix.to_string(),
168                ..Default::default()
169            };
170            assert!(config.validate_prefix().is_err(), "{prefix:?}");
171        }
172        for prefix in ["wal", "tenant/wal", " wal ", "wal/. ", ". "] {
173            let config = ObjectStoreWalConfig {
174                prefix: prefix.to_string(),
175                ..Default::default()
176            };
177            assert_eq!(Ok(()), config.validate_prefix());
178            assert_eq!(prefix, config.prefix);
179        }
180    }
181
182    #[test]
183    fn test_node_prefix() {
184        let config = ObjectStoreWalConfig::default();
185        assert_eq!(
186            config.node_prefix(0, FIXED_DIRECTORY_GENERATION),
187            "wal/datanodes/0/epochs/0"
188        );
189
190        let config = ObjectStoreWalConfig {
191            prefix: "cluster-a/wal".to_string(),
192            ..Default::default()
193        };
194        assert_eq!(
195            config.node_prefix(3, 7),
196            "cluster-a/wal/datanodes/3/epochs/7"
197        );
198    }
199}