| 1 |
//! Helpers around revlog compression |
| 2 |
|
| 3 |
use std::cell::RefCell; |
| 4 |
use std::collections::HashSet; |
| 5 |
use std::io::Read; |
| 6 |
|
| 7 |
use flate2::bufread::ZlibEncoder; |
| 8 |
use flate2::read::ZlibDecoder; |
| 9 |
|
| 10 |
use super::corrupted; |
| 11 |
use super::RevlogError; |
| 12 |
use crate::config::Config; |
| 13 |
use crate::errors::HgError; |
| 14 |
use crate::exit_codes; |
| 15 |
|
| 16 |
/// Header byte used to identify ZSTD-compressed data |
| 17 |
pub const ZSTD_BYTE: u8 = b'\x28'; |
| 18 |
/// Header byte used to identify Zlib-compressed data |
| 19 |
pub const ZLIB_BYTE: u8 = b'x'; |
| 20 |
|
| 21 |
const ZSTD_DEFAULT_LEVEL: u8 = 3; |
| 22 |
const ZLIB_DEFAULT_LEVEL: u8 = 6; |
| 23 |
/// The length of data below which we don't even try to compress it when using |
| 24 |
/// Zstandard. |
| 25 |
const MINIMUM_LENGTH_ZSTD: usize = 50; |
| 26 |
/// The length of data below which we don't even try to compress it when using |
| 27 |
/// Zlib. |
| 28 |
const MINIMUM_LENGTH_ZLIB: usize = 44; |
| 29 |
|
| 30 |
/// Defines the available compression engines and their options. |
| 31 |
#[derive(Debug, Copy, Clone, PartialEq, Eq)] |
| 32 |
pub enum CompressionConfig { |
| 33 |
Zlib { |
| 34 |
/// Between 0 and 9 included |
| 35 |
level: u8, |
| 36 |
}, |
| 37 |
Zstd { |
| 38 |
/// Between 0 and 22 included |
| 39 |
level: u8, |
| 40 |
/// Never used in practice for now |
| 41 |
threads: u8, |
| 42 |
}, |
| 43 |
/// No compression is performed |
| 44 |
None, |
| 45 |
} |
| 46 |
|
| 47 |
impl CompressionConfig { |
| 48 |
pub fn new( |
| 49 |
config: &Config, |
| 50 |
requirements: &HashSet<String>, |
| 51 |
) -> Result<Self, HgError> { |
| 52 |
let mut new = Self::default(); |
| 53 |
|
| 54 |
let zlib_level = config.get_u32(b"storage", b"revlog.zlib.level")?; |
| 55 |
let zstd_level = config.get_u32(b"storage", b"revlog.zstd.level")?; |
| 56 |
|
| 57 |
for requirement in requirements { |
| 58 |
if requirement.starts_with("revlog-compression-") |
| 59 |
|| requirement.starts_with("exp-compression-") |
| 60 |
{ |
| 61 |
let split = &mut requirement.splitn(3, '-'); |
| 62 |
split.next(); |
| 63 |
split.next(); |
| 64 |
new = match split.next().unwrap() { |
| 65 |
"zstd" => CompressionConfig::zstd(zstd_level)?, |
| 66 |
e => { |
| 67 |
return Err(HgError::unsupported(format!( |
| 68 |
"Unsupported compression engine '{e}'" |
| 69 |
))) |
| 70 |
} |
| 71 |
}; |
| 72 |
} |
| 73 |
} |
| 74 |
if let Some(level) = zlib_level { |
| 75 |
if matches!(new, CompressionConfig::Zlib { .. }) { |
| 76 |
new.set_level(level as usize)?; |
| 77 |
} |
| 78 |
} |
| 79 |
Ok(new) |
| 80 |
} |
| 81 |
|
| 82 |
/// Sets the level of the current compression engine |
| 83 |
pub fn set_level(&mut self, new_level: usize) -> Result<(), HgError> { |
| 84 |
match self { |
| 85 |
CompressionConfig::Zlib { level } => { |
| 86 |
if new_level > 9 { |
| 87 |
return Err(HgError::abort( |
| 88 |
format!( |
| 89 |
"invalid compression zlib compression level {}, \ |
| 90 |
expected between 0 and 9 included", |
| 91 |
new_level |
| 92 |
), |
| 93 |
exit_codes::ABORT, |
| 94 |
None, |
| 95 |
)); |
| 96 |
} |
| 97 |
*level = new_level as u8; |
| 98 |
} |
| 99 |
CompressionConfig::Zstd { level, .. } => { |
| 100 |
if new_level > 22 { |
| 101 |
return Err(HgError::abort( |
| 102 |
format!( |
| 103 |
"invalid compression zstd compression level {}, \ |
| 104 |
expected between 0 and 22 included", |
| 105 |
new_level |
| 106 |
), |
| 107 |
exit_codes::ABORT, |
| 108 |
None, |
| 109 |
)); |
| 110 |
} |
| 111 |
*level = new_level as u8; |
| 112 |
} |
| 113 |
CompressionConfig::None => {} |
| 114 |
} |
| 115 |
Ok(()) |
| 116 |
} |
| 117 |
|
| 118 |
/// Return a ZSTD compression config |
| 119 |
pub fn zstd(zstd_level: Option<u32>) -> Result<CompressionConfig, HgError> { |
| 120 |
let mut engine = |
| 121 |
CompressionConfig::Zstd { level: ZSTD_DEFAULT_LEVEL, threads: 0 }; |
| 122 |
if let Some(level) = zstd_level { |
| 123 |
engine.set_level(level as usize)?; |
| 124 |
} |
| 125 |
Ok(engine) |
| 126 |
} |
| 127 |
} |
| 128 |
|
| 129 |
impl Default for CompressionConfig { |
| 130 |
fn default() -> Self { |
| 131 |
Self::Zlib { level: ZLIB_DEFAULT_LEVEL } |
| 132 |
} |
| 133 |
} |
| 134 |
|
| 135 |
/// A high-level trait to define compressors that should be able to compress |
| 136 |
/// and decompress arbitrary bytes. |
| 137 |
pub trait Compressor: Send { |
| 138 |
/// Returns a new [`Vec`] with the compressed data. |
| 139 |
/// Should return `Ok(None)` if compression does not apply (e.g. too small) |
| 140 |
fn compress(&mut self, data: &[u8]) |
| 141 |
-> Result<Option<Vec<u8>>, RevlogError>; |
| 142 |
/// Returns a new [`Vec`] with the decompressed data. |
| 143 |
fn decompress(&self, data: &[u8]) -> Result<Vec<u8>, RevlogError>; |
| 144 |
} |
| 145 |
|
| 146 |
/// A compressor that does nothing (useful in tests) |
| 147 |
pub struct NoneCompressor; |
| 148 |
|
| 149 |
impl Compressor for NoneCompressor { |
| 150 |
fn compress( |
| 151 |
&mut self, |
| 152 |
_data: &[u8], |
| 153 |
) -> Result<Option<Vec<u8>>, RevlogError> { |
| 154 |
Ok(None) |
| 155 |
} |
| 156 |
|
| 157 |
fn decompress(&self, data: &[u8]) -> Result<Vec<u8>, RevlogError> { |
| 158 |
Ok(data.to_owned()) |
| 159 |
} |
| 160 |
} |
| 161 |
|
| 162 |
/// A compressor for Zstandard |
| 163 |
pub struct ZstdCompressor { |
| 164 |
/// Level of compression to use |
| 165 |
level: u8, |
| 166 |
/// How many threads are used (not implemented yet) |
| 167 |
threads: u8, |
| 168 |
/// The underlying zstd compressor |
| 169 |
compressor: zstd::bulk::Compressor<'static>, |
| 170 |
} |
| 171 |
|
| 172 |
impl ZstdCompressor { |
| 173 |
pub fn new(level: u8, threads: u8) -> Self { |
| 174 |
Self { |
| 175 |
level, |
| 176 |
threads, |
| 177 |
compressor: zstd::bulk::Compressor::new(level.into()) |
| 178 |
.expect("invalid zstd arguments"), |
| 179 |
} |
| 180 |
} |
| 181 |
} |
| 182 |
|
| 183 |
impl Compressor for ZstdCompressor { |
| 184 |
fn compress( |
| 185 |
&mut self, |
| 186 |
data: &[u8], |
| 187 |
) -> Result<Option<Vec<u8>>, RevlogError> { |
| 188 |
if self.threads != 0 { |
| 189 |
// TODO use a zstd builder + zstd cargo feature to support this |
| 190 |
unimplemented!("zstd parallel compression is not implemented"); |
| 191 |
} |
| 192 |
if data.len() < MINIMUM_LENGTH_ZSTD { |
| 193 |
return Ok(None); |
| 194 |
} |
| 195 |
let level = self.level as i32; |
| 196 |
if data.len() <= 1000000 { |
| 197 |
let compressed = self.compressor.compress(data).map_err(|e| { |
| 198 |
corrupted(format!("revlog compress error: {}", e)) |
| 199 |
})?; |
| 200 |
Ok(if compressed.len() < data.len() { |
| 201 |
Some(compressed) |
| 202 |
} else { |
| 203 |
None |
| 204 |
}) |
| 205 |
} else { |
| 206 |
Ok(Some(zstd::stream::encode_all(data, level).map_err(|e| { |
| 207 |
corrupted(format!("revlog compress error: {}", e)) |
| 208 |
})?)) |
| 209 |
} |
| 210 |
} |
| 211 |
|
| 212 |
fn decompress(&self, data: &[u8]) -> Result<Vec<u8>, RevlogError> { |
| 213 |
zstd::stream::decode_all(data).map_err(|e| { |
| 214 |
corrupted(format!("revlog decompress error: {}", e)).into() |
| 215 |
}) |
| 216 |
} |
| 217 |
} |
| 218 |
|
| 219 |
/// A compressor for Zlib |
| 220 |
pub struct ZlibCompressor { |
| 221 |
/// Level of compression to use |
| 222 |
level: flate2::Compression, |
| 223 |
} |
| 224 |
|
| 225 |
impl ZlibCompressor { |
| 226 |
pub fn new(level: u8) -> Self { |
| 227 |
Self { level: flate2::Compression::new(level.into()) } |
| 228 |
} |
| 229 |
} |
| 230 |
|
| 231 |
impl Compressor for ZlibCompressor { |
| 232 |
fn compress( |
| 233 |
&mut self, |
| 234 |
data: &[u8], |
| 235 |
) -> Result<Option<Vec<u8>>, RevlogError> { |
| 236 |
assert!(!data.is_empty()); |
| 237 |
if data.len() < MINIMUM_LENGTH_ZLIB { |
| 238 |
return Ok(None); |
| 239 |
} |
| 240 |
let mut buf = Vec::with_capacity(data.len()); |
| 241 |
ZlibEncoder::new(data, self.level) |
| 242 |
.read_to_end(&mut buf) |
| 243 |
.map_err(|e| corrupted(format!("revlog compress error: {}", e)))?; |
| 244 |
|
| 245 |
Ok(if buf.len() < data.len() { |
| 246 |
buf.shrink_to_fit(); |
| 247 |
Some(buf) |
| 248 |
} else { |
| 249 |
None |
| 250 |
}) |
| 251 |
} |
| 252 |
|
| 253 |
fn decompress(&self, data: &[u8]) -> Result<Vec<u8>, RevlogError> { |
| 254 |
let mut decoder = ZlibDecoder::new(data); |
| 255 |
// TODO reuse the allocation somehow? |
| 256 |
let mut buf = vec![]; |
| 257 |
decoder.read_to_end(&mut buf).map_err(|e| { |
| 258 |
corrupted(format!("revlog decompress error: {}", e)) |
| 259 |
})?; |
| 260 |
Ok(buf) |
| 261 |
} |
| 262 |
} |
| 263 |
|
| 264 |
thread_local! { |
| 265 |
// seems fine to [unwrap] here: this can only fail due to memory allocation |
| 266 |
// failing, and it's normal for that to cause panic. |
| 267 |
static ZSTD_DECODER : RefCell<zstd::bulk::Decompressor<'static>> = |
| 268 |
RefCell::new(zstd::bulk::Decompressor::new().ok().unwrap()); |
| 269 |
} |
| 270 |
|
| 271 |
/// Util to wrap the reuse of a zstd decoder while controlling its buffer size. |
| 272 |
fn zstd_decompress_to_buffer( |
| 273 |
bytes: &[u8], |
| 274 |
buf: &mut Vec<u8>, |
| 275 |
) -> Result<usize, std::io::Error> { |
| 276 |
ZSTD_DECODER |
| 277 |
.with(|decoder| decoder.borrow_mut().decompress_to_buffer(bytes, buf)) |
| 278 |
} |
| 279 |
|
| 280 |
/// Specialized revlog decompression to use less memory for deltas while |
| 281 |
/// keeping performance acceptable. |
| 282 |
pub(super) fn uncompressed_zstd_data( |
| 283 |
bytes: &[u8], |
| 284 |
is_delta: bool, |
| 285 |
uncompressed_len: i32, |
| 286 |
) -> Result<Vec<u8>, HgError> { |
| 287 |
let cap = uncompressed_len.max(0) as usize; |
| 288 |
if is_delta { |
| 289 |
// [cap] is usually an over-estimate of the space needed because |
| 290 |
// it's the length of delta-decoded data, but we're interested |
| 291 |
// in the size of the delta. |
| 292 |
// This means we have to [shrink_to_fit] to avoid holding on |
| 293 |
// to a large chunk of memory, but it also means we must have a |
| 294 |
// fallback branch, for the case when the delta is longer than |
| 295 |
// the original data (surprisingly, this does happen in practice) |
| 296 |
let mut buf = Vec::with_capacity(cap); |
| 297 |
match zstd_decompress_to_buffer(bytes, &mut buf) { |
| 298 |
Ok(_) => buf.shrink_to_fit(), |
| 299 |
Err(_) => { |
| 300 |
buf.clear(); |
| 301 |
zstd::stream::copy_decode(bytes, &mut buf) |
| 302 |
.map_err(|e| corrupted(e.to_string()))?; |
| 303 |
} |
| 304 |
}; |
| 305 |
Ok(buf) |
| 306 |
} else { |
| 307 |
let mut buf = Vec::with_capacity(cap); |
| 308 |
let len = zstd_decompress_to_buffer(bytes, &mut buf) |
| 309 |
.map_err(|e| corrupted(e.to_string()))?; |
| 310 |
if len != uncompressed_len as usize { |
| 311 |
Err(corrupted("uncompressed length does not match")) |
| 312 |
} else { |
| 313 |
Ok(buf) |
| 314 |
} |
| 315 |
} |
| 316 |
} |
| 317 |
|
| 318 |
#[cfg(test)] |
| 319 |
mod tests { |
| 320 |
use super::*; |
| 321 |
|
| 322 |
const LARGE_TEXT: &[u8] = b" |
| 323 |
Patali Dirapata, Cromda Cromda Ripalo, Pata Pata, Ko Ko Ko |
| 324 |
Bokoro Dipoulito, Rondi Rondi Pepino, Pata Pata, Ko Ko Ko |
| 325 |
Emana Karassoli, Loucra Loucra Nonponto, Pata Pata, Ko Ko Ko."; |
| 326 |
|
| 327 |
#[test] |
| 328 |
fn test_zlib_compressor() { |
| 329 |
// Can return `Ok(None)` |
| 330 |
let mut compressor = ZlibCompressor::new(1); |
| 331 |
assert_eq!(compressor.compress(b"too small").unwrap(), None); |
| 332 |
|
| 333 |
// Compression returns bytes |
| 334 |
let compressed_with_1 = |
| 335 |
compressor.compress(LARGE_TEXT).unwrap().unwrap(); |
| 336 |
assert!(compressed_with_1.len() < LARGE_TEXT.len()); |
| 337 |
// Round trip works |
| 338 |
assert_eq!( |
| 339 |
compressor.decompress(&compressed_with_1).unwrap(), |
| 340 |
LARGE_TEXT |
| 341 |
); |
| 342 |
|
| 343 |
// Compression levels mean something |
| 344 |
let mut compressor = ZlibCompressor::new(9); |
| 345 |
// Compression returns bytes |
| 346 |
let compressed = compressor.compress(LARGE_TEXT).unwrap().unwrap(); |
| 347 |
assert!(compressed.len() < compressed_with_1.len()); |
| 348 |
} |
| 349 |
|
| 350 |
#[test] |
| 351 |
fn test_zstd_compressor() { |
| 352 |
// Can return `Ok(None)` |
| 353 |
let mut compressor = ZstdCompressor::new(1, 0); |
| 354 |
assert_eq!(compressor.compress(b"too small").unwrap(), None); |
| 355 |
|
| 356 |
// Compression returns bytes |
| 357 |
let compressed_with_1 = |
| 358 |
compressor.compress(LARGE_TEXT).unwrap().unwrap(); |
| 359 |
assert!(compressed_with_1.len() < LARGE_TEXT.len()); |
| 360 |
// Round trip works |
| 361 |
assert_eq!( |
| 362 |
compressor.decompress(&compressed_with_1).unwrap(), |
| 363 |
LARGE_TEXT |
| 364 |
); |
| 365 |
|
| 366 |
// Compression levels mean something |
| 367 |
let mut compressor = ZstdCompressor::new(22, 0); |
| 368 |
// Compression returns bytes |
| 369 |
let compressed = compressor.compress(LARGE_TEXT).unwrap().unwrap(); |
| 370 |
assert!(compressed.len() < compressed_with_1.len()); |
| 371 |
} |
| 372 |
} |