rustfs-ecstore 1.0.1

Erasure coding storage backend for RustFS, providing efficient data storage and retrieval with redundancy.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use rustfs_utils::string::{has_pattern, has_string_suffix_in_slice, match_simple};
use std::env;
use std::sync::OnceLock;
use tracing::debug;

pub const MIN_DISK_COMPRESSIBLE_SIZE: usize = 4096;

// Environment variable name to control whether object disk compression is enabled.
pub const ENV_DISK_COMPRESSION_ENABLED: &str = "RUSTFS_COMPRESSION_ENABLED";

// Environment variable for file extensions to include in object disk compression.
pub const ENV_DISK_COMPRESSION_EXTENSIONS: &str = "RUSTFS_COMPRESSION_EXTENSIONS";

// Environment variable for MIME types to include in object disk compression.
pub const ENV_DISK_COMPRESSION_MIME_TYPES: &str = "RUSTFS_COMPRESSION_MIME_TYPES";

// Environment variable for additional extensions to exclude from compression (comma-separated, e.g. ".foo,.bar")
pub const ENV_ADDED_EXCLUDE_COMPRESS_EXTENSIONS: &str = "RUSTFS_ADDED_EXCLUDE_COMPRESS_EXTENSIONS";

// Environment variable to additionally enable disk compression for multipart uploads.
// Default off: nodes from before the resumable decompressor fix fail transient reads of
// compressed objects, so multipart compression stays dark until the operator confirms the
// fleet has converged on a fixed build.
// RUSTFS_COMPAT_TODO(multipart-compression-default-off-window): staged rollout switch for restored multipart compression, flipping the default to enabled on retirement. Remove after the minimum supported direct-upgrade release ships the resumable DecompressReader.
pub const ENV_DISK_COMPRESSION_MULTIPART_ENABLED: &str = "RUSTFS_COMPRESSION_MULTIPART_ENABLED";

pub const DEFAULT_DISK_COMPRESS_EXTENSIONS: &str = ".txt,.log,.csv,.json,.tar,.xml,.bin";
pub const DEFAULT_DISK_COMPRESS_MIME_TYPES: &str = "text/*,application/json,application/xml,binary/octet-stream";

#[derive(Debug)]
struct DiskCompressionConfig {
    enabled: bool,
    extensions: Vec<String>,
    mime_types: Vec<String>,
    added_exclude_extensions: Vec<String>,
}

/// Parses RUSTFS_COMPRESSION_ENABLED. Called once at first use via OnceLock.
fn parse_disk_compression_enabled() -> bool {
    env::var(ENV_DISK_COMPRESSION_ENABLED)
        .map(|s| matches!(s.to_ascii_lowercase().as_str(), "true" | "on" | "1"))
        .unwrap_or(false)
}

fn parse_csv(value: &str) -> Vec<String> {
    value
        .split(',')
        .map(|v| v.trim().to_ascii_lowercase())
        .filter(|v| !v.is_empty())
        .collect()
}

fn normalize_extensions(extensions: Vec<String>) -> Vec<String> {
    extensions
        .into_iter()
        .map(|v| if v.starts_with('.') { v } else { format!(".{v}") })
        .collect()
}

fn has_config_pattern(patterns: &[String], match_str: &str) -> bool {
    patterns.iter().any(|pattern| match_simple(pattern, match_str))
}

fn has_object_content_encoding(headers: &http::HeaderMap) -> bool {
    for value in headers.get_all(http::header::CONTENT_ENCODING) {
        let Ok(content_encoding) = value.to_str() else {
            return true;
        };

        for encoding in content_encoding.split(',').map(str::trim) {
            if !encoding.is_empty() && !encoding.eq_ignore_ascii_case("identity") && !encoding.eq_ignore_ascii_case("aws-chunked")
            {
                return true;
            }
        }
    }
    false
}

fn parse_disk_compression_extensions() -> Vec<String> {
    let extensions = env::var(ENV_DISK_COMPRESSION_EXTENSIONS).unwrap_or_else(|_| DEFAULT_DISK_COMPRESS_EXTENSIONS.to_string());
    normalize_extensions(parse_csv(&extensions))
}

fn parse_disk_compression_mime_types() -> Vec<String> {
    let mime_types = env::var(ENV_DISK_COMPRESSION_MIME_TYPES).unwrap_or_else(|_| DEFAULT_DISK_COMPRESS_MIME_TYPES.to_string());
    parse_csv(&mime_types)
}

/// Parses RUSTFS_ADDED_EXCLUDE_COMPRESS_EXTENSIONS (comma-separated). Called once at first use via OnceLock.
pub(crate) fn parse_added_exclude_extensions() -> Vec<String> {
    env::var(ENV_ADDED_EXCLUDE_COMPRESS_EXTENSIONS)
        .ok()
        .map(|s| normalize_extensions(parse_csv(&s)))
        .unwrap_or_default()
}

fn parse_disk_compression_config() -> DiskCompressionConfig {
    DiskCompressionConfig {
        enabled: parse_disk_compression_enabled(),
        extensions: parse_disk_compression_extensions(),
        mime_types: parse_disk_compression_mime_types(),
        added_exclude_extensions: parse_added_exclude_extensions(),
    }
}

// Parsed once at first use, then reused for all disk compression checks.
static DISK_COMPRESSION_CONFIG: OnceLock<DiskCompressionConfig> = OnceLock::new();

// Some standard object extensions which we strictly dis-allow for compression.
#[rustfmt::skip]
pub const DISK_COMPRESSION_EXCLUDED_EXTENSIONS: &[&str] = &[
    // Compressed archives
    ".gz", ".bz2", ".rar", ".zip", ".7z", ".xz", ".zst", ".lz4", ".br", ".lzo", ".sz", ".tgz",
    // Images
    ".jpg", ".jpeg", ".png", ".gif", ".webp", ".avif", ".heic", ".heif", ".jxl",
    // Video
    ".mp4", ".mkv", ".mov", ".avi", ".wmv", ".flv", ".webm", ".m4v", ".mpeg", ".mpg",
    // Audio
    ".mp3", ".aac", ".ogg", ".flac", ".wma", ".m4a", ".opus",
    // Documents (internally compressed)
    ".pdf", ".docx", ".xlsx", ".pptx",
    // Package formats
    ".deb", ".rpm", ".jar", ".war", ".apk",
    // Web fonts
    ".woff", ".woff2",
];

// Some standard content-types which we strictly dis-allow for compression.
pub const DISK_COMPRESSION_EXCLUDED_CONTENT_TYPES: &[&str] = &[
    "video/*",
    "audio/*",
    "image/*",
    // Archive formats (compressed)
    "application/zip",
    "application/gzip",
    "application/x-gzip",
    "application/x-zip-compressed",
    "application/x-compress",
    "application/x-spoon",
    "application/x-rar-compressed",
    "application/x-7z-compressed",
    "application/x-bzip",
    "application/x-bzip2",
    "application/x-xz",
    "application/x-lzip",
    "application/x-lzma",
    "application/x-lzop",
    "application/zstd",
    "application/x-zstd",
    // Archive formats (uncompressed containers that are typically not further compressible)
    "application/x-tar",
    "application/tar",
    "application/pdf",
    "application/wasm",
    "font/*",
];

pub fn is_disk_compressible(headers: &http::HeaderMap, object_name: &str) -> bool {
    is_disk_compressible_with_config(headers, object_name, DISK_COMPRESSION_CONFIG.get_or_init(parse_disk_compression_config))
}

pub fn is_disk_compression_enabled() -> bool {
    DISK_COMPRESSION_CONFIG.get_or_init(parse_disk_compression_config).enabled
}

// Parsed once at first use, mirroring DISK_COMPRESSION_CONFIG.
static MULTIPART_DISK_COMPRESSION_ENABLED: OnceLock<bool> = OnceLock::new();

/// Whether multipart uploads may advertise disk compression. Requires the
/// regular disk-compression gates to pass as well; this is the staged-rollout
/// switch that keeps multipart compression dark during rolling upgrades from
/// builds whose decompressor was not yet resumable.
pub fn is_multipart_disk_compression_enabled() -> bool {
    *MULTIPART_DISK_COMPRESSION_ENABLED.get_or_init(|| {
        env::var(ENV_DISK_COMPRESSION_MULTIPART_ENABLED)
            .map(|s| matches!(s.to_ascii_lowercase().as_str(), "true" | "on" | "1"))
            .unwrap_or(false)
    })
}

fn is_disk_compressible_with_config(headers: &http::HeaderMap, object_name: &str, config: &DiskCompressionConfig) -> bool {
    // Check if disk compression is enabled (read once at first use, then fixed for process lifetime)
    if !config.enabled {
        debug!("Disk compression is disabled by environment variable");
        return false;
    }

    let content_type = headers.get("content-type").and_then(|s| s.to_str().ok()).unwrap_or("");

    if has_object_content_encoding(headers) {
        debug!("object_name: {} is already content-encoded; skipping disk compression", object_name);
        return false;
    }

    if has_string_suffix_in_slice(object_name, DISK_COMPRESSION_EXCLUDED_EXTENSIONS) {
        debug!("object_name: {} is not disk-compressible", object_name);
        return false;
    }

    if !config.added_exclude_extensions.is_empty() && has_string_suffix_in_slice(object_name, &config.added_exclude_extensions) {
        debug!("object_name: {} is not disk-compressible (added exclusion)", object_name);
        return false;
    }

    if !content_type.is_empty() && has_pattern(DISK_COMPRESSION_EXCLUDED_CONTENT_TYPES, content_type) {
        debug!("content_type: {} is not disk-compressible", content_type);
        return false;
    }

    if config.extensions.is_empty() && config.mime_types.is_empty() {
        return true;
    }

    if !config.extensions.is_empty() && has_string_suffix_in_slice(object_name, &config.extensions) {
        return true;
    }

    if !content_type.is_empty() && !config.mime_types.is_empty() && has_config_pattern(&config.mime_types, content_type) {
        return true;
    }

    debug!("object_name: {} does not match disk compression include filters", object_name);
    false
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_disk_compression_enabled() {
        temp_env::with_var(ENV_DISK_COMPRESSION_ENABLED, Some("true"), || {
            assert!(parse_disk_compression_enabled());
        });
        temp_env::with_var(ENV_DISK_COMPRESSION_ENABLED, Some("on"), || {
            assert!(parse_disk_compression_enabled());
        });
        temp_env::with_var(ENV_DISK_COMPRESSION_ENABLED, Some("false"), || {
            assert!(!parse_disk_compression_enabled());
        });
        temp_env::with_var(ENV_DISK_COMPRESSION_ENABLED, Some("FALSE"), || {
            assert!(!parse_disk_compression_enabled());
        });
        temp_env::with_var_unset(ENV_DISK_COMPRESSION_ENABLED, || {
            assert!(!parse_disk_compression_enabled());
        });
    }

    #[test]
    fn test_parse_disk_compression_includes() {
        temp_env::with_var(ENV_DISK_COMPRESSION_EXTENSIONS, Some(".txt,log, .json"), || {
            assert_eq!(parse_disk_compression_extensions(), [".txt", ".log", ".json"]);
        });
        temp_env::with_var(ENV_DISK_COMPRESSION_MIME_TYPES, Some("text/*, application/json"), || {
            assert_eq!(parse_disk_compression_mime_types(), ["text/*", "application/json"]);
        });
        temp_env::with_var_unset(ENV_DISK_COMPRESSION_EXTENSIONS, || {
            assert_eq!(
                parse_disk_compression_extensions(),
                [".txt", ".log", ".csv", ".json", ".tar", ".xml", ".bin"]
            );
        });
        temp_env::with_var_unset(ENV_DISK_COMPRESSION_MIME_TYPES, || {
            assert_eq!(
                parse_disk_compression_mime_types(),
                ["text/*", "application/json", "application/xml", "binary/octet-stream"]
            );
        });
    }

    fn test_config() -> DiskCompressionConfig {
        DiskCompressionConfig {
            enabled: true,
            extensions: normalize_extensions(parse_csv(DEFAULT_DISK_COMPRESS_EXTENSIONS)),
            mime_types: parse_csv(DEFAULT_DISK_COMPRESS_MIME_TYPES),
            added_exclude_extensions: Vec::new(),
        }
    }

    #[test]
    fn test_is_disk_compressible() {
        use http::HeaderMap;

        let config = test_config();
        let mut headers = HeaderMap::new();
        // Test non-compressible extensions - compressed archives
        headers.insert("content-type", "text/plain".parse().expect("valid content type"));
        assert!(!is_disk_compressible_with_config(&headers, "file.gz", &config));
        assert!(!is_disk_compressible_with_config(&headers, "file.zip", &config));
        assert!(!is_disk_compressible_with_config(&headers, "file.7z", &config));
        assert!(!is_disk_compressible_with_config(&headers, "file.zst", &config));
        assert!(!is_disk_compressible_with_config(&headers, "file.br", &config));
        assert!(!is_disk_compressible_with_config(&headers, "file.tgz", &config));

        // Test non-compressible extensions - images
        assert!(!is_disk_compressible_with_config(&headers, "file.jpg", &config));
        assert!(!is_disk_compressible_with_config(&headers, "file.jpeg", &config));
        assert!(!is_disk_compressible_with_config(&headers, "file.png", &config));
        assert!(!is_disk_compressible_with_config(&headers, "file.gif", &config));
        assert!(!is_disk_compressible_with_config(&headers, "file.webp", &config));
        assert!(!is_disk_compressible_with_config(&headers, "file.avif", &config));

        // Test non-compressible extensions - video
        assert!(!is_disk_compressible_with_config(&headers, "file.mp4", &config));
        assert!(!is_disk_compressible_with_config(&headers, "file.mkv", &config));
        assert!(!is_disk_compressible_with_config(&headers, "file.webm", &config));

        // Test non-compressible extensions - audio
        assert!(!is_disk_compressible_with_config(&headers, "file.mp3", &config));
        assert!(!is_disk_compressible_with_config(&headers, "file.aac", &config));
        assert!(!is_disk_compressible_with_config(&headers, "file.ogg", &config));
        assert!(!is_disk_compressible_with_config(&headers, "file.flac", &config));
        assert!(!is_disk_compressible_with_config(&headers, "file.opus", &config));

        // Test non-compressible extensions - documents
        assert!(!is_disk_compressible_with_config(&headers, "file.pdf", &config));
        assert!(!is_disk_compressible_with_config(&headers, "file.docx", &config));
        assert!(!is_disk_compressible_with_config(&headers, "file.xlsx", &config));
        assert!(!is_disk_compressible_with_config(&headers, "file.pptx", &config));

        // Test non-compressible extensions - packages
        assert!(!is_disk_compressible_with_config(&headers, "file.deb", &config));
        assert!(!is_disk_compressible_with_config(&headers, "file.rpm", &config));
        assert!(!is_disk_compressible_with_config(&headers, "file.jar", &config));

        // Test non-compressible extensions - web fonts
        assert!(!is_disk_compressible_with_config(&headers, "file.woff2", &config));

        // Test non-compressible content types
        headers.insert("content-type", "video/mp4".parse().expect("valid content type"));
        assert!(!is_disk_compressible_with_config(&headers, "file.txt", &config));

        headers.insert("content-type", "audio/mpeg".parse().expect("valid content type"));
        assert!(!is_disk_compressible_with_config(&headers, "file.txt", &config));

        headers.insert("content-type", "image/png".parse().expect("valid content type"));
        assert!(!is_disk_compressible_with_config(&headers, "file.txt", &config));

        headers.insert("content-type", "image/webp".parse().expect("valid content type"));
        assert!(!is_disk_compressible_with_config(&headers, "file.txt", &config));

        headers.insert("content-type", "application/zip".parse().expect("valid content type"));
        assert!(!is_disk_compressible_with_config(&headers, "file.txt", &config));

        headers.insert("content-type", "application/x-gzip".parse().expect("valid content type"));
        assert!(!is_disk_compressible_with_config(&headers, "file.txt", &config));

        headers.insert("content-type", "application/x-7z-compressed".parse().expect("valid content type"));
        assert!(!is_disk_compressible_with_config(&headers, "file.txt", &config));

        headers.insert("content-type", "application/pdf".parse().expect("valid content type"));
        assert!(!is_disk_compressible_with_config(&headers, "file.txt", &config));

        headers.insert("content-type", "font/woff2".parse().expect("valid content type"));
        assert!(!is_disk_compressible_with_config(&headers, "file.txt", &config));

        // Test compressible cases
        headers.insert("content-type", "text/plain".parse().expect("valid content type"));
        assert!(is_disk_compressible_with_config(&headers, "file.txt", &config));
        assert!(is_disk_compressible_with_config(&headers, "file.log", &config));

        headers.insert("content-type", "text/html".parse().expect("valid content type"));
        assert!(is_disk_compressible_with_config(&headers, "file.html", &config));

        headers.insert("content-type", "application/json".parse().expect("valid content type"));
        assert!(is_disk_compressible_with_config(&headers, "file.json", &config));

        headers.insert("content-type", "application/octet-stream".parse().expect("valid content type"));
        assert!(!is_disk_compressible_with_config(&headers, "file.data", &config));
    }

    #[test]
    fn test_content_encoding_skips_disk_compression() {
        use http::{HeaderMap, HeaderValue};

        let config = test_config();
        let mut headers = HeaderMap::new();
        headers.insert("content-type", "text/plain".parse().expect("valid content type"));

        headers.insert(http::header::CONTENT_ENCODING, HeaderValue::from_static("zstd"));
        assert!(!is_disk_compressible_with_config(&headers, "file.txt", &config));

        headers.insert(http::header::CONTENT_ENCODING, HeaderValue::from_static("gzip"));
        assert!(!is_disk_compressible_with_config(&headers, "file.txt", &config));

        headers.insert(http::header::CONTENT_ENCODING, HeaderValue::from_static("aws-chunked,gzip"));
        assert!(!is_disk_compressible_with_config(&headers, "file.txt", &config));

        headers.insert(http::header::CONTENT_ENCODING, HeaderValue::from_static("aws-chunked"));
        assert!(is_disk_compressible_with_config(&headers, "file.txt", &config));

        headers.insert(http::header::CONTENT_ENCODING, HeaderValue::from_static("identity"));
        assert!(is_disk_compressible_with_config(&headers, "file.txt", &config));
    }

    #[test]
    fn test_added_exclude_compress_extensions_parsing() {
        temp_env::with_var(ENV_ADDED_EXCLUDE_COMPRESS_EXTENSIONS, Some(".foo,.bar"), || {
            let added = parse_added_exclude_extensions();
            assert_eq!(added, [".foo", ".bar"]);
        });
        temp_env::with_var(ENV_ADDED_EXCLUDE_COMPRESS_EXTENSIONS, Some("baz, .qux"), || {
            let added = parse_added_exclude_extensions();
            assert_eq!(added, [".baz", ".qux"]);
        });
        temp_env::with_var_unset(ENV_ADDED_EXCLUDE_COMPRESS_EXTENSIONS, || {
            let added = parse_added_exclude_extensions();
            assert!(added.is_empty());
        });
    }

    #[test]
    fn test_added_exclude_compress_extensions_excludes_included_extension() {
        use http::HeaderMap;

        let mut headers = HeaderMap::new();
        headers.insert("content-type", "text/plain".parse().expect("valid content type"));
        let mut config = test_config();
        config.added_exclude_extensions = vec![".txt".to_string()];

        assert!(!is_disk_compressible_with_config(&headers, "file.txt", &config));
        assert!(is_disk_compressible_with_config(&headers, "file.log", &config));
    }

    #[test]
    fn test_empty_includes_compress_everything_except_exclusions() {
        use http::HeaderMap;

        let mut headers = HeaderMap::new();
        headers.insert("content-type", "application/octet-stream".parse().expect("valid content type"));
        let config = DiskCompressionConfig {
            enabled: true,
            extensions: Vec::new(),
            mime_types: Vec::new(),
            added_exclude_extensions: Vec::new(),
        };

        assert!(is_disk_compressible_with_config(&headers, "file.data", &config));
        assert!(!is_disk_compressible_with_config(&headers, "file.zip", &config));
    }
}