Line data Source code
1 : use std::sync::Arc;
2 :
3 : use ::metrics::IntGauge;
4 : use bytes::{Buf, BufMut, Bytes};
5 : use pageserver_api::key::{Key, AUX_KEY_PREFIX, METADATA_KEY_SIZE};
6 : use tracing::warn;
7 :
8 : // BEGIN Copyright (c) 2017 Servo Contributors
9 :
10 : /// Const version of FNV hash.
11 : #[inline]
12 : #[must_use]
13 26 : pub const fn fnv_hash(bytes: &[u8]) -> u128 {
14 26 : const INITIAL_STATE: u128 = 0x6c62272e07bb014262b821756295c58d;
15 26 : const PRIME: u128 = 0x0000000001000000000000000000013B;
16 26 :
17 26 : let mut hash = INITIAL_STATE;
18 26 : let mut i = 0;
19 196 : while i < bytes.len() {
20 170 : hash ^= bytes[i] as u128;
21 170 : hash = hash.wrapping_mul(PRIME);
22 170 : i += 1;
23 170 : }
24 26 : hash
25 26 : }
26 :
27 : // END Copyright (c) 2017 Servo Contributors
28 :
29 : /// Create a metadata key from a hash, encoded as [AUX_KEY_PREFIX, 2B directory prefix, least significant 13B of FNV hash].
30 20 : fn aux_hash_to_metadata_key(dir_level1: u8, dir_level2: u8, data: &[u8]) -> Key {
31 20 : let mut key: [u8; 16] = [0; METADATA_KEY_SIZE];
32 20 : let hash = fnv_hash(data).to_be_bytes();
33 20 : key[0] = AUX_KEY_PREFIX;
34 20 : key[1] = dir_level1;
35 20 : key[2] = dir_level2;
36 20 : key[3..16].copy_from_slice(&hash[3..16]);
37 20 : Key::from_metadata_key_fixed_size(&key)
38 20 : }
39 :
40 : const AUX_DIR_PG_LOGICAL: u8 = 0x01;
41 : const AUX_DIR_PG_REPLSLOT: u8 = 0x02;
42 : const AUX_DIR_PG_UNKNOWN: u8 = 0xFF;
43 :
44 : /// Encode the aux file into a fixed-size key.
45 : ///
46 : /// The first byte is the AUX key prefix. We use the next 2 bytes of the key for the directory / aux file type.
47 : /// We have one-to-one mapping for each of the aux file that we support. We hash the remaining part of the path
48 : /// (usually a single file name, or several components) into 13-byte hash. The way we determine the 2-byte prefix
49 : /// is roughly based on the first two components of the path, one unique number for one component.
50 : ///
51 : /// * pg_logical/mappings -> 0x0101
52 : /// * pg_logical/snapshots -> 0x0102
53 : /// * pg_logical/replorigin_checkpoint -> 0x0103
54 : /// * pg_logical/others -> 0x01FF
55 : /// * pg_replslot/ -> 0x0201
56 : /// * others -> 0xFFFF
57 : ///
58 : /// If you add new AUX files to this function, please also add a test case to `test_encoding_portable`.
59 : /// The new file type must have never been written to the storage before. Otherwise, there could be data
60 : /// corruptions as the new file belongs to a new prefix but it might have been stored under the `others` prefix.
61 20 : pub fn encode_aux_file_key(path: &str) -> Key {
62 20 : if let Some(fname) = path.strip_prefix("pg_logical/mappings/") {
63 10 : aux_hash_to_metadata_key(AUX_DIR_PG_LOGICAL, 0x01, fname.as_bytes())
64 10 : } else if let Some(fname) = path.strip_prefix("pg_logical/snapshots/") {
65 2 : aux_hash_to_metadata_key(AUX_DIR_PG_LOGICAL, 0x02, fname.as_bytes())
66 8 : } else if path == "pg_logical/replorigin_checkpoint" {
67 2 : aux_hash_to_metadata_key(AUX_DIR_PG_LOGICAL, 0x03, b"")
68 6 : } else if let Some(fname) = path.strip_prefix("pg_logical/") {
69 2 : if cfg!(debug_assertions) {
70 2 : warn!(
71 0 : "unsupported pg_logical aux file type: {}, putting to 0x01FF, would affect path scanning",
72 : path
73 : );
74 0 : }
75 2 : aux_hash_to_metadata_key(AUX_DIR_PG_LOGICAL, 0xFF, fname.as_bytes())
76 4 : } else if let Some(fname) = path.strip_prefix("pg_replslot/") {
77 2 : aux_hash_to_metadata_key(AUX_DIR_PG_REPLSLOT, 0x01, fname.as_bytes())
78 : } else {
79 2 : if cfg!(debug_assertions) {
80 2 : warn!(
81 0 : "unsupported aux file type: {}, putting to 0xFFFF, would affect path scanning",
82 : path
83 : );
84 0 : }
85 2 : aux_hash_to_metadata_key(AUX_DIR_PG_UNKNOWN, 0xFF, path.as_bytes())
86 : }
87 20 : }
88 :
89 : const AUX_FILE_ENCODING_VERSION: u8 = 0x01;
90 :
91 6 : pub fn decode_file_value(val: &[u8]) -> anyhow::Result<Vec<(&str, &[u8])>> {
92 6 : let mut ptr = val;
93 6 : if ptr.is_empty() {
94 : // empty value = no files
95 2 : return Ok(Vec::new());
96 4 : }
97 4 : assert_eq!(
98 4 : ptr.get_u8(),
99 : AUX_FILE_ENCODING_VERSION,
100 0 : "unsupported aux file value"
101 : );
102 4 : let mut files = vec![];
103 10 : while ptr.has_remaining() {
104 6 : let key_len = ptr.get_u32() as usize;
105 6 : let key = &ptr[..key_len];
106 6 : ptr.advance(key_len);
107 6 : let val_len = ptr.get_u32() as usize;
108 6 : let content = &ptr[..val_len];
109 6 : ptr.advance(val_len);
110 :
111 6 : let path = std::str::from_utf8(key)?;
112 6 : files.push((path, content));
113 : }
114 4 : Ok(files)
115 6 : }
116 :
117 : /// Decode an aux file key-value pair into a list of files. The returned `Bytes` contains reference
118 : /// to the original value slice. Be cautious about memory consumption.
119 16 : pub fn decode_file_value_bytes(val: &Bytes) -> anyhow::Result<Vec<(String, Bytes)>> {
120 16 : let mut ptr = val.clone();
121 16 : if ptr.is_empty() {
122 : // empty value = no files
123 0 : return Ok(Vec::new());
124 16 : }
125 16 : assert_eq!(
126 16 : ptr.get_u8(),
127 : AUX_FILE_ENCODING_VERSION,
128 0 : "unsupported aux file value"
129 : );
130 16 : let mut files = vec![];
131 32 : while ptr.has_remaining() {
132 16 : let key_len = ptr.get_u32() as usize;
133 16 : let key = ptr.slice(..key_len);
134 16 : ptr.advance(key_len);
135 16 : let val_len = ptr.get_u32() as usize;
136 16 : let content = ptr.slice(..val_len);
137 16 : ptr.advance(val_len);
138 :
139 16 : let path = std::str::from_utf8(&key)?.to_string();
140 16 : files.push((path, content));
141 : }
142 16 : Ok(files)
143 16 : }
144 :
145 12 : pub fn encode_file_value(files: &[(&str, &[u8])]) -> anyhow::Result<Vec<u8>> {
146 12 : if files.is_empty() {
147 : // no files = empty value
148 2 : return Ok(Vec::new());
149 10 : }
150 10 : let mut encoded = vec![];
151 10 : encoded.put_u8(AUX_FILE_ENCODING_VERSION);
152 22 : for (path, content) in files {
153 12 : if path.len() > u32::MAX as usize {
154 0 : anyhow::bail!("{} exceeds path size limit", path);
155 12 : }
156 12 : encoded.put_u32(path.len() as u32);
157 12 : encoded.put_slice(path.as_bytes());
158 12 : if content.len() > u32::MAX as usize {
159 0 : anyhow::bail!("{} exceeds content size limit", path);
160 12 : }
161 12 : encoded.put_u32(content.len() as u32);
162 12 : encoded.put_slice(content);
163 : }
164 10 : Ok(encoded)
165 12 : }
166 :
167 : /// An estimation of the size of aux files.
168 : pub struct AuxFileSizeEstimator {
169 : aux_file_size_gauge: IntGauge,
170 : size: Arc<std::sync::Mutex<Option<isize>>>,
171 : }
172 :
173 : impl AuxFileSizeEstimator {
174 352 : pub fn new(aux_file_size_gauge: IntGauge) -> Self {
175 352 : Self {
176 352 : aux_file_size_gauge,
177 352 : size: Arc::new(std::sync::Mutex::new(None)),
178 352 : }
179 352 : }
180 :
181 8 : pub fn on_base_backup(&self, new_size: usize) {
182 8 : let mut guard = self.size.lock().unwrap();
183 8 : *guard = Some(new_size as isize);
184 8 : self.report(new_size as isize);
185 8 : }
186 :
187 6 : pub fn on_add(&self, file_size: usize) {
188 6 : let mut guard = self.size.lock().unwrap();
189 6 : if let Some(size) = &mut *guard {
190 4 : *size += file_size as isize;
191 4 : self.report(*size);
192 4 : }
193 6 : }
194 :
195 0 : pub fn on_remove(&self, file_size: usize) {
196 0 : let mut guard = self.size.lock().unwrap();
197 0 : if let Some(size) = &mut *guard {
198 0 : *size -= file_size as isize;
199 0 : self.report(*size);
200 0 : }
201 0 : }
202 :
203 2 : pub fn on_update(&self, old_size: usize, new_size: usize) {
204 2 : let mut guard = self.size.lock().unwrap();
205 2 : if let Some(size) = &mut *guard {
206 2 : *size += new_size as isize - old_size as isize;
207 2 : self.report(*size);
208 2 : }
209 2 : }
210 :
211 14 : pub fn report(&self, size: isize) {
212 14 : self.aux_file_size_gauge.set(size as i64);
213 14 : }
214 : }
215 :
216 : #[cfg(test)]
217 : mod tests {
218 : use super::*;
219 :
220 : #[test]
221 2 : fn test_hash_portable() {
222 2 : // AUX file encoding requires the hash to be portable across all platforms. This test case checks
223 2 : // if the algorithm produces the same hash across different environments.
224 2 :
225 2 : assert_eq!(
226 2 : 265160408618497461376862998434862070044,
227 2 : super::fnv_hash("test1".as_bytes())
228 2 : );
229 2 : assert_eq!(
230 2 : 295486155126299629456360817749600553988,
231 2 : super::fnv_hash("test/test2".as_bytes())
232 2 : );
233 2 : assert_eq!(
234 2 : 144066263297769815596495629667062367629,
235 2 : super::fnv_hash("".as_bytes())
236 2 : );
237 2 : }
238 :
239 : #[test]
240 2 : fn test_encoding_portable() {
241 2 : // To correct retrieve AUX files, the generated keys for the same file must be the same for all versions
242 2 : // of the page server.
243 2 : assert_eq!(
244 2 : "62000001017F8B83D94F7081693471ABF91C",
245 2 : encode_aux_file_key("pg_logical/mappings/test1").to_string(),
246 2 : );
247 2 : assert_eq!(
248 2 : "62000001027F8E83D94F7081693471ABFCCD",
249 2 : encode_aux_file_key("pg_logical/snapshots/test2").to_string(),
250 2 : );
251 2 : assert_eq!(
252 2 : "62000001032E07BB014262B821756295C58D",
253 2 : encode_aux_file_key("pg_logical/replorigin_checkpoint").to_string(),
254 2 : );
255 2 : assert_eq!(
256 2 : "62000001FF4F38E1C74754E7D03C1A660178",
257 2 : encode_aux_file_key("pg_logical/unsupported").to_string(),
258 2 : );
259 2 : assert_eq!(
260 2 : "62000002017F8D83D94F7081693471ABFB92",
261 2 : encode_aux_file_key("pg_replslot/test3").to_string()
262 2 : );
263 2 : assert_eq!(
264 2 : "620000FFFF2B6ECC8AEF93F643DC44F15E03",
265 2 : encode_aux_file_key("other_file_not_supported").to_string(),
266 2 : );
267 2 : }
268 :
269 : #[test]
270 2 : fn test_value_encoding() {
271 2 : let files = vec![
272 2 : ("pg_logical/1.file", "1111".as_bytes()),
273 2 : ("pg_logical/2.file", "2222".as_bytes()),
274 2 : ];
275 2 : assert_eq!(
276 2 : files,
277 2 : decode_file_value(&encode_file_value(&files).unwrap()).unwrap()
278 2 : );
279 2 : let files = vec![];
280 2 : assert_eq!(
281 2 : files,
282 2 : decode_file_value(&encode_file_value(&files).unwrap()).unwrap()
283 2 : );
284 2 : }
285 : }
|