wal_backup/storage/
compressed.rs1use async_trait::async_trait;
2use bytes::Bytes;
3use flate2::read::GzDecoder;
4use flate2::write::GzEncoder;
5use flate2::Compression;
6use std::path::PathBuf;
7use std::sync::Arc;
8
9use crate::error::Result;
10use crate::storage::BucketStore;
11
12const MAX_DECOMPRESSED_SIZE: usize = 2 * 1024 * 1024 * 1024;
13
14pub struct CompressedBucketStore {
15 inner: Arc<dyn BucketStore>,
16 level: u32,
17 max_decompressed_size: usize,
18}
19
20impl CompressedBucketStore {
21 pub fn new(inner: Arc<dyn BucketStore>, level: u32) -> Self {
22 CompressedBucketStore {
23 inner,
24 level,
25 max_decompressed_size: MAX_DECOMPRESSED_SIZE,
26 }
27 }
28
29 pub fn with_max_decompressed_size(mut self, limit: usize) -> Self {
30 self.max_decompressed_size = limit;
31 self
32 }
33
34 fn compress(&self, data: &[u8]) -> Result<Vec<u8>> {
35 let mut encoder = GzEncoder::new(Vec::new(), Compression::new(self.level));
36 std::io::Write::write_all(&mut encoder, data)
37 .map_err(|e| crate::error::Error::Other(format!("gzip compress: {e}")))?;
38 encoder
39 .finish()
40 .map_err(|e| crate::error::Error::Other(format!("gzip finish: {e}")))
41 }
42
43 fn decompress(&self, data: &[u8]) -> Result<Vec<u8>> {
44 let mut decoder = GzDecoder::new(data);
45 let mut buf = Vec::new();
46 let mut chunk = [0u8; 8192];
47 use std::io::Read;
48 loop {
49 let n = decoder
50 .read(&mut chunk)
51 .map_err(|e| crate::error::Error::Other(format!("gzip decompress: {e}")))?;
52 if n == 0 {
53 break;
54 }
55 if buf.len() + n > self.max_decompressed_size {
56 return Err(crate::error::Error::Other(format!(
57 "decompressed data exceeds {} byte limit (possible zip bomb)",
58 self.max_decompressed_size
59 )));
60 }
61 buf.extend_from_slice(&chunk[..n]);
62 }
63 Ok(buf)
64 }
65}
66
67#[async_trait]
68impl BucketStore for CompressedBucketStore {
69 fn prefix(&self) -> &str {
70 self.inner.prefix()
71 }
72 fn writer_id(&self) -> &str {
73 self.inner.writer_id()
74 }
75
76 async fn put(&self, key: &str, data: Bytes) -> Result<()> {
77 let compressed = self.compress(&data)?;
78 self.inner.put(key, Bytes::from(compressed)).await
79 }
80
81 async fn get(&self, key: &str) -> Result<Option<Bytes>> {
82 self.get_with_etag(key).await.map(|opt| opt.map(|(b, _)| b))
83 }
84
85 async fn get_with_etag(&self, key: &str) -> Result<Option<(Bytes, String)>> {
86 match self.inner.get_with_etag(key).await? {
91 Some((data, etag)) => {
92 let decompressed = self.decompress(&data)?;
93 Ok(Some((Bytes::from(decompressed), etag)))
94 }
95 None => Ok(None),
96 }
97 }
98
99 async fn list(&self, prefix: &str) -> Result<Vec<String>> {
100 self.inner.list(prefix).await
101 }
102
103 async fn delete(&self, key: &str) -> Result<()> {
104 self.inner.delete(key).await
105 }
106
107 async fn exists(&self, key: &str) -> Result<bool> {
108 self.inner.exists(key).await
109 }
110
111 async fn put_file(&self, key: &str, path: &std::path::Path) -> Result<()> {
112 let level = self.level;
116
117 let tmp_file = tempfile::NamedTempFile::new()
119 .map_err(|e| crate::error::Error::Other(format!("create temp file: {e}")))?;
120
121 tokio::task::spawn_blocking({
123 let tmp_path = tmp_file.path().to_path_buf();
124 let path = path.to_path_buf();
125 move || -> Result<()> {
126 let data = std::fs::read(&path).map_err(|e| {
127 crate::error::Error::Other(format!("failed to read file for compression: {e}"))
128 })?;
129 let mut encoder = GzEncoder::new(Vec::new(), Compression::new(level));
130 std::io::Write::write_all(&mut encoder, &data)
131 .map_err(|e| crate::error::Error::Other(format!("gzip compress: {e}")))?;
132 drop(data);
134 let compressed = encoder
135 .finish()
136 .map_err(|e| crate::error::Error::Other(format!("gzip finish: {e}")))?;
137 std::fs::write(&tmp_path, &compressed).map_err(|e| {
138 crate::error::Error::Other(format!("failed to write compressed temp file: {e}"))
139 })?;
140 Ok(())
141 }
142 })
143 .await??;
144
145 let tmp_path = tmp_file.path().to_path_buf();
148 let result = self.inner.put_file(key, &tmp_path).await;
149 drop(tmp_file);
151 result
152 }
153
154 async fn get_file(&self, key: &str, dest: &std::path::Path) -> Result<PathBuf> {
155 let compressed_tmp = dest.with_extension("compressed-tmp");
159 self.inner.get_file(key, &compressed_tmp).await?;
160
161 let tmp_path = dest.with_extension("tmp");
162 let tmp_path_owned = tmp_path.clone();
163 let dest_owned = dest.to_path_buf();
164 let compressed_tmp_owned = compressed_tmp.clone();
165 let max_size = self.max_decompressed_size;
166
167 let result = tokio::task::spawn_blocking(move || -> Result<PathBuf> {
168 use std::io::{Read, Write};
169 let compressed_file = std::fs::File::open(&compressed_tmp_owned)?;
170 let mut decoder = GzDecoder::new(compressed_file);
171 let mut file = std::fs::File::create(&tmp_path_owned)?;
172 let mut chunk = [0u8; 8192];
173 let mut written: usize = 0;
174 loop {
175 let n = decoder
176 .read(&mut chunk)
177 .map_err(|e| crate::error::Error::Other(format!("gzip decompress: {e}")))?;
178 if n == 0 {
179 break;
180 }
181 if written + n > max_size {
182 return Err(crate::error::Error::Other(format!(
183 "decompressed data exceeds {} byte limit (possible zip bomb)",
184 max_size
185 )));
186 }
187 Write::write_all(&mut file, &chunk[..n])?;
188 written += n;
189 }
190 Write::flush(&mut file)?;
191 file.sync_all()?;
192 std::fs::rename(&tmp_path_owned, &dest_owned)?;
193 Ok(dest_owned)
194 })
195 .await?;
196
197 let _ = tokio::fs::remove_file(&compressed_tmp).await;
199 result
200 }
201
202 async fn put_if_match(&self, key: &str, data: Bytes, etag: &str) -> Result<()> {
203 let compressed = self.compress(&data)?;
205 self.inner
206 .put_if_match(key, Bytes::from(compressed), etag)
207 .await
208 }
209
210 async fn put_if_not_exists(&self, key: &str, data: Bytes) -> Result<()> {
211 let compressed = self.compress(&data)?;
212 self.inner
213 .put_if_not_exists(key, Bytes::from(compressed))
214 .await
215 }
216}